Question: Filter {@code extensionMatches} so that only those matches are left that don't cover or touch one of the {@code matches}.

@NotNull
  List<RuleMatch> getFilteredExtensionMatches(List<RuleMatch> matches, List<RemoteRuleMatch> extensionMatches) {
    List<RuleMatch> filteredExtMatches = new ArrayList<>();
    for (RemoteRuleMatch extensionMatch : extensionMatches) {
      if (!extensionMatch.isTouchedByOneOf(matches)) {
        AnalyzedSentence sentence = new AnalyzedSentence(new AnalyzedTokenReadings[]{});
        HiddenRule hiddenRule = new HiddenRule(extensionMatch.getLocQualityIssueType().orElse(null), extensionMatch.estimatedContextForSureMatch());
        RuleMatch hiddenRuleMatch = new RuleMatch(hiddenRule, sentence, extensionMatch.getErrorOffset(),
                extensionMatch.getErrorOffset()+extensionMatch.getErrorLength(), "(hidden message)");
        filteredExtMatches.add(hiddenRuleMatch);
      }
    }
    return filteredExtMatches;
  }

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

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

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


Question:
生成随机字符串 可用于生成随机密码等
@param int    $length   生成长度
@param string $alphabet 自定义生成字符集
@author : evalor <master@evalor.cn>
@return bool|string

static function character($length = 6, $alphabet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789')
    {
        /*
         * mt_srand() is to fix:
            mt_rand(0,100);
            if(pcntl_fork()){
                var_dump(mt_rand(0,100));
            }else{
                var_dump(mt_rand(0,100));
            }
         */
        mt_srand();
        // 重复字母表以防止生成长度溢出字母表长度
        if ($length >= strlen($alphabet)) {
            $rate = intval($length / strlen($alphabet)) + 1;
            $alphabet = str_repeat($alphabet, $rate);
        }

        // 打乱顺序返回
        return substr(str_shuffle($alphabet), 0, $length);
    }

protected function request($method, $command, $data = null)
    {
        if (!$this->isAttached()) {
            throw new NotAttachedException('No token');
        }
        $url = $this->getRequestUrl($command, !$data || $method === 'POST' ? [] : $data);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer '. $this->getSessionID()]);

        if ($method === 'POST' && !empty($data)) {
            $post = is_string($data) ? $data : http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $response = curl_exec($ch);

        if (curl_errno($ch) != 0) {
            $message = 'Server request failed: ' . curl_error($ch);
            throw new Exception($message);
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        list($contentType) = explode(';', curl_getinfo($ch, CURLINFO_CONTENT_TYPE));

        if ($contentType != 'application/json') {
            $message = 'Expected application/json response, got ' . $contentType;
            throw new Exception($message);
        }
        $data = json_decode($response, true);

        if ($httpCode == 403) {
            $this->clearToken();
            throw new NotAttachedException($data['error'] ?: $response, $httpCode);
        }

        if ($httpCode >= 400) {
            throw new Exception($data['error'] ?: $response, $httpCode);
        }

        return $data;
    }

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


Question:
Set the field that owns this handler.
@param owner The field this listener was added to (or null if being removed).

public void setOwner(ListenerOwner owner)
    {
        if (owner == null)
        {
            this.saveValue(m_recordOwnerCache);
            m_recordOwnerCache = null;
        }
        super.setOwner(owner);
        if (owner != null)
            this.retrieveValue();
    }

public function onGenerateResourceTracking(GenericDataEvent $event)
    {
        $data = $event->getData();
        $node = $data['resourceNode'];
        $user = $data['user'];
        $startDate = $data['startDate'];

        $logs = $this->resourceEvalManager->getLogsForResourceTracking(
            $node,
            $user,
            ['resource-read'],
            $startDate
        );
        $nbLogs = count($logs);

        if ($nbLogs > 0) {
            $this->om->startFlushSuite();
            $tracking = $this->resourceEvalManager->getResourceUserEvaluation($node, $user);
            $tracking->setDate($logs[0]->getDateLog());
            $tracking->setStatus(AbstractResourceEvaluation::STATUS_OPENED);
            $tracking->setNbOpenings($nbLogs);
            $this->om->persist($tracking);
            $this->om->endFlushSuite();
        }
        $event->stopPropagation();
    }

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


Question:
Format the args of the given Frame as a human readable html string

@param  Frame $frame
@return string the rendered html

public function dumpArgs(Frame $frame)
    {
        // we support frame args only when the optional dumper is available
        if (!$this->getDumper()) {
            return '';
        }

        $html = '';
        $numFrames = count($frame->getArgs());

        if ($numFrames > 0) {
            $html = '
';
            foreach ($frame->getArgs() as $j => $frameArg) {
                $html .= '
'. $this->dump($frameArg) .'
';
            }
            $html .= '
';
        }

        return $html;
    }

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

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

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

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

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

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

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

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


Question: Internal method used by subclasses to activate a bean

protected BeanO doActivation(EJBThreadData threadData, ContainerTx tx, BeanId beanId,
                                 boolean takeInvocationRef)
                    throws RemoteException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "doActivation",
                     new Object[] { tx, beanId,
                                   new Boolean(takeInvocationRef) });
        }

        BeanO bean = null;
        Throwable exception = null;
        MasterKey key = new MasterKey(beanId);
        boolean activate = false;
        boolean pushedCallbackBeanO = false;

        try {

            synchronized (locks.getLock(key)) {

                if ((bean = (BeanO) cache.find(key)) == null)
                {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Bean not in cache");

                    bean = beanId.getHome().createBeanO(threadData, tx, beanId); // d630940
                    pushedCallbackBeanO = true;
                    cache.insert(key, bean);
                    bean.ivCacheKey = key; // d199233
                    activate = true;
                }
                else
                {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Found bean in cache");

                    // Set the found BeanO as the 'Callback' BeanO, as this is the
                    // BeanO that is becoming the active beanO for the thread.
                    // This will allow methods called by customer code (like Timer
                    // methods) to determine the state of the BeanO that is making
                    // the call.                                              d168509
                    threadData.pushCallbackBeanO(bean); // d630940
                    pushedCallbackBeanO = true;
                }
            }

            boolean pin = false;

            if (activate) {
                bean.activate(beanId, tx); // d114677
            }

            pin = bean.enlist(tx); // d114677

            if (takeInvocationRef && pin) {
                // We need to take an additional reference
                cache.pin(key);
            } else if (!takeInvocationRef && !pin) {
                // Need to drop reference taken by find or insert
                cache.unpin(key);
            }

        } catch (RemoteException e) {

            FFDCFilter.processException(e, CLASS_NAME + ".doActivation", "123", this);
            exception = e;
            throw e;

        } catch (RuntimeException e) {

            FFDCFilter.processException(e, CLASS_NAME + ".doActivation", "129", this);
            exception = e;
            throw e;

        } finally {

            if (exception != null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                    Tr.event(tc, "doActivation: exception raised", exception);
            }

            if (exception != null && bean != null)
            {
                if (pushedCallbackBeanO)
                {
                    threadData.popCallbackBeanO();
                }

                bean.destroy();

                if (activate) {
                    // Synchronize to insure that a temp pin obtained by getBean
                    // doesn't cause the remove to fail due to too many pins. PQ53065
                    synchronized (locks.getLock(key)) {
                        cache.remove(key, true);
                        bean.ivCacheKey = null; // d199233
                    }
                }
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(tc, "doActivation", bean);
        }

        return bean;
    }

@Override
  public void jobAdded(JobInProgress job) {
    synchronized (jobInitQueue) {
      jobInitQueue.add(job);
      resortInitQueue();
      jobInitQueue.notifyAll();
    }

  }

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


Question:
@param string $name
@param bool   $validate

@return WorkflowDescriptor
@throws FactoryException

public function getWorkflow($name, $validate = true)
    {
        $name = (string)$name;
        if (!array_key_exists($name, $this->workflows)) {
            $errMsg = sprintf('Нет workflow с именем %s', $name);
            throw new FactoryException($errMsg);
        }
        $c = $this->workflows[$name];

        if (null !== $c->descriptor) {
            if ($this->reload && file_exists($c->url) && (filemtime($c->url) > $c->lastModified)) {
                $c->lastModified = filemtime($c->url);
                $this->loadWorkflow($c, $validate);
            }
        } else {
            $this->loadWorkflow($c, $validate);
        }

        $c->descriptor->setName($name);

        return $c->descriptor;
    }

public function execute(Input $input, Output $output)
    {
        $connector = $input->getArgument('connector') ?: $this->app->config->get('queue.connector', 'sync');

        $queue = $input->getOption('queue') ?: $this->app->config->get("queue.{$connector}", 'default');
        $delay = $input->getOption('delay');
        $sleep = $input->getOption('sleep');
        $tries = $input->getOption('tries');

        $this->listenForEvents();

        if ($input->getOption('once')) {
            $this->worker->runNextJob($connector, $queue, $delay, $sleep, $tries);
        } else {
            $memory  = $input->getOption('memory');
            $timeout = $input->getOption('timeout');
            $this->worker->daemon($connector, $queue, $delay, $sleep, $tries, $memory, $timeout);
        }
    }

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


Question:
/*
For reading we support both PKCS#1 and PKCS#8. If we find a private key,
we just take the public component of it and use that.

function read(buf, options, forceType) {
	var input = buf;
	if (typeof (buf) !== 'string') {
		assert.buffer(buf, 'buf');
		buf = buf.toString('ascii');
	}

	var lines = buf.trim().split(/[\r\n]+/g);

	var m;
	var si = -1;
	while (!m && si < lines.length) {
		m = lines[++si].match(/*JSSTYLED*/
		    /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
	}
	assert.ok(m, 'invalid PEM header');

	var m2;
	var ei = lines.length;
	while (!m2 && ei > 0) {
		m2 = lines[--ei].match(/*JSSTYLED*/
		    /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
	}
	assert.ok(m2, 'invalid PEM footer');

	/* Begin and end banners must match key type */
	assert.equal(m[2], m2[2]);
	var type = m[2].toLowerCase();

	var alg;
	if (m[1]) {
		/* They also must match algorithms, if given */
		assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
		alg = m[1].trim();
	}

	lines = lines.slice(si, ei + 1);

	var headers = {};
	while (true) {
		lines = lines.slice(1);
		m = lines[0].match(/*JSSTYLED*/
		    /^([A-Za-z0-9-]+): (.+)$/);
		if (!m)
			break;
		headers[m[1].toLowerCase()] = m[2];
	}

	/* Chop off the first and last lines */
	lines = lines.slice(0, -1).join('');
	buf = Buffer.from(lines, 'base64');

	var cipher, key, iv;
	if (headers['proc-type']) {
		var parts = headers['proc-type'].split(',');
		if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
			if (typeof (options.passphrase) === 'string') {
				options.passphrase = Buffer.from(
				    options.passphrase, 'utf-8');
			}
			if (!Buffer.isBuffer(options.passphrase)) {
				throw (new errors.KeyEncryptedError(
				    options.filename, 'PEM'));
			} else {
				parts = headers['dek-info'].split(',');
				assert.ok(parts.length === 2);
				cipher = parts[0].toLowerCase();
				iv = Buffer.from(parts[1], 'hex');
				key = utils.opensslKeyDeriv(cipher, iv,
				    options.passphrase, 1).key;
			}
		}
	}

	if (alg && alg.toLowerCase() === 'encrypted') {
		var eder = new asn1.BerReader(buf);
		var pbesEnd;
		eder.readSequence();

		eder.readSequence();
		pbesEnd = eder.offset + eder.length;

		var method = eder.readOID();
		if (method !== OID_PBES2) {
			throw (new Error('Unsupported PEM/PKCS8 encryption ' +
			    'scheme: ' + method));
		}

		eder.readSequence();	/* PBES2-params */

		eder.readSequence();	/* keyDerivationFunc */
		var kdfEnd = eder.offset + eder.length;
		var kdfOid = eder.readOID();
		if (kdfOid !== OID_PBKDF2)
			throw (new Error('Unsupported PBES2 KDF: ' + kdfOid));
		eder.readSequence();
		var salt = eder.readString(asn1.Ber.OctetString, true);
		var iterations = eder.readInt();
		var hashAlg = 'sha1';
		if (eder.offset < kdfEnd) {
			eder.readSequence();
			var hashAlgOid = eder.readOID();
			hashAlg = OID_TO_HASH[hashAlgOid];
			if (hashAlg === undefined) {
				throw (new Error('Unsupported PBKDF2 hash: ' +
				    hashAlgOid));
			}
		}
		eder._offset = kdfEnd;

		eder.readSequence();	/* encryptionScheme */
		var cipherOid = eder.readOID();
		cipher = OID_TO_CIPHER[cipherOid];
		if (cipher === undefined) {
			throw (new Error('Unsupported PBES2 cipher: ' +
			    cipherOid));
		}
		iv = eder.readString(asn1.Ber.OctetString, true);

		eder._offset = pbesEnd;
		buf = eder.readString(asn1.Ber.OctetString, true);

		if (typeof (options.passphrase) === 'string') {
			options.passphrase = Buffer.from(
			    options.passphrase, 'utf-8');
		}
		if (!Buffer.isBuffer(options.passphrase)) {
			throw (new errors.KeyEncryptedError(
			    options.filename, 'PEM'));
		}

		var cinfo = utils.opensshCipherInfo(cipher);

		cipher = cinfo.opensslName;
		key = utils.pbkdf2(hashAlg, salt, iterations, cinfo.keySize,
		    options.passphrase);
		alg = undefined;
	}

	if (cipher && key && iv) {
		var cipherStream = crypto.createDecipheriv(cipher, key, iv);
		var chunk, chunks = [];
		cipherStream.once('error', function (e) {
			if (e.toString().indexOf('bad decrypt') !== -1) {
				throw (new Error('Incorrect passphrase ' +
				    'supplied, could not decrypt key'));
			}
			throw (e);
		});
		cipherStream.write(buf);
		cipherStream.end();
		while ((chunk = cipherStream.read()) !== null)
			chunks.push(chunk);
		buf = Buffer.concat(chunks);
	}

	/* The new OpenSSH internal format abuses PEM headers */
	if (alg && alg.toLowerCase() === 'openssh')
		return (sshpriv.readSSHPrivate(type, buf, options));
	if (alg && alg.toLowerCase() === 'ssh2')
		return (rfc4253.readType(type, buf, options));

	var der = new asn1.BerReader(buf);
	der.originalInput = input;

	/*
	 * All of the PEM file types start with a sequence tag, so chop it
	 * off here
	 */
	der.readSequence();

	/* PKCS#1 type keys name an algorithm in the banner explicitly */
	if (alg) {
		if (forceType)
			assert.strictEqual(forceType, 'pkcs1');
		return (pkcs1.readPkcs1(alg, type, der));
	} else {
		if (forceType)
			assert.strictEqual(forceType, 'pkcs8');
		return (pkcs8.readPkcs8(alg, type, der));
	}
}

function generateKeyPair (pub, prv) {
  try {
    mkdirp.sync(path.dirname(pub))
    mkdirp.sync(path.dirname(prv))

    childProcess.execFileSync('openssl', [
      'genrsa',
      '-out',
      prv,
      '4096'
    ], {
      stdio: 'ignore'
    })

    childProcess.execFileSync('openssl', [
      'rsa',
      '-pubout',
      '-in',
      prv,
      '-out',
      pub
    ], {
      stdio: 'ignore'
    })
  } catch (e) {
    throw new Error(
      'Failed to generate keys using OpenSSL. Please ensure you have OpenSSL ' +
      'installed and configured on your system.'
    )
  }
}

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


Question:
Executes "DoCapture". Returns response array from PayPal

@param \OxidEsales\PayPalModule\Model\PayPalRequest\PayPalRequest $request request

@return \OxidEsales\PayPalModule\Model\Response\Response

public function doCapture($request)
    {
        $caller = $this->getCaller();
        $caller->setRequest($request);

        $response = oxNew(\OxidEsales\PayPalModule\Model\Response\ResponseDoCapture::class);
        $response->setData($caller->call('DoCapture'));

        return $response;
    }

public function registerPaymentMethodMapper(PaymentMethodMapperInterface $paymentMethodMapper)
    {
        $paymentMethodMapper->setStandardParameter($this->standardParameter);
        $paymentMethodMapper->setSequenceNumberProvider($this->sequenceNumberProvider);
        $paymentMethodMapper->setUrlHmacGenerator($this->urlHmacGenerator);
        $this->registeredMethodMappers[$paymentMethodMapper->getName()] = $paymentMethodMapper;
    }

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


Question: // AllowNsOp is shorthand for AllowNamespaceOperation

func (a *ACL) AllowNsOp(ns string, op string) bool {
	return a.AllowNamespaceOperation(ns, op)
}

public base_response save_config() throws Exception
	{
		nsconfig resource = new nsconfig();
		options option = new options();
		option.set_action("save");
		base_response result = resource.perform_operation(this, option);
		return result;
	}

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


Question:
Set the value of [contact_id_version] column.

@param      int $v new value
@return   \Dealer\Model\DealerContactInfoVersion The current object (for fluent API support)

public function setContactIdVersion($v)
    {
        if ($v !== null) {
            $v = (int) $v;
        }

        if ($this->contact_id_version !== $v) {
            $this->contact_id_version = $v;
            $this->modifiedColumns[DealerContactInfoVersionTableMap::CONTACT_ID_VERSION] = true;
        }

        return $this;
    }

public function change()
    {
        $tableName = 'language_translations';
        if (!$this->hasTable($tableName)) {
            $tableName = 'translations';
        }

        $table = $this->table($tableName);
        if ($table->hasColumn('created')) {
            $table->changeColumn('created', 'datetime', [
                'default' => null,
                'null' => true
            ]);
        }
        if ($table->hasColumn('modified')) {
            $table->changeColumn('modified', 'datetime', [
                'default' => null,
                'null' => true
            ]);
        }
        $table->save();
    }

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


Question: // Runs command with stdout and stderr pipes connected to process

func (h OsHelperImpl) RunCommand(executable string, args ...string) (string, error) {
	cmd := exec.Command(executable, args...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return string(out), err
	}
	return string(out), nil
}

@Task(name = "createStream", version = "1.0", resource = "{scope}/{stream}")
    public CompletableFuture<CreateStreamStatus.Status> createStream(String scope, String stream, StreamConfiguration config, long createTimestamp) {
        return execute(
                new Resource(scope, stream),
                new Serializable[]{scope, stream, config, createTimestamp},
                () -> createStreamBody(scope, stream, config, createTimestamp));
    }

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


Question: #line 967 "../smarty/lexer/smarty_internal_templateparser.y"

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

def apply_T9(word):
    ''''''
    WORD = word
    index = 0
    offset = 0

    for iu in iu_sequences(WORD):
        if iu.start(1) != index:
            i = iu.start(1) + 1 + offset
            WORD = WORD[:i] + '.' + WORD[i:]
            index = iu.start(1)
            offset += 1

    RULE = ' T9' if word != WORD else ''

    return WORD, RULE

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


Question:
Gets the user with the specified ID.

@param id the id of the required user
@return the user

protected User getUser(int id) {
    User user = users().get(id);
    if (user == null) {
      throw new IllegalStateException(format("Could not find user corresponding to id [%d]", id));
    }

    return user;
  }

protected function assert_rating_matches($expected, $stored) {
        $this->assertEquals($expected->rating, $stored->rating);
        $this->assertEquals($expected->userid, $stored->author);
    }

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


Question:
Get the current line from $analysisResponse and returns it.
Moves the internal offset pointer.

private function popLine() {
		$newLinePos = strpos($this->analysisResponse, "\n", $this->analysisOffset);

		if ($newLinePos === false) {
			throw new \Exception("End of file reached!");
		}

		$line = substr($this->analysisResponse, $this->analysisOffset, ($newLinePos - $this->analysisOffset));
        $this->analysisOffset = $newLinePos + 1;
		return $line;
	}

function copyAndOffsetMapping(existingMapping) {
    var column     = getColumnAfter(existingMapping.generatedLine - 1, existingMapping.generatedColumn);
    var newMapping = {
      generated: {
        line  : existingMapping.generatedLine,
        column: column
      }
    };
    if (existingMapping.source) {
      newMapping.source   = existingMapping.source;
      newMapping.original = {
        line  : existingMapping.originalLine,
        column: existingMapping.originalColumn
      };
      if (existingMapping.name) {
        newMapping.name = existingMapping.name;
      }
    }
    generator.addMapping(newMapping);
  }

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


Question:
startsWithPackage.

@param pkgs a {@link java.lang.String} object.
@return a boolean.

public boolean startsWithPackage(String... pkgs) {
        for (String st : pkgs) {
            if (!st.endsWith(".")) st += ".";
            String className = getClassName();
            if (className.startsWith(st)) {
                return true;
            }
        }
        return false;
    }

public Type[] getParameterTypes() {
        Type[] types = new Type[parameterNames.size()];
        for (int i = 0; i < types.length; i++) {
            types[i] = String.class;
        }

        return types;
    }

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


Question:
Lowest common ancestor sequence assignment using the One Codex API.
    Streams annotated records to stdout in fasta format.
    Taxa assigned using the One Codex 31mer LCA database.

def kmer_lca(seqs_path: 'path to (optionally gzipped) fasta/fastq input',
             fastq: 'input is fastq; disable autodetection' = False,
             progress: 'show progress bar (sent to stderr)' = False):
    '''

    '''
    conf = tictax.config()
    records = tictax.parse_seqs(seqs_path, fastq)
    print('Classifying sequences…', file=sys.stderr)
    asyncio.get_event_loop().run_until_complete(tictax.oc_classify(records,
                                                                   conf['one_codex_api_key'],
                                                                   progress,
                                                                   True))
    print('✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌', file=sys.stderr)

func SetOrdererEnv(cmd *cobra.Command, args []string) {
	// read in the legacy logging level settings and, if set,
	// notify users of the FABRIC_LOGGING_SPEC env variable
	var loggingLevel string
	if viper.GetString("logging_level") != "" {
		loggingLevel = viper.GetString("logging_level")
	} else {
		loggingLevel = viper.GetString("logging.level")
	}
	if loggingLevel != "" {
		mainLogger.Warning("CORE_LOGGING_LEVEL is no longer supported, please use the FABRIC_LOGGING_SPEC environment variable")
	}
	// need to init logging here as cobra does not currently support
	// chaining PersistentPreRun functions
	loggingSpec := os.Getenv("FABRIC_LOGGING_SPEC")
	flogging.InitFromSpec(loggingSpec)
	// set the orderer environment from flags
	viper.Set("orderer.tls.rootcert.file", caFile)
	viper.Set("orderer.tls.clientKey.file", keyFile)
	viper.Set("orderer.tls.clientCert.file", certFile)
	viper.Set("orderer.address", OrderingEndpoint)
	viper.Set("orderer.tls.serverhostoverride", ordererTLSHostnameOverride)
	viper.Set("orderer.tls.enabled", tlsEnabled)
	viper.Set("orderer.tls.clientAuthRequired", clientAuth)
	viper.Set("orderer.client.connTimeout", connTimeout)
}

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


Question:
Remove feature names from the feature lists in a composite distance
    function.

def _scrub_composite_distance_features(distance, feature_blacklist):

    dist_out = []

    for i, d in enumerate(distance):
        ftrs, dist, weight = d
        new_ftrs = [x for x in ftrs if x not in feature_blacklist]
        if len(new_ftrs) > 0:
            dist_out.append([new_ftrs, dist, weight])

    return dist_out

func (statement *Statement) Omit(columns ...string) {
	newColumns := col2NewCols(columns...)
	for _, nc := range newColumns {
		statement.columnMap[nc] = false
	}
	statement.OmitStr = statement.Engine.Quote(strings.Join(newColumns, statement.Engine.Quote(", ")))
}

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


Question:
Remote TLS processing - one address:port per line
        :param data:
        :param name:
        :return:

def process_tls(self, data, name):

        ret = []
        try:
            lines = [x.strip() for x in data.split('\n')]
            for idx, line in enumerate(lines):
                if line == '':
                    continue

                sub = self.process_host(line, name, idx)
                if sub is not None:
                    ret.append(sub)

        except Exception as e:
            logger.error('Error in file processing %s : %s' % (name, e))
            self.roca.trace_logger.log(e)
        return ret

function execute(cmd, args, cb) {
  if(typeof args === 'function') {
    cb = args;
    args = null;
  }
  var arr = [cmd].concat(args || []);
  if(typeof cb === 'function') {
    this.once('reply', cb);
  }

  // sending over tcp
  if(this.tcp) {
    this.encoder.write(arr);
  // connected to a server within this process
  }else{
    this.socket.write(arr);
  }
}

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


Question: // Add SG rules for a given NLB

func (c *Cloud) updateInstanceSecurityGroupsForNLB(mappings []nlbPortMapping, instances map[InstanceID]*ec2.Instance, lbName string, clientCidrs []string) error {
	if c.cfg.Global.DisableSecurityGroupIngress {
		return nil
	}

	vpcCidrBlocks, err := c.getVpcCidrBlocks()
	if err != nil {
		return err
	}

	// Unlike the classic ELB, NLB does not have a security group that we can
	// filter against all existing groups to see if they allow access. Instead
	// we use the IpRange.Description field to annotate NLB health check and
	// client traffic rules

	// Get the actual list of groups that allow ingress for the load-balancer
	var actualGroups []*ec2.SecurityGroup
	{
		// Server side filter
		describeRequest := &ec2.DescribeSecurityGroupsInput{}
		filters := []*ec2.Filter{
			newEc2Filter("ip-permission.protocol", "tcp"),
		}
		describeRequest.Filters = c.tagging.addFilters(filters)
		response, err := c.ec2.DescribeSecurityGroups(describeRequest)
		if err != nil {
			return fmt.Errorf("Error querying security groups for NLB: %q", err)
		}
		for _, sg := range response {
			if !c.tagging.hasClusterTag(sg.Tags) {
				continue
			}
			actualGroups = append(actualGroups, sg)
		}

		// client-side filter
		// Filter out groups that don't have IP Rules we've annotated for this service
		actualGroups = filterForIPRangeDescription(actualGroups, lbName)
	}

	taggedSecurityGroups, err := c.getTaggedSecurityGroups()
	if err != nil {
		return fmt.Errorf("Error querying for tagged security groups: %q", err)
	}

	externalTrafficPolicyIsLocal := false
	trafficPorts := []int64{}
	for i := range mappings {
		trafficPorts = append(trafficPorts, mappings[i].TrafficPort)
		if mappings[i].TrafficPort != mappings[i].HealthCheckPort {
			externalTrafficPolicyIsLocal = true
		}
	}

	healthCheckPorts := trafficPorts
	// if externalTrafficPolicy is Local, all listeners use the same health
	// check port
	if externalTrafficPolicyIsLocal && len(mappings) > 0 {
		healthCheckPorts = []int64{mappings[0].HealthCheckPort}
	}

	desiredGroupIds := []string{}
	// Scan instances for groups we want open
	for _, instance := range instances {
		securityGroup, err := findSecurityGroupForInstance(instance, taggedSecurityGroups)
		if err != nil {
			return err
		}

		if securityGroup == nil {
			klog.Warningf("Ignoring instance without security group: %s", aws.StringValue(instance.InstanceId))
			continue
		}

		id := aws.StringValue(securityGroup.GroupId)
		if id == "" {
			klog.Warningf("found security group without id: %v", securityGroup)
			continue
		}

		desiredGroupIds = append(desiredGroupIds, id)
	}

	// Run once for Client traffic
	err = c.updateInstanceSecurityGroupsForNLBTraffic(actualGroups, desiredGroupIds, trafficPorts, lbName, clientCidrs, true)
	if err != nil {
		return err
	}

	// Run once for health check traffic
	err = c.updateInstanceSecurityGroupsForNLBTraffic(actualGroups, desiredGroupIds, healthCheckPorts, lbName, vpcCidrBlocks, false)
	if err != nil {
		return err
	}

	return nil
}

@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType)
	{
		switch (featureID)
		{
			case XbasePackage.XBINARY_OPERATION__LEFT_OPERAND:
				return getLeftOperand();
			case XbasePackage.XBINARY_OPERATION__RIGHT_OPERAND:
				return getRightOperand();
			case XbasePackage.XBINARY_OPERATION__REASSIGN_FIRST_ARGUMENT:
				return isReassignFirstArgument();
		}
		return super.eGet(featureID, resolve, coreType);
	}

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


Question:
Process a currency definition.

@param row record from XER file

private void processCurrency(Row row)
   {
      String currencyName = row.getString("curr_short_name");
      DecimalFormatSymbols symbols = new DecimalFormatSymbols();
      symbols.setDecimalSeparator(row.getString("decimal_symbol").charAt(0));
      symbols.setGroupingSeparator(row.getString("digit_group_symbol").charAt(0));
      DecimalFormat nf = new DecimalFormat();
      nf.setDecimalFormatSymbols(symbols);
      nf.applyPattern("#.#");
      m_currencyMap.put(currencyName, nf);

      if (currencyName.equalsIgnoreCase(m_defaultCurrencyName))
      {
         m_numberFormat = nf;
         m_defaultCurrencyData = row;
      }
   }

func (itr *seriesQueryAdapterIterator) Next() (*query.FloatPoint, error) {
	for {
		// Read next series element.
		e, err := itr.itr.Next()
		if err != nil {
			return nil, err
		} else if e.SeriesID.IsZero() {
			return nil, nil
		}

		// Skip if key has been tombstoned.
		seriesKey := itr.sfile.SeriesKey(e.SeriesID)
		if len(seriesKey) == 0 {
			continue
		}

		// Convert to a key.
		name, tags := ParseSeriesKey(seriesKey)
		key := string(models.MakeKey(name, tags))

		// Write auxiliary fields.
		for i, f := range itr.opt.Aux {
			switch f.Val {
			case "key":
				itr.point.Aux[i] = key
			}
		}
		return &itr.point, nil
	}
}

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


Question:
Return a possible next word after ``word1`` and ``word2``, or ``None``
        if there's no possibility.

def _get(self, word1, word2):

        key = self._WSEP.join([self._sanitize(word1), self._sanitize(word2)])
        key = key.lower()
        if key not in self._db:
            return

        return sample(self._db[key], 1)[0]

protected function get_position_of_relevant_code(PHP_CodeSniffer_File $file, $pointer) {
        // Advance through tokens until we find some real code.
        $tokens = $file->getTokens();
        $relevantcodefound = false;
        $ignoredtokens = array_merge([T_OPEN_TAG, T_SEMICOLON], PHP_CodeSniffer_Tokens::$emptyTokens);

        do {
            // Find some non-whitespace (etc) code.
            $pointer = $file->findNext($ignoredtokens, $pointer, null, true);
            if ($tokens[$pointer]['code'] === T_NAMESPACE || $tokens[$pointer]['code'] === T_USE) {
                // Namespace definitions are allowed before anything else, jump to end of namspace statement.
                $pointer = $file->findEndOfStatement($pointer + 1);
            } else if ($tokens[$pointer]['code'] === T_STRING && $tokens[$pointer]['content'] == 'define') {
                // Some things like AJAX_SCRIPT NO_MOODLE_COOKIES need to be defined before config inclusion.
                // Jump to end of define().
                $pointer = $file->findEndOfStatement($pointer + 1);
            } else {
                $relevantcodefound = true;
            }
        } while (!$relevantcodefound);

        return $pointer;
    }

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


Question:
No lookup specified for the field. Attempt to load relationship from
original POJOs. Throw an InternalServerErrorException if the field is an
Iterable and null.

private Set<Resource> fetchRelationFromEntity(IncludeRequest request, List<Resource> sourceResources, ResourceField
			relationshipField, boolean allowLookup, boolean fetchRelatedEntity, boolean mustInclude) {
		Set<Resource> loadedResources = new HashSet<>();
		for (Resource sourceResource : sourceResources) {
			ResourceIdentifier id = sourceResource.toIdentifier();

			Object sourceEntity = request.getEntity(id);
			if (sourceEntity != null && !(sourceEntity instanceof Resource)) {

				Object relatedEntity = null;
				if (fetchRelatedEntity) {
					relatedEntity = relationshipField.getAccessor().getValue(sourceEntity);
					if (!allowLookup && Iterable.class.isAssignableFrom(relationshipField.getType()) && relatedEntity == null) {
						// note that single-valued relations are allowed to be null
						throw new InternalServerErrorException(
								id + " relationship field collection '" + relationshipField.getJsonName()
										+ "' can not be null. Either set the relationship as an empty "
										+ Iterable.class.getCanonicalName() + " or use LookupIncludeBehavior.AUTOMATICALLY_ALWAYS");
					}
				}

				// attempt to work with full relationship and fallback to relationshipId where possible
				if (relatedEntity != null) {
					List<Resource> relatedResources =
							request.setupRelation(sourceResource, relationshipField, relatedEntity);
					loadedResources.addAll(relatedResources);
				} else if (relationshipField.hasIdField()) {
					Object relatedEntityID = relationshipField.getIdAccessor().getValue(sourceEntity);
					request.setupRelationId(sourceResource, relationshipField, relatedEntityID);
					if (fetchRelatedEntity && relatedEntityID != null && !allowLookup && mustInclude) {
						throw new IllegalStateException("inconsistent relationship '" + relationshipField.getUnderlyingName()
								+ "' for " + id + ", id "
								+ "set to " + relatedEntityID + ", but related object is null and lookup disabled");
					}
				}
			}
		}
		return loadedResources;
	}

def retrieve(self, request, project, pk=None):

        job_id, bug_id = map(int, pk.split("-"))
        job = Job.objects.get(repository__name=project, id=job_id)
        try:
            bug_job_map = BugJobMap.objects.get(job=job, bug_id=bug_id)
            serializer = BugJobMapSerializer(bug_job_map)

            return Response(serializer.data)
        except BugJobMap.DoesNotExist:
            return Response("Object not found", status=HTTP_404_NOT_FOUND)

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


Question:
// RemoteIP extracts the remote IP of the request, taking into
// account proxy headers.

func RemoteIP(r *http.Request) string {
	addr := RemoteAddr(r)

	// Try parsing it as "IP:port"
	if ip, _, err := net.SplitHostPort(addr); err == nil {
		return ip
	}

	return addr
}

def web_modification_time(local_url)
      resp = nil
      Net::HTTP.start(local_url.host, 80) do |http|
        resp = http.head(local_url.path)
      end
      resp['Last-Modified'].nil? ? Time.at(0) : Time.parse(resp['Last-Modified'])
    end

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


Question: // NewActivityTaskPoller returns an ActivityTaskPoller.

func NewActivityTaskPoller(awc ActivityWorkerClient, domain string, identity string, taskList string) *ActivityTaskPoller {
	return &ActivityTaskPoller{
		client:   awc,
		Domain:   domain,
		Identity: identity,
		TaskList: taskList,
	}
}

public void setReturnType(String type) {
		if (!Strings.isEmpty(type)
				&& !Objects.equals("void", type)
				&& !Objects.equals(Void.class.getName(), type)) {
			this.sarlAction.setReturnType(newTypeRef(container, type));
		} else {
			this.sarlAction.setReturnType(null);
		}
	}

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


Question: Store given transition in the backend

def store_transition(self, frame, action, reward, done, extra_info=None):

        self.backend.store_transition(frame=frame, action=action, reward=reward, done=done, extra_info=extra_info)

function(controller, qp) {
        var value = get(controller, qp.prop);
        this.router._queuedQPChanges[qp.fprop] = value;
        run.once(this, this._fireQueryParamTransition);
      }

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


Question:
Mapping result value of promise to another value

@param res mapping function
@param <R> destination type
@return promise

@ObjectiveCName("map:")
    public <R> Promise<R> map(final Function<T, R> res) {
        final Promise<T> self = this;
        return new Promise<>((PromiseFunc<R>) resolver -> {
            self.then(t -> {
                R r;
                try {
                    r = res.apply(t);
                } catch (Exception e) {
                    e.printStackTrace();
                    resolver.tryError(e);
                    return;
                }
                resolver.tryResult(r);
            });
            self.failure(e -> resolver.error(e));
        });
    }

public void marshall(InferenceSpecification inferenceSpecification, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(inferenceSpecification.getContainers(), CONTAINERS_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedTransformInstanceTypes(), SUPPORTEDTRANSFORMINSTANCETYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedRealtimeInferenceInstanceTypes(), SUPPORTEDREALTIMEINFERENCEINSTANCETYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedContentTypes(), SUPPORTEDCONTENTTYPES_BINDING);
            protocolMarshaller.marshall(inferenceSpecification.getSupportedResponseMIMETypes(), SUPPORTEDRESPONSEMIMETYPES_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:
Return array with Doctrine expressions

@param array $filterConfigurations
@param Query $baseQuery
@return array
@throws MigrationException

public function getFilterExpressions(array $filterConfigurations, Query $baseQuery): array
    {
        $filterExpressions = [];
        foreach ($filterConfigurations as $filterConfiguration) {
            $filterObject = $this->constructFilterObject($filterConfiguration);
            if ($filterObject instanceof DoctrineFilterInterface) {
                foreach ($filterObject->getFilterExpressions($baseQuery) as $filterExpression) {
                    $filterExpressions[] = $filterExpression;
                }
            }
        }
        return $filterExpressions;
    }

public function fetchData($storeId = Store::DEFAULT_STORE_ID, $categoryIds = [])
    {
        $connection = $this->getConnection('read');
        $table = $this->getTable('url_rewrite');
        $select = $connection
            ->select()
            ->from($table, ['entity_id', 'request_path'])
            ->where('entity_type = ?', 'category')
            ->where('redirect_type = ?', 0)
            ->where('store_id = ?', $storeId)
            ->where('entity_id IN (' . implode(',', $categoryIds) . ')');

        return $connection->fetchPairs($select);
    }

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


Question:
Calculates the percent the inputed value is in relation to the
        list of other values.

        :param      value  | <variant>
                    values | [<variant>, ..]

        :return     <float> 0.0 - 1.0

def percentOfTotal(self, value, values):

        try:
            return float(value) / sum(values)
        except (ZeroDivisionError, TypeError, ValueError):
            return 0.0

public static function format($value)
    {
        $formatFunction = Config::get('shop.display_price_number_format') ?: function($price) { return number_format($price, 2); };
        return preg_replace(
            [
                '/:symbol/',
                '/:price/',
                '/:currency/'
            ],
            [
                Config::get('shop.currency_symbol'),
                $formatFunction($value),
                Config::get('shop.currency')
            ],
            Config::get('shop.display_price_format')
        );
    }

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


Question: matches @return/@returns {type} [ return.name ] ...

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

public ResultResponseUtil status(IReturnCode iReturnCode) {
        this.setCode(iReturnCode.getCode());
        this.setMsg(iReturnCode.getMsg());
        return this;
    }

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


Question: // SetChannelId sets the ChannelId field's value.

func (s *StopChannelInput) SetChannelId(v string) *StopChannelInput {
	s.ChannelId = &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:
Whether or not the supplied class can accept dynamic properties.

    @rtype: C{bool}
    @since: 0.5

def is_class_sealed(klass):

    mro = inspect.getmro(klass)
    new = False

    if mro[-1] is object:
        mro = mro[:-1]
        new = True

    for kls in mro:
        if new and '__dict__' in kls.__dict__:
            return False

        if not hasattr(kls, '__slots__'):
            return False

    return True

public function addVar($name, $type = '', $description = '')
    {
        $this->var_types[$name] = $type == '' ? $type : $type.' ';
        $this->var_descriptions[$name] = $description;
        return $this;
    }

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


Question:
Applies the currently active scope to a repository.

@param ExtendedRepositoryInterface $repository
@param null|string                 $scope        active if not given
@return $this

protected function applyScope(ExtendedRepositoryInterface $repository, $scope = null)
    {
        $scope = (null === $scope) ? $this->activeScope : $scope;

        $repository->clearScopes();

        if ($this->hasActiveListParent()) {
            return $this;
        }

        if ($scope) {

            $info = $this->getModelInformation();

            $method = $info->list->scopes[ $scope ]->method ?: $scope;

            $repository->addScope($method);
        }

        return $this;
    }

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

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


Question:
@param array|null $params
@param string|null $apiKey

@return Shippo_Get_Status Get the tracking status of a Shipment.

public static function get_status($params = null, $apiKey = null)
    {
        $class = get_class();
        $id = $params['id'];
        return self::_scopedGetStatus($class, $id, $params, $apiKey);
    }

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


Question: Process a SDP state change event.

def _process_event(event: Event, sdp_state: SDPState,
                   service_states: List[ServiceState]):
    """"""
    LOG.debug('Event detected! (id : "%s", type: "%s", data: "%s")',
              event.object_id, event.type, event.data)

    if event.object_id == 'SDP' and event.type == 'current_state_updated':
        LOG.info('SDP current state updated, no action required!')

    if event.object_id == 'SDP' and event.type == 'target_state_updated':
        LOG.info("SDP target state changed to '%s'",
                 sdp_state.target_state)

        # If the sdp is already in the target state do nothing
        if sdp_state.target_state == sdp_state.current_state:
            LOG.warning('SDP already in %s state',
                        sdp_state.current_state)
            return

        # Check that a transition to the target state is allowed in the
        # current state.
        if not sdp_state.is_target_state_allowed(sdp_state.target_state):
            LOG.error('Transition to %s is not allowed when in state %s',
                      sdp_state.target_state, sdp_state.current_state)
            sdp_state.target_state = sdp_state.current_state
            return

        _update_services_target_state(sdp_state.target_state)

        # If asking SDP to turn off, also turn off services.
        if sdp_state.target_state == 'off':
            LOG.info('Turning off services!')
            for service_state in service_states:
                service_state.update_target_state('off')
                service_state.update_current_state('off')

        LOG.info('Processing target state change request ...')
        time.sleep(0.1)
        LOG.info('Done processing target state change request!')

        # Assuming that the SDP has responding to the target
        # target state command by now, set the current state
        # to the target state.
        sdp_state.update_current_state(sdp_state.target_state)

        if sdp_state.current_state == 'alarm':
            LOG.debug('raising SDP state alarm')
            SIP_STATE_ALARM.set(1)
        else:
            SIP_STATE_ALARM.set(0)
        try:
            # FIXME(BMo) the pushgateway host should not be hardcoded!
            push_to_gateway('platform_pushgateway:9091', job='SIP',
                            registry=COLLECTOR_REGISTRY)
        except urllib.error.URLError:
            LOG.warning("Unable to connect to the Alarms service!")

def resume(self):

        if self._status != TransferState.PAUSED:
            self._running.set()
            self._status = TransferState.RUNNING
        else:
            raise SbgError('Can not pause. Download not in PAUSED state.')

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


Question:
Removes the cp definition grouped entry where uuid = ? and groupId = ? from the database.

@param uuid the uuid
@param groupId the group ID
@return the cp definition grouped entry that was removed

public static CPDefinitionGroupedEntry removeByUUID_G(String uuid,
		long groupId)
		throws com.liferay.commerce.product.type.grouped.exception.NoSuchCPDefinitionGroupedEntryException {
		return getPersistence().removeByUUID_G(uuid, groupId);
	}

def _update_requires_resolution_inputs(self):

        input_paths = [quad[1] for quad in self.requires_resolution]
        results = resolve_multiple_existing_paths(input_paths)
        for input_name, input_value, input_class, input_index in self.requires_resolution:
            project = results[input_value]['project']
            folderpath = results[input_value]['folder']
            entity_result = results[input_value]['name']
            if input_class is None:
                if entity_result is not None:
                    if isinstance(entity_result, basestring):
                        # Case: -ifoo=job-012301230123012301230123
                        # Case: -ifoo=analysis-012301230123012301230123
                        assert(is_job_id(entity_result) or
                               (is_analysis_id(entity_result)))
                        input_value = entity_result
                    elif is_hashid(input_value):
                        input_value = {'$dnanexus_link': entity_result['id']}
                    elif 'describe' in entity_result:
                        # Then findDataObjects was called (returned describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['describe']['project'],
                                                          "id": entity_result['id']}}
                    else:
                        # Then resolveDataObjects was called in a batch (no describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                          "id": entity_result['id']}}
                if input_index >= 0:
                    if self.inputs[input_name][input_index] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name][input_index] = input_value
                else:
                    if self.inputs[input_name] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name] = input_value
            else:
                msg = 'Value provided for input field "' + input_name + '" could not be parsed as ' + \
                      input_class + ': '
                if input_value == '':
                    raise DXCLIError(msg + 'empty string cannot be resolved')
                if entity_result is None:
                    raise DXCLIError(msg + 'could not resolve \"' + input_value + '\" to a name or ID')
                try:
                    dxpy.bindings.verify_string_dxid(entity_result['id'], input_class)
                except DXError as details:
                    raise DXCLIError(msg + str(details))
                if is_hashid(input_value):
                    input_value = {'$dnanexus_link': entity_result['id']}
                elif 'describe' in entity_result:
                    # Then findDataObjects was called (returned describe hash)
                    input_value = {'$dnanexus_link': {"project": entity_result['describe']['project'],
                                                      "id": entity_result['id']}}
                else:
                    # Then resolveDataObjects was called in a batch (no describe hash)
                    input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                      "id": entity_result['id']}}
                if input_index != -1:
                    # The class is an array, so append the resolved value
                    self.inputs[input_name].append(input_value)
                else:
                    self.inputs[input_name] = input_value

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


Question: // New returns a new Bee instance configured with the supplied options.

func (factory *CronBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface {
	bee := CronBee{
		Bee: bees.NewBee(name, factory.ID(), description, options),
	}
	bee.ReloadOptions(options)

	return &bee
}

def hvac_autosize(self):

        for i in range(len(self.BEM)):
            if self.is_near_zero(self.autosize) == False:
                self.BEM[i].building.coolCap = 9999.
                self.BEM[i].building.heatCap = 9999.

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


Question:
Calculates net output of the network as a float value for the given input

@return int|float

protected function output(array $sample)
    {
        $sum = 0;
        foreach ($this->weights as $index => $w) {
            if ($index == 0) {
                $sum += $w;
            } else {
                $sum += $w * $sample[$index - 1];
            }
        }

        return $sum;
    }

protected void checkOutput()
    {
        if (_out==_realOut)
        {
            if (_bufferedOut==null)
            {
                _bufferedOut=new ChunkingOutputStream(_realOut,
                                                      _bufferSize,
                                                      _headerReserve,
                                                      false);
                _bufferedOut.setCommitObserver(this);
                _bufferedOut.setBypassBuffer(true);
                _bufferedOut.setFixed(true);
            }
            _out=_bufferedOut;
        }
    }

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


Question:
Encode the facility and priority. You can pass in strings or
        integers - if strings are passed, the facility_names and
        priority_names mapping dictionaries are used to convert them to
        integers.

def encode_priority(self, facility, priority):

        return (facility << 3) | self.priority_map.get(priority, self.LOG_WARNING)

private function key_list()
    {
        $this->enigma->load_engine();

        $pagesize = $this->rc->config->get('pagesize', 100);
        $page     = max(intval(rcube_utils::get_input_value('_p', rcube_utils::INPUT_GPC)), 1);
        $search   = rcube_utils::get_input_value('_q', rcube_utils::INPUT_GPC);

        // Get the list
        $list = $this->enigma->engine->list_keys($search);

        if ($list && ($list instanceof enigma_error))
            $this->rc->output->show_message('enigma.keylisterror', 'error');
        else if (empty($list))
            $this->rc->output->show_message('enigma.nokeysfound', 'notice');
        else if (is_array($list)) {
            // Save the size
            $listsize = count($list);

            // Sort the list by key (user) name
            usort($list, array('enigma_key', 'cmp'));

            // Slice current page
            $list = array_slice($list, ($page - 1) * $pagesize, $pagesize);
            $size = count($list);

            // Add rows
            foreach ($list as $key) {
                $this->rc->output->command('enigma_add_list_row', array(
                        'name'  => rcube::Q($key->name),
                        'id'    => $key->id,
                        'flags' => $key->is_private() ? 'p' : ''
                ));
            }
        }

        $this->rc->output->set_env('rowcount', $size);
        $this->rc->output->set_env('search_request', $search);
        $this->rc->output->set_env('pagecount', ceil($listsize/$pagesize));
        $this->rc->output->set_env('current_page', $page);
        $this->rc->output->command('set_rowcount',
            $this->get_rowcount_text($listsize, $size, $page));

        $this->rc->output->send();
    }

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


Question:
Logs with an arbitrary level.

@param mixed        $level
@param string|array $message
@param array        $context

@return void

public function log($level, $message, array $context = [])
    {
        if (!isset($this->logLevels[$level])) {
            $level = LogLevel::DEBUG;
        }

        if ($this->logLevels[$level] < $this->level) {
            // do not print.
            return;
        }

        if ($this->level === 3 && $this->logLevels[$level] === 3) {
            $style = 'dim';
        } else {
            $style = $this->levelStyles[$level];
        }

        if ($this->indent) {
            $this->write(\str_repeat($this->indentCharacter, $this->indent));
        }

        if (\is_object($message) || \is_array($message)) {
            $this->writeln(\print_r($message, true), $style);
        } else {
            $this->writeln($message, $style);
        }
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--logfile', '-l',      GetoptLong::REQUIRED_ARGUMENT ],
          [ '--verbose', '-v',      GetoptLong::NO_ARGUMENT ],
          [ '--quiet',   '-q',      GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--port', '-p',         GetoptLong::REQUIRED_ARGUMENT ],
          [ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h',         GetoptLong::NO_ARGUMENT ],
          [ '--exit', '-x', 				GetoptLong::NO_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--logfile', '-l'
              @logfile = arg
              Log.logger = Logger.new(@logfile)
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--verbose', '-v'
              @verbose = true
            when '--quiet',   '-q'
              @quiet = true
            when '--port', '-p'
              @port = arg
            when '--bind-address', '-b'
              @bind_address = arg.to_s
            when '--help', '-h'
              help
            when '--exit', '-x'
              uri = "http://localhost:#{@port}/admin"
              response = RestClient.post uri, { 'shutdown' => true }.to_yaml
              exit 0
          end
        end
      rescue GetoptLong::InvalidOption => ex
        puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
        exit 1
      end

      #
      # Set up logging/verbosity
      #
      Chimp.set_verbose(@verbose, @quiet)

      if not @verbose
      	ENV['REST_CONNECTION_LOG'] = "/dev/null"
      	ENV['RESTCLIENT_LOG'] = "/dev/null"
        Log.threshold= Logger::INFO
      else
        Log.threshold= Logger::DEBUG
      end

      if @quiet
        Log.threshold = Logger::WARN
      end
    end

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


Question: // run periodically probes the container.

func (w *worker) run() {
	probeTickerPeriod := time.Duration(w.spec.PeriodSeconds) * time.Second

	// If kubelet restarted the probes could be started in rapid succession.
	// Let the worker wait for a random portion of tickerPeriod before probing.
	time.Sleep(time.Duration(rand.Float64() * float64(probeTickerPeriod)))

	probeTicker := time.NewTicker(probeTickerPeriod)

	defer func() {
		// Clean up.
		probeTicker.Stop()
		if !w.containerID.IsEmpty() {
			w.resultsManager.Remove(w.containerID)
		}

		w.probeManager.removeWorker(w.pod.UID, w.container.Name, w.probeType)
		ProberResults.Delete(w.proberResultsSuccessfulMetricLabels)
		ProberResults.Delete(w.proberResultsFailedMetricLabels)
		ProberResults.Delete(w.proberResultsUnknownMetricLabels)
	}()

probeLoop:
	for w.doProbe() {
		// Wait for next probe tick.
		select {
		case <-w.stopCh:
			break probeLoop
		case <-probeTicker.C:
			// continue
		}
	}
}

def _ensure_opened(self):

        if not self._opened:
            self._opened = True
            self._update_servers()

            # Start or restart the events publishing thread.
            if self._publish_tp or self._publish_server:
                self.__events_executor.open()

        # Ensure that the monitors are open.
        for server in itervalues(self._servers):
            server.open()

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


Question: // SetWebACL sets the WebACL field's value.

func (s *GetWebACLOutput) SetWebACL(v *WebACL) *GetWebACLOutput {
	s.WebACL = v
	return s
}

def get_default(self, node):

        if node.inst.properties.get("woset", False):
            return rdltypes.OnWriteType.woset
        elif node.inst.properties.get("woclr", False):
            return rdltypes.OnWriteType.woclr
        else:
            return self.default

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


Question: // Clear removes all objects from the Buffer.

func (b *Buffer) Clear() {
	b.array = make([]float64, bufferDefaultCapacity)
	b.head = 0
	b.tail = 0
	b.size = 0
}

func (node TableName) Format(buf *TrackedBuffer) {
	if node.IsEmpty() {
		return
	}
	if !node.Qualifier.IsEmpty() {
		buf.Myprintf("%v.", node.Qualifier)
	}
	buf.Myprintf("%v", node.Name)
}

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


Question:
Add a tagged component to be included in the template. The component will be rendered in place of the
corresponding tag in the template.

@param tag the tag for this component in the template
@param component the component to add

public void addTaggedComponent(final String tag, final WComponent component) {
		if (Util.empty(tag)) {
			throw new IllegalArgumentException("A tag must be provided.");
		}
		if (component == null) {
			throw new IllegalArgumentException("A component must be provided.");
		}

		TemplateModel model = getOrCreateComponentModel();
		if (model.taggedComponents == null) {
			model.taggedComponents = new HashMap<>();
		} else {
			if (model.taggedComponents.containsKey(tag)) {
				throw new IllegalArgumentException("The tag [" + tag + "] has already been added.");
			}
			if (model.taggedComponents.containsValue(component)) {
				throw new IllegalArgumentException("Component has already been added.");
			}
		}
		model.taggedComponents.put(tag, component);
		add(component);
	}

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question:
Adds more result handlers to the validator.

@param resultHandlers Result handlers to be added.

@return Same validator context.

public ValidatorContext<D, O> handleWith(final ResultHandler<O>... resultHandlers) {
        if (resultHandlers != null) {
            Collections.addAll(registeredResultHandlers, resultHandlers);
        }
        return this;
    }

public function bind(MapInterface $values): self
    {
        if (
            (string) $values->keyType() !== 'string' ||
            (string) $values->valueType() !== 'mixed'
        ) {
            throw new \TypeError('Argument 1 must be of type MapInterface<string, mixed>');
        }

        $this
            ->arguments
            ->filter(static function(string $name, Argument $argument): bool {
                return !$argument->optional() && !$argument->hasDefault();
            })
            ->foreach(static function(string $name) use ($values): void {
                if (!$values->contains($name)) {
                    throw new MissingArgument($name);
                }
            });
        $this
            ->arguments
            ->filter(static function(string $name) use ($values): bool {
                return $values->contains($name);
            })
            ->foreach(static function(string $name, Argument $argument) use ($values): void {
                $argument->validate($values->get($name));
            });

        $self = clone $this;
        $self->values = $values;

        return $self;
    }

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


Question:
// RandRead is a belt-and-suspenders wrapper around
// crypto.rand.Read().

func RandRead(buf []byte) error {
	n, err := rand.Read(buf)
	if err != nil {
		return errors.WithStack(err)
	}
	// This is truly unexpected, as rand.Read() is supposed to
	// return an error on a short read already!
	if n != len(buf) {
		return errors.WithStack(UnexpectedShortCryptoRandRead{})
	}
	return nil
}

def random_sample(self, k=1):

        # k == 0: no work to do
        if k == 0:
            results = []
        # k == 1: same behavior on all versions of Redis
        elif k == 1:
            results = [self.redis.srandmember(self.key)]
        # k != 1, Redis version >= 2.6: compute in Redis
        else:
            results = self.redis.srandmember(self.key, k)

        return [self._unpickle(x) for x in results]

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


Question:
read as date value

In case the default value is not of type stubbles\date\Date an IllegalStateException
will be thrown.

@param   \stubbles\input\filter\range\DateRange  $range
@return  \stubbles\date\Date

public function asDate(DateRange $range = null)
    {
        $this->default = (null === $this->default) ? (null) : (Date::castFrom($this->default, 'default'));
        return $this->default;
    }

public function getInputFilterSpecification()
    {
        return array(
            'firstName' => array(
                'required'   => true,
                'filters'    => array(
                    array('name' => '\Zend\Filter\StringTrim'),
                ),
                'validators' => array(
                    new NotEmpty(),
                    new StringLength(array('max' => 50))
                ),
            ),
            'lastName'  => array(
                'required'   => true,
                'filters'    => array(
                    array('name' => 'Zend\Filter\StringTrim'),
                ),
                'validators' => array(
                    new NotEmpty(),
                    new StringLength(array('max' => 50))
                ),
            ),
            'email'     => array(
                'required'   => true,
                'filters'    => array(
                    array('name' => 'Zend\Filter\StringTrim'),
                ),
                'validators' => array(
                    new NotEmpty(),
                    new StringLength(array('max' => 100)),
                    new EmailAddress()
                )
            ),
            'image'     => array(
                'required'   => false,
                'filters'    => array(),
                'validators' => array(
                    new File\Exists(),
                    new File\Extension(array('extension' => array('jpg', 'png', 'jpeg', 'gif'))),
                ),
            ),
        );
    }

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


Question: //Render the initial html form

func (form FormHome) Render(ws *websocket.Conn, app *valente.App, params []string) error {
	root := elements.Panel{}
	root.AddElement(elements.Heading3{Text: "Quotes"})

	list := elements.List{}
	list.SetData("data-role", "listview")
	list.SetData("data-inset", "true")
	list.AddElement(itemQuote("Alphabet Inc.", "GOOG"))
	list.AddElement(itemQuote("Apple Inc.", "AAPL"))
	list.AddElement(itemQuote("Microsoft Inc.", "MSFT"))
	list.AddElement(itemQuote("Facebook Inc.", "FB"))
	root.AddElement(list)

	action.HTML(ws, "content", root.String())
	action.Exec(ws, "$('#content').appendTo('.ui-page').trigger('create');")

	go func() {
		for {
			updateQuote(ws, "GOOG")
			updateQuote(ws, "AAPL")
			updateQuote(ws, "MSFT")
			updateQuote(ws, "FB")
			time.Sleep(5 * time.Minute)
		}
	}()

	return nil
}

public function handle()
    {
        $this->showWelcomeMessage();
        $this->userSetup();
        $this->triggerPublish();
        $this->call('dashboard:fresh');
        $this->setupSeedStubs();
        $this->triggerMigrations();
        $this->createDefaultUser();
        $this->info('Setup is complete. Keep coding!');
    }

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


Question:
gets the attributes of a node - ordered by sequence in html

@param  {DOM Node} node
@return {Array}

function( node ){
			var nodeStr = node.outerHTML,
				attrs = [];

			for (var i = 0; i < node.attributes.length; i++) {
				var attr = node.attributes[i];
					attr.indexNum = nodeStr.indexOf(attr.name);

				attrs.push( attr );
			}
			return attrs.sort( modules.utils.sortObjects( 'indexNum' ) );
		}

protected function addAttributes(DOMElement $element, $storage): void
    {
        foreach ($storage as $attrKey => $attrVal) {
            if (strpos($attrKey, ':') !== false) {
                $this->namespaces[$attrKey] = $attrVal;
            }

            $element->setAttribute($attrKey, $attrVal);
        }
    }

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


Question: list := (tasks:Array<Continuable<T>>) => Continuable<Array<T>>

function list(tasks) {
    return function continuable(callback) {
        var result = []
        var count = 0

        if (tasks.length === 0) {
            return callback(null, result)
        }

        tasks.forEach(function invokeSource(source, index) {
            source(function continuation(err, value) {
                if (err && result) {
                    result = null
                    callback(err)
                } else if (!err && result) {
                    result[index] = value
                    if (++count === tasks.length) {
                        callback(null, result)
                    }
                }
            })
        })
    }
}

func (r *ChainResponse) Send(response *restful.Response) {
	var keys []string
	for k := range r.chains {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		r.Chains = append(r.Chains, prepareChainResponse(r.Context, r.chains[k]))
	}

	r.Response.Send(response)
}

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


Question:
Processes a single line of Haml.

 This method doesn't return anything; it simply processes the line and
 adds the appropriate code to `@precompiled`.

def process_line(line)
      case line.text[0]
      when DIV_CLASS; push div(line)
      when DIV_ID
        return push plain(line) if %w[{ @ $].include?(line.text[1])
        push div(line)
      when ELEMENT; push tag(line)
      when COMMENT; push comment(line.text[1..-1].lstrip)
      when SANITIZE
        return push plain(line.strip!(3), :escape_html) if line.text[1, 2] == '=='
        return push script(line.strip!(2), :escape_html) if line.text[1] == SCRIPT
        return push flat_script(line.strip!(2), :escape_html) if line.text[1] == FLAT_SCRIPT
        return push plain(line.strip!(1), :escape_html) if line.text[1] == ?\s || line.text[1..2] == '#{'
        push plain(line)
      when SCRIPT
        return push plain(line.strip!(2)) if line.text[1] == SCRIPT
        line.text = line.text[1..-1]
        push script(line)
      when FLAT_SCRIPT; push flat_script(line.strip!(1))
      when SILENT_SCRIPT
        return push haml_comment(line.text[2..-1]) if line.text[1] == SILENT_COMMENT
        push silent_script(line)
      when FILTER; push filter(line.text[1..-1].downcase)
      when DOCTYPE
        return push doctype(line.text) if line.text[0, 3] == '!!!'
        return push plain(line.strip!(3), false) if line.text[1, 2] == '=='
        return push script(line.strip!(2), false) if line.text[1] == SCRIPT
        return push flat_script(line.strip!(2), false) if line.text[1] == FLAT_SCRIPT
        return push plain(line.strip!(1), false) if line.text[1] == ?\s || line.text[1..2] == '#{'
        push plain(line)
      when ESCAPE
        line.text = line.text[1..-1]
        push plain(line)
      else; push plain(line)
      end
    end

def prepare_metadata(self):
        # type: () -> None

        assert self.source_dir

        with indent_log():
            if self.use_pep517:
                self.prepare_pep517_metadata()
            else:
                self.run_egg_info()

        if not self.req:
            if isinstance(parse_version(self.metadata["Version"]), Version):
                op = "=="
            else:
                op = "==="
            self.req = Requirement(
                "".join([
                    self.metadata["Name"],
                    op,
                    self.metadata["Version"],
                ])
            )
            self._correct_build_location()
        else:
            metadata_name = canonicalize_name(self.metadata["Name"])
            if canonicalize_name(self.req.name) != metadata_name:
                logger.warning(
                    'Generating metadata for package %s '
                    'produced metadata for project name %s. Fix your '
                    '#egg=%s fragments.',
                    self.name, metadata_name, self.name
                )
                self.req = Requirement(metadata_name)

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


Question:
TODO: Document args
 TODO: Document block format

def go(&stream_block)
      @status = :running
      @results = { @host.hostname => {} }
      mkdir = exec_and_log(@host, "mkdir -p '#{@dir}' -m #{@chmod}", @sudo, @results[@host.hostname], &stream_block)

      if (mkdir[:exit_status]).zero?
        exec_and_log(@host, "chmod #{@chmod} #{@dir}", @sudo, @results[@host.hostname], &stream_block)
      end

      @results
    end

def method_rules
      [
        Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
          json[:body_md] && json[:body_md].empty?
        end),
        Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
          json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
        end),
        Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
          json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
        end),
        Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return  [void]` - this will be ignored by documentation generators.", proc do |json|
          return_hash = json[:tags].find { |tag| tag[:name] == "return" }
          !(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
        end)
      ]
    end

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


Question:
Execute the SQL file's content.

@param unitDaoFactory the {@link net.cpollet.jixture.dao.UnitDaoFactory} to use.

@Override
	public void load(UnitDaoFactory unitDaoFactory) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
		BufferedReaderIterator iterator = new BufferedReaderIterator(reader);

		StringBuilder currentQuery = new StringBuilder();
		while (iterator.hasNext()) {
			String line = iterator.next().trim();

			if (!isCommentOrEmptyLine(line)) {
				currentQuery.append(line).append(" ");
			}

			if (isEndOfQuery(line)) {
				unitDaoFactory.getUnitDao().execute(currentQuery.toString());
				currentQuery = new StringBuilder();
			}
		}
	}

public DaoDesc createDaoDesc(EntityDesc entityDesc) {
    DaoDesc daoDesc = new DaoDesc();
    daoDesc.setPackageName(packageName);
    String entityPrefix = StringUtil.defaultString(entityDesc.getEntityPrefix(), "");
    String entitySuffix = StringUtil.defaultString(entityDesc.getEntitySuffix(), "");
    String simpleName = entityPrefix + entityDesc.getSimpleName() + entitySuffix + suffix;
    daoDesc.setSimpleName(simpleName);
    if (configClassName != null) {
      daoDesc.setConfigClassSimpleName(ClassUtil.getSimpleName(configClassName));
    }
    daoDesc.setEntityDesc(entityDesc);
    daoDesc.setTemplateName(Constants.DAO_TEMPLATE);
    handleImportName(daoDesc, entityDesc);
    return daoDesc;
  }

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


Question:
// Add adds the passed nonce to the map and handles eviction of the oldest item
// if adding the new item would exceed the max limit.  Adding an existing item
// makes it the most recently used item.
//
// This function is safe for concurrent access.

func (m *mruNonceMap) Add(nonce uint64) {
	m.mtx.Lock()
	defer m.mtx.Unlock()

	// When the limit is zero, nothing can be added to the map, so just
	// return.
	if m.limit == 0 {
		return
	}

	// When the entry already exists move it to the front of the list
	// thereby marking it most recently used.
	if node, exists := m.nonceMap[nonce]; exists {
		m.nonceList.MoveToFront(node)
		return
	}

	// Evict the least recently used entry (back of the list) if the the new
	// entry would exceed the size limit for the map.  Also reuse the list
	// node so a new one doesn't have to be allocated.
	if uint(len(m.nonceMap))+1 > m.limit {
		node := m.nonceList.Back()
		lru := node.Value.(uint64)

		// Evict least recently used item.
		delete(m.nonceMap, lru)

		// Reuse the list node of the item that was just evicted for the
		// new item.
		node.Value = nonce
		m.nonceList.MoveToFront(node)
		m.nonceMap[nonce] = node
		return
	}

	// The limit hasn't been reached yet, so just add the new item.
	node := m.nonceList.PushFront(nonce)
	m.nonceMap[nonce] = node
}

private function selectNodeType(\DOMNode $node, $val): bool
    {
        if (\is_array($val)) {
            return $this->buildXml($node, $val);
        } elseif ($val instanceof \SimpleXMLElement) {
            $child = $this->dom->importNode(dom_import_simplexml($val), true);
            $node->appendChild($child);
        } elseif ($val instanceof \Traversable) {
            $this->buildXml($node, $val);
        } elseif (\is_object($val)) {
            return $this->selectNodeType($node, $this->serializer->normalize($val, $this->format, $this->context));
        } elseif (is_numeric($val)) {
            return $this->appendText($node, (string) $val);
        } elseif (\is_string($val) && $this->needsCdataWrapping($val)) {
            return $this->appendCData($node, $val);
        } elseif (\is_string($val)) {
            return $this->appendText($node, $val);
        } elseif (\is_bool($val)) {
            return $this->appendText($node, (int) $val);
        } elseif ($val instanceof \DOMNode) {
            $child = $this->dom->importNode($val, true);
            $node->appendChild($child);
        }

        return true;
    }

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


Question: Create utitilies stack.

def create_utilities(self):

        self.create_stack(
            self.utilities_name,
            'amazon-utilities.yaml',
            parameters=define_parameters(
                Subnets=self.subnet_ids,
                NodeSecurityGroup=self.node_security_group
            )
        )

def put_current_line(self, prefix='', suffix=''):

        return '%s#line %i "%s"%s' % (prefix, self.lex.lineno, self.filestack[-1][0], suffix)

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


Question: // condition evaluates a condition

func condition(name string, input interface{}, template interface{}, options *ProcessorOptions) interface{} {
	if v, ok := input.(string); ok {

		if v, ok := retrieveCondition(input, template); ok {
			return v
		}

		if c := getCondition(v, template); c != nil {
			res := search(c, template, options)
			// replace the value in the template so the value can be reused
			setCondition(v, res, template)

			return res
		}
	}

	return nil
}

def devaluate(actual, expected)
      expected = %r[#{Regexp.escape(expected)}] if expected.kind_of?(String)
      if actual.to_s =~ expected
        fail(expected_message(expected).not_to_match(actual))
      else
        pass(new_message.matches(expected))
      end
    end

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


Question:
Save string content into output file with given name and extension.

@param event
@param content
@param name
@param extension

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

public function setFilePointer($pointer)
	{
		if(!is_resource($pointer))
			throw new InvalidArgumentException("Invalid type - not a file resource");

		$this->pointer = $pointer;

		# and now to set everything up...
		$metadata = stream_get_meta_data($this->pointer);

		# can this stream be read from?
		if(isset($metadata["mode"]))
		{
			$mode = rtrim($metadata["mode"], "bt");

			$super = (boolean) preg_match("/\+$/", $mode);
			$mode = rtrim($mode, "+");

			switch($mode)
			{
				case "r":
					$this->is_readable = true;
				break;

				case "w":
				case "a":
				case "x":
				case "c":
					$this->is_readable = $super;
				break;

				default:
					throw new LogicException("Invalid file access type: '".$metadata["mode"]."'");
				break;
			}
		}

		# can this stream be written to?
		if(isset($metadata["mode"]))
		{
			$mode = rtrim($metadata["mode"], "bt");

			$super = (boolean) preg_match("/\+$/", $mode);
			$mode = rtrim($mode, "+");

			switch($mode)
			{
				case "r":
					$this->is_writable = $super;
				break;

				case "w":
				case "a":
				case "x":
				case "c":
					$this->is_writable = true;
				break;

				default:
					throw new LogicException("Invalid file access type: '".$metadata["mode"]."'");
				break;
			}
		}

		# does this stream support seek functionality?
		if(isset($metadata["seekable"]))
			$this->is_seekable = (boolean) $metadata["seekable"];

		return null;
	}

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


Question:
Tests if a received class name is in fact a Doctrine Entity

Based on @link https://stackoverflow.com/a/27121978/1155833

@param string $classFQCN

@return boolean
@throws EntityNotFoundException

function isEntity(string $classFQCN) : bool
    {
        if ( ! class_exists($classFQCN)) {

            throw new ClassNotFoundException(sprintf('Given class FQCN "%s" does not exist.', $classFQCN));
        }

        if ( ! is_object($classFQCN)) {

            throw new EntityNotFoundException(sprintf('Given class "%s" is not a Doctrine Entity.', $classFQCN));
        }

        return ! $this->getObjectManager()
                      ->getMetadataFactory()
                      ->isTransient(ClassUtils::getClass($classFQCN));
    }

public static function create(Response $response)
    {
        $errorMessage = $response->getError();
        $exception = isset(static::$exceptionMap[$errorMessage])
            ? static::$exceptionMap[$errorMessage]
            : CentrifugoException::class;

        return new static($response, new $exception($errorMessage));
    }

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


Question:
// readStateFile loads a stateFile from the subdirectory of dirPath named
// for the supplied storage tag. If the directory does not exist, no error
// is returned.

func readStateFile(dirPath string, tag names.StorageTag) (d *stateFile, err error) {
	filename := strings.Replace(tag.Id(), "/", "-", -1)
	d = &stateFile{
		filepath.Join(dirPath, filename),
		state{storage: tag},
	}
	defer errors.DeferredAnnotatef(&err, "cannot load storage %q state from %q", tag.Id(), d.path)
	if _, err := os.Stat(d.path); os.IsNotExist(err) {
		return d, nil
	} else if err != nil {
		return nil, err
	}
	var info diskInfo
	if err := utils.ReadYaml(d.path, &info); err != nil {
		return nil, errors.Errorf("invalid storage state file %q: %v", d.path, err)
	}
	if info.Attached == nil {
		return nil, errors.Errorf("invalid storage state file %q: missing 'attached'", d.path)
	}
	d.state.attached = *info.Attached
	return d, nil
}

def _ScanFileSystem(self, scan_node, base_path_specs):

    if not scan_node or not scan_node.path_spec:
      raise errors.ScannerError('Invalid or missing file system scan node.')

    base_path_specs.append(scan_node.path_spec)

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


Question: Adds an @this annotation to all functions in the objLit.

private void addTypesToFunctions(
      Node objLit, String thisType, PolymerClassDefinition.DefinitionType defType) {
    checkState(objLit.isObjectLit());
    for (Node keyNode : objLit.children()) {
      Node value = keyNode.getLastChild();
      if (value != null && value.isFunction()) {
        JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(keyNode.getJSDocInfo());
        fnDoc.recordThisType(
            new JSTypeExpression(new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE));
        keyNode.setJSDocInfo(fnDoc.build());
      }
    }

    // Add @this and @return to default property values.
    for (MemberDefinition property :
        PolymerPassStaticUtils.extractProperties(
            objLit,
            defType,
            compiler,
            /** constructor= */
            null)) {
      if (!property.value.isObjectLit()) {
        continue;
      }

      Node defaultValue = NodeUtil.getFirstPropMatchingKey(property.value, "value");
      if (defaultValue == null || !defaultValue.isFunction()) {
        continue;
      }
      Node defaultValueKey = defaultValue.getParent();
      JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(defaultValueKey.getJSDocInfo());
      fnDoc.recordThisType(
          new JSTypeExpression(new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE));
      fnDoc.recordReturnType(PolymerPassStaticUtils.getTypeFromProperty(property, compiler));
      defaultValueKey.setJSDocInfo(fnDoc.build());
    }
  }

public <V extends ModelElementInstance> AttributeReferenceBuilder<V> qNameAttributeReference(Class<V> referenceTargetElement) {
    AttributeImpl<String> attribute = (AttributeImpl<String>) build();
    AttributeReferenceBuilderImpl<V> referenceBuilder = new QNameAttributeReferenceBuilderImpl<V>(attribute, referenceTargetElement);
    setAttributeReference(referenceBuilder);
    return referenceBuilder;
  }

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


Question:
/*
(non-Javadoc)

@see javax.persistence.metamodel.ManagedType#getSet(java.lang.String,
java.lang.Class)

@Override
    public <E> SetAttribute<? super X, E> getSet(String paramName, Class<E> paramClass)
    {
        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);

        if (onCheckSetAttribute(declaredAttrib, paramClass))
        {
            return (SetAttribute<X, E>) declaredAttrib;
        }

        PluralAttribute<? super X, ?, ?> superAttrib = getPluralAttriute(paramName);

        if (onCheckSetAttribute(superAttrib, paramClass))
        {
            return (SetAttribute<? super X, E>) superAttrib;

        }
        throw new IllegalArgumentException(
                "attribute of the given name and type is not present in the managed type, for name:" + paramName
                        + " , type:" + paramClass);
    }

public Classification nameOf(String classificationName, String name) {
        return findClassificationMeta((String) classificationName, () -> {
            return "nameOf('" + classificationName + "', '" + name + "')";
        }).nameOf(name);
    }

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


Question: // GetTextRotationDegrees returns the text rotation in degrees.

func (s Style) GetTextRotationDegrees(defaults ...float64) float64 {
	if s.TextRotationDegrees == 0 {
		if len(defaults) > 0 {
			return defaults[0]
		}
	}
	return s.TextRotationDegrees
}

function(direction, length) {
        direction *= Math.PI / 180;
        var dx = length * Math.cos(direction);
        var dy = length * Math.sin(direction);
        this.insertDeltaXY(dx, dy);
    }

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


Question:
Returns a boolean of whether the raw_password was correct. Handles
    encryption formats behind the scenes.

def check_password(raw_password, enc_password):

    l = enc_password.split('$')
    #only password of built-in user can split to 3
    if len(l)==3:
        algo, salt, hsh = l
        return hsh == get_hexdigest(algo, salt, raw_password)
    else:
        return False

private function formLoginAuthenticator(ContainerBuilder $container, $routes, $user)
    {
        $container->setDefinition(
            'bengor.user_bundle.security.authenticator.form_login_' . $user . '_authenticator',
            new Definition(
                FormLoginAuthenticator::class, [
                    $container->getDefinition('router.default'),
                    $container->getDefinition('bengor_user.' . $user . '.command_bus'),
                    [
                        'login'                     => $routes[$user]['login']['name'],
                        'login_check'               => $routes[$user]['login_check']['name'],
                        'success_redirection_route' => $routes[$user]['success_redirection_route'],
                    ],
                ]
            )
        )->setPublic(false);

        $container->setAlias(
            'bengor_user.' . $user . '.form_login_authenticator',
            'bengor.user_bundle.security.authenticator.form_login_' . $user . '_authenticator'
        );
    }

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


Question:
Handle SET

@param   array $columns

@return  string

protected function handleSetColumns(array $columns)
    {
        if (empty($columns)) {
            return '';
        }

        $sql = [];

        foreach ($columns as $column) {
            $sql[] = $this->wrap($column['column']) . ' = ' . $this->param($column['value']);
        }

        return ' SET ' . implode(', ', $sql);
    }

func (s *DescribeDBParameterGroupsOutput) SetDBParameterGroups(v []*DBParameterGroup) *DescribeDBParameterGroupsOutput {
	s.DBParameterGroups = v
	return s
}

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


Question: // NewDecoder returns a Decoder which reads JSON stream from "r".

func (j *JSONBuiltin) NewDecoder(r io.Reader) Decoder {
	return json.NewDecoder(r)
}

protected static final Object parseNext(Source src) throws IOException {
		skipWhitespaces(src);
		switch (src.ch) {

		case '"':
			return parseString(src);

		case 't':
			src.idx += 4;
			return Boolean.TRUE;

		case 'f':
			src.idx += 5;
			return Boolean.FALSE;

		case 'n':
			src.idx += 4;
			return null;

		case '[':
			return parseList(src);

		case '{':
			return parseMap(src);

		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
		case '-':
			return parseNumber(src);

		default:
			throw new IOException(
					"Unable to determine the next character, it is not a string, number, array, or object!");
		}
	}

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


Question:
In-place bitwise XOR (symmetric difference) operation. The current bitmap is modified.

@param x2 other bitmap

public void xor(final RoaringBitmap x2) {
    int pos1 = 0, pos2 = 0;
    int length1 = highLowContainer.size();
    final int length2 = x2.highLowContainer.size();

    main: if (pos1 < length1 && pos2 < length2) {
      short s1 = highLowContainer.getKeyAtIndex(pos1);
      short s2 = x2.highLowContainer.getKeyAtIndex(pos2);

      while (true) {
        if (s1 == s2) {
          final Container c = highLowContainer.getContainerAtIndex(pos1)
              .ixor(x2.highLowContainer.getContainerAtIndex(pos2));
          if (!c.isEmpty()) {
            this.highLowContainer.setContainerAtIndex(pos1, c);
            pos1++;
          } else {
            highLowContainer.removeAtIndex(pos1);
            --length1;
          }
          pos2++;
          if ((pos1 == length1) || (pos2 == length2)) {
            break main;
          }
          s1 = highLowContainer.getKeyAtIndex(pos1);
          s2 = x2.highLowContainer.getKeyAtIndex(pos2);
        } else if (Util.compareUnsigned(s1, s2) < 0) { // s1 < s2
          pos1++;
          if (pos1 == length1) {
            break main;
          }
          s1 = highLowContainer.getKeyAtIndex(pos1);
        } else { // s1 > s2
          highLowContainer.insertNewKeyValueAt(pos1, s2,
              x2.highLowContainer.getContainerAtIndex(pos2).clone());
          pos1++;
          length1++;
          pos2++;
          if (pos2 == length2) {
            break main;
          }
          s2 = x2.highLowContainer.getKeyAtIndex(pos2);
        }
      }
    }
    if (pos1 == length1) {
      highLowContainer.appendCopy(x2.highLowContainer, pos2, length2);
    }
  }

protected void writeMemo( Object obj ) throws IOException
	{
		if(!this.useMemo)
			return;
		int hash = valueCompare ? obj.hashCode() : System.identityHashCode(obj);
		if(!memo.containsKey(hash))
		{
			int memo_index = memo.size();
			memo.put(hash, new Memo(obj, memo_index));
			if(memo_index<=0xFF)
			{
				out.write(Opcodes.BINPUT);
				out.write((byte)memo_index);
			}
			else
			{
				out.write(Opcodes.LONG_BINPUT);
				byte[] index_bytes = PickleUtils.integer_to_bytes(memo_index);
				out.write(index_bytes, 0, 4);
			}
		}
	}

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