Question:
/*
Check the response from the endpoint to see if there was an error

boolean isErrorResponse(HttpResponse response) {
        StatusLine status = response.getStatusLine();
        if (status == null || status.getStatusCode() != 200) {
            return true;
        }
        return false;
    }

public ApiSuccessResponse forward(ForwardData forwardData) throws ApiException {
        ApiResponse<ApiSuccessResponse> resp = forwardWithHttpInfo(forwardData);
        return resp.getData();
    }

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


Question:
// newHook returns a io.ReadSeeker which implements hookReader that
// reports the data read from the source to the hook.

func newHook(source, hook io.Reader) io.Reader {
	if hook == nil {
		return source
	}
	return &hookReader{source, hook}
}

public boolean canReadVarInt () throws KryoException {
		if (limit - position >= 5) return true;
		if (optional(5) <= 0) return false;
		int p = position, limit = this.limit;
		byte[] buffer = this.buffer;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		if ((buffer[p++] & 0x80) == 0) return true;
		if (p == limit) return false;
		return true;
	}

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


Question:
Translate (mutate) this vector using a function
function $f($x, $y, $value) {return [$newX, $newY, $newValue];}

@param \callable $f
@throws VectorException
@returns $this

public function translate(callable $f)
    {
        list($this->x, $this->y, $this->value) = $f($this->x, $this->y, $this->value);
    }

func (mv *Validator) copy() *Validator {
	newFuncs := map[string]ValidationFunc{}
	for k, f := range mv.validationFuncs {
		newFuncs[k] = f
	}
	return &Validator{
		tagName:         mv.tagName,
		validationFuncs: newFuncs,
	}
}

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


Question:
// writeTokens writes a slice of tokens to the output.
// codes for literal and offset encoding must be supplied.

func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) {
	if w.err != nil {
		return
	}
	for _, t := range tokens {
		if t < matchType {
			w.writeCode(leCodes[t.literal()])
			continue
		}
		// Write the length
		length := t.length()
		lengthCode := lengthCode(length)
		w.writeCode(leCodes[lengthCode+lengthCodesStart])
		extraLengthBits := uint(lengthExtraBits[lengthCode])
		if extraLengthBits > 0 {
			extraLength := int32(length - lengthBase[lengthCode])
			w.writeBits(extraLength, extraLengthBits)
		}
		// Write the offset
		offset := t.offset()
		offsetCode := offsetCode(offset)
		w.writeCode(oeCodes[offsetCode])
		extraOffsetBits := uint(offsetExtraBits[offsetCode])
		if extraOffsetBits > 0 {
			extraOffset := int32(offset - offsetBase[offsetCode])
			w.writeBits(extraOffset, extraOffsetBits)
		}
	}
}

protected function rcdata() {
        if (is_null($this->untilTag)) {
            return $this->text();
        }
        $sequence = '</' . $this->untilTag . '>';
        $txt = '';
        $tok = $this->scanner->current();
        while ($tok !== false && !($tok == '<' && ($this->sequenceMatches($sequence) || $this->sequenceMatches(strtoupper($sequence))))) {
            if ($tok == '&') {
                $txt .= $this->decodeCharacterReference();
                $tok = $this->scanner->current();
            } else {
                $txt .= $tok;
                $tok = $this->scanner->next();
            }
        }
        $this->events->text($txt);
        $this->setTextMode(0);
        return $this->endTag();
    }

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


Question:
// Page will return the Page (of Kind taxonomyList) that represents this set
// of pages. This method will panic if p is empty, as that should never happen.

func (p WeightedPages) Page() Page {
	if len(p) == 0 {
		panic("WeightedPages is empty")
	}

	first := p[0]

	// TODO(bep) fix tests
	if first.owner == nil {
		return nil
	}

	return first.owner.Page
}

def prepare_notes(self, *notes, **keyword_notes):
        """"""
        __partial = keyword_notes.pop('__partial', False)
        args = tuple(self.get(note) for note in notes)
        kwargs = {}
        for arg in keyword_notes:
            note = keyword_notes[arg]
            if isinstance(note, tuple) and len(note) == 2 and note[0] == MAYBE:
                try:
                    kwargs[arg] = self.get(note[1])
                except LookupError:
                    continue
            elif __partial:
                try:
                    kwargs[arg] = self.get(note)
                except LookupError:
                    continue
            else:
                kwargs[arg] = self.get(note)
        return args, kwargs

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


Question:
Função para exclusão das pastas de arquivo no sistema
@param  string     $path
@param  boolean    $recursive
@throws \Exception

public static function removeFolder($path, $recursive = true)
    {
        if (is_dir($path)) {
            if ($recursive) {
                $objects = scandir($path);
                foreach ($objects as $object) {
                    if ($object != "." && $object != "..") {
                        if (filetype($path . DS . $object) == "dir") {
                            self::removeFolder($path . DS . $object);
                        } else {
                            unlink($path . DS . $object);
                        }
                    }
                }
                reset($objects);
                rmdir($path);
            } else {
                rmdir($path);
            }
        }
    }

public function load($file){
        $realPath = realpath($file);

        if (!$realPath || !file_exists($realPath)) {
            throw new FileNotFoundException($realPath);
        }

        $this->cookies = file_get_contents($realPath);
    }

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


Question:
Tells if the given path is absolute.

@param  string  $path
@return boolean

public function isAbsolute($path)
    {
        $firstChar = substr($path, 0, 1);
        if ('/' === $firstChar || '\\' === $firstChar) {
            return true;
        }
        $isLetter = (
            ($firstChar >= 'A' && $firstChar <= 'Z') ||
            ($firstChar >= 'a' && $firstChar <= 'z')
        );
        $path = substr($path, 1, 2);
        return $isLetter && (':/' === $path || ':\\' === $path);
    }

func makeAbsoluteIfNecessary(current, root string) (string, error) {
	currentUri, err := url.Parse(current)
	if err != nil {
		return "", err
	}

	if currentUri.IsAbs() {
		return current, nil
	}

	rootUri, err := url.Parse(root)
	if err != nil {
		return "", err
	}

	currentUri.Scheme = rootUri.Scheme
	currentUri.Host = rootUri.Host
	currentUri.User = rootUri.User

	return currentUri.String(), nil
}

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


Question:
收集统计数据
@param string $module
@param string $interface
@param float $cost_time
@param int $success
@param string $ip
@param int $code
@param string $msg
@return void

protected function collectStatistics($module, $interface , $cost_time, $success, $ip, $code, $msg)
   {
       // 统计相关信息
       if(!isset($this->statisticData[$ip]))
       {
           $this->statisticData[$ip] = array();
       }
       if(!isset($this->statisticData[$ip][$module]))
       {
           $this->statisticData[$ip][$module] = array();
       }
       if(!isset($this->statisticData[$ip][$module][$interface]))
       {
           $this->statisticData[$ip][$module][$interface] = array('code'=>array(), 'suc_cost_time'=>0, 'fail_cost_time'=>0, 'suc_count'=>0, 'fail_count'=>0);
       }
       if(!isset($this->statisticData[$ip][$module][$interface]['code'][$code]))
       {
           $this->statisticData[$ip][$module][$interface]['code'][$code] = 0;
       }
       $this->statisticData[$ip][$module][$interface]['code'][$code]++;
       if($success)
       {
           $this->statisticData[$ip][$module][$interface]['suc_cost_time'] += $cost_time;
           $this->statisticData[$ip][$module][$interface]['suc_count'] ++;
       }
       else
       {
           $this->statisticData[$ip][$module][$interface]['fail_cost_time'] += $cost_time;
           $this->statisticData[$ip][$module][$interface]['fail_count'] ++;
       }
   }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question:
Builds the filename of under which the data gets saved in the storage adapter.

@param \Cake\Datasource\EntityInterface $entity
@param array $options
@return string

public function filename(EntityInterface $entity, array $options = []) {
		$config = array_merge($this->getConfig(), $options);
		if ($config['preserveFilename'] === true) {
			return $this->_preserveFilename($entity, $config);
		}

		return $this->_buildFilename($entity, $config);
	}

public function storeImage(ImageInterface $image, ImagePathInterface $path) {
		$this->optimizerImageManipulator->manipulateImage($image, $path);
		$this->writeImageFile($image, $path);
	}

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


Question: // encode body as JSON, deferring any errors until io.Reader is used.

func encode(body interface{}) io.Reader {
	var b bytes.Buffer
	err := json.NewEncoder(&b).Encode(body)
	if err != nil {
		return errorReader{err}
	}
	return &b
}

function init(options, requestBody, type) {
    /**
     * If the user asked for a file, simply return the string.
     */
    if (type && type === "file") {
        return processItems(requestBody);
    }

    /**
     * Otherwise return a function to be used a middleware
     */
    return function(req, res) {
        /**
         * default to using the uncompressed string
         * @type {String}
         */
        var output = processItems(requestBody);

        /**
         * Set the appropriate headers for caching
         */
        setHeaders(res, output);
        if (isConditionalGet(req) && fresh(req.headers, res._headers)) {
            return notModified(res);
        }

        /**
         * If gzip is supported, compress the string once
         * and save for future requests
         */
        if (supportsGzip(req)) {
            res.setHeader("Content-Encoding", "gzip");
            var buf = new Buffer(output, "utf-8");
            zlib.gzip(buf, function(_, result) {
                res.end(result);
            });
        } else {
            res.end(output);
        }
    };
}

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


Question: :param crabpy.gateway.capakey.CapakeyGateway gateway: Gateway to use.

def set_gateway(self, gateway):
        '''

        '''
        self.gateway = gateway
        if (self._gemeente is not None):
            self._gemeente.set_gateway(gateway)

def create_parser():
    """"""
    description = """RPC Release Diff Generator
--------------------------

Finds changes in OpenStack-Ansible, OpenStack-Ansible roles, and OpenStack
projects between two RPC-OpenStack revisions.

"""

    parser = argparse.ArgumentParser(
        usage='%(prog)s',
        description=description,
        epilog='Licensed "Apache 2.0"',
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument(
        'old_commit',
        action='store',
        nargs=1,
        help="Git SHA of the older commit",
    )
    parser.add_argument(
        'new_commit',
        action='store',
        nargs=1,
        help="Git SHA of the newer commit",
    )
    parser.add_argument(
        '--debug',
        action='store_true',
        default=False,
        help="Enable debug output",
    )
    parser.add_argument(
        '--verbose',
        action='store_true',
        default=False,
        help="Enable verbose output",
    )
    parser.add_argument(
        '-d', '--directory',
        action='store',
        default="~/.osa-differ",
        help="Git repo storage directory (default: ~/.osa-differ)",
    )
    parser.add_argument(
        '-rroc', '--role-requirements-old-commit',
        action='store',
        default=None,
        help=(
            "Name of the Ansible role requirements file to read from the old "
            "commit, defaults to value of `--role-requirements`."
        ),
    )
    parser.add_argument(
        '-rr', '--role-requirements',
        action='store',
        default=ROLE_REQ_FILE,
        help="Name of the ansible role requirements file to read",
    )
    parser.add_argument(
        '-r', '--rpc-repo-url',
        action='store',
        default="https://github.com/rcbops/rpc-openstack",
        help="Github repository for the rpc-openstack project"
    )
    parser.add_argument(
        '--osa-repo-url',
        action='store',
        default="https://git.openstack.org/openstack/openstack-ansible",
        help="URL of the openstack-ansible git repo"
    )
    parser.add_argument(
        '-rpoc', '--rpc-product-old-commit',
        action='store',
        default=None,
        help=(
            "Set the RPC product version for the old commit, defaults to "
            "value of `--rpc-product`."
        )
    )
    parser.add_argument(
        '-rp', '--rpc-product',
        action='store',
        default="master",
        help="Set the RPC product version"
    )
    parser.add_argument(
        '-u', '--update',
        action='store_true',
        default=False,
        help="Fetch latest changes to repo",
    )
    parser.add_argument(
        '--version-mappings',
        action=osa_differ.VersionMappingsAction,
        help=(
            "Map dependency versions in cases where the old version no longer "
            "exists. The argument should be of the form "
            "'repo-name;old-version1:new-version1;old-version2:new-version2'."
        ),
    )

    display_opts = parser.add_argument_group("Limit scope")
    display_opts.add_argument(
        "--skip-projects",
        action="store_true",
        help="Skip checking for changes in OpenStack projects"
    )
    display_opts.add_argument(
        "--skip-roles",
        action="store_true",
        help="Skip checking for changes in OpenStack-Ansible roles"
    )
    output_desc = ("Output is printed to stdout by default.")
    output_opts = parser.add_argument_group('Output options', output_desc)
    output_opts.add_argument(
        '--quiet',
        action='store_true',
        default=False,
        help="Do not output to stdout",
    )
    output_opts.add_argument(
        '--gist',
        action='store_true',
        default=False,
        help="Output into a GitHub Gist",
    )
    output_opts.add_argument(
        '--file',
        metavar="FILENAME",
        action='store',
        help="Output to a file",
    )
    return parser

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


Question: // Run instantiates a HANA object, and runs the RPC server for the plugin

func Run(apiTLSConfig *api.TLSConfig) error {
	dbType, err := New()
	if err != nil {
		return err
	}

	dbplugin.Serve(dbType.(dbplugin.Database), api.VaultPluginTLSProvider(apiTLSConfig))

	return nil
}

public static rnat[] get_filtered(nitro_service service, String filter) throws Exception{
		rnat obj = new rnat();
		options option = new options();
		option.set_filter(filter);
		rnat[] response = (rnat[]) obj.getfiltered(service, option);
		return response;
	}

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


Question:
// UpdateTable figures out what columns we need to add to the target table based on the
// input table, and completes this action in the transaction provided
// Note: only supports adding columns currently, not updating existing columns or removing them

func (r *Redshift) UpdateTable(tx *sql.Tx, inputTable, targetTable Table) error {

	columnOps, err := checkSchemas(inputTable, targetTable)
	if err != nil {
		return fmt.Errorf("mismatched schema: %s", err)
	}

	// postgres only allows adding one column at a time
	for _, op := range columnOps {
		alterStmt, err := tx.PrepareContext(r.ctx, op)
		if err != nil {
			return fmt.Errorf("issue preparing statement: '%s' - err: %s", op, err)
		}

		log.Printf("Running command: %s", op)
		_, err = alterStmt.ExecContext(r.ctx)
		if err != nil {
			return fmt.Errorf("issue running statement %s: %s", op, err)
		}
	}
	return nil
}

private Mutation mutationFromTuple(Tuple t) throws IOException
    {
        Mutation mutation = new Mutation();
        if (t.get(1) == null)
        {
            if (allow_deletes)
            {
                mutation.deletion = new Deletion();
                mutation.deletion.predicate = new org.apache.cassandra.thrift.SlicePredicate();
                mutation.deletion.predicate.column_names = Arrays.asList(objToBB(t.get(0)));
                mutation.deletion.setTimestamp(FBUtilities.timestampMicros());
            }
            else
                throw new IOException("null found but deletes are disabled, set " + PIG_ALLOW_DELETES +
                    "=true in environment or allow_deletes=true in URL to enable");
        }
        else
        {
            org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
            column.setName(objToBB(t.get(0)));
            column.setValue(objToBB(t.get(1)));
            column.setTimestamp(FBUtilities.timestampMicros());
            mutation.column_or_supercolumn = new ColumnOrSuperColumn();
            mutation.column_or_supercolumn.column = column;
        }
        return mutation;
    }

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


Question:
Asserts the configuration of content entity type bundles.

@Then exactly the following content entity type bundles should exist

@throws \Exception

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

protected function _log($context)
    {
        if ($context instanceof ConnectionException) {
            $this->_logger->error('Elastica Request Failure', [
                'exception' => $context,
                'request' => $context->getRequest()->toArray(),
                'retry' => $this->hasConnection(),
            ]);

            return;
        }

        if ($context instanceof Request) {
            $this->_logger->debug('Elastica Request', [
                'request' => $context->toArray(),
                'response' => $this->_lastResponse ? $this->_lastResponse->getData() : null,
                'responseStatus' => $this->_lastResponse ? $this->_lastResponse->getStatus() : null,
            ]);

            return;
        }

        $this->_logger->debug('Elastica Request', [
            'message' => $context,
        ]);
    }

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


Question:
Logs error to build console and changes build result

@return true as of it terminating handler

@Override
    public boolean handle(Exception e, @Nonnull Run<?, ?> run, @Nonnull TaskListener listener) {
        Result toSet = Result.fromString(trimToEmpty(result));

        listener.error("[GitHub Commit Status Setter] - %s, setting build result to %s", e.getMessage(), toSet);

        run.setResult(toSet);
        return true;
    }

public void update() throws DevFailed {
	xlogger.entry();
	final Map<String, String[]> property = PropertiesUtils.getDeviceProperties(deviceName);

	if (property != null && property.size() != 0) {
	    try {
		propertyMethod.invoke(businessObject, property);
	    } catch (final IllegalArgumentException e) {
		throw DevFailedUtils.newDevFailed(e);
	    } catch (final IllegalAccessException e) {
		throw DevFailedUtils.newDevFailed(e);
	    } catch (final SecurityException e) {
		throw DevFailedUtils.newDevFailed(e);
	    } catch (final InvocationTargetException e) {
		throw DevFailedUtils.newDevFailed(e);
	    }
	}
	xlogger.exit();
    }

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


Question:
{@inheritDoc}

@throws SuperCsvCellProcessorException
if value is null

public Object execute(final Object value, final CsvContext context) {
		validateInputNotNull(value, context);
		String result = regexPattern.matcher(value.toString()).replaceAll(replacement);
		return next.execute(result, context);
	}

def _prepare_calls(result_file, out_dir, data):

    sample = dd.get_sample_name(data)
    out_file = os.path.join(out_dir, "%s-optitype.csv" % (sample))
    if not utils.file_uptodate(out_file, result_file):
        hla_truth = bwakit.get_hla_truthset(data)
        with file_transaction(data, out_file) as tx_out_file:
            with open(tx_out_file, "w") as out_handle:
                writer = csv.writer(out_handle)
                allele_info = _parse_result_file(result_file)
                if len(allele_info) == 1:
                    writer.writerow(["sample", "locus", "alleles", "expected", "validates"])
                else:
                    writer.writerow(["sample", "local", "index", "alleles", "score"])
                for j, (alleles, score) in enumerate(allele_info):
                    for hla_locus, call_alleles in alleles:
                        truth_alleles = tz.get_in([sample, hla_locus], hla_truth, [])
                        if len(allele_info) == 1:
                            writer.writerow([sample, hla_locus,
                                             ";".join(call_alleles), ";".join(truth_alleles),
                                             bwakit.matches_truth(call_alleles, truth_alleles, data)])
                        else:
                            writer.writerow([sample, hla_locus, j, ";".join(call_alleles), score])
    return out_file

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


Question: // UnmarshalJSON sets the object from the provided JSON representation

func (l *CodePipelinePipelineStageDeclarationList) UnmarshalJSON(buf []byte) error {
	// Cloudformation allows a single object when a list of objects is expected
	item := CodePipelinePipelineStageDeclaration{}
	if err := json.Unmarshal(buf, &item); err == nil {
		*l = CodePipelinePipelineStageDeclarationList{item}
		return nil
	}
	list := []CodePipelinePipelineStageDeclaration{}
	err := json.Unmarshal(buf, &list)
	if err == nil {
		*l = CodePipelinePipelineStageDeclarationList(list)
		return nil
	}
	return err
}

public WebhookData parseWebhookData(String webhook) {
        if (webhook == null || webhook.trim()
                .length() <= 0) {
            return null;
        }
        webhook = LEFT_QUOTATION.matcher(webhook)
                .replaceAll("{");
        webhook = RIGHT_QUOTATION.matcher(webhook)
                .replaceAll("}");
        webhook = BACKLASH_QUOTATION.matcher(webhook)
                .replaceAll("\"");

        return FastjsonDecoder.decodeAsBean(webhook, WebhookData.class);
    }

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


Question:
Checks authorization.

@param string $element
@return void
@throws Application\ForbiddenRequestException

public function checkRequirements($element)
    {
        try {
            parent::checkRequirements($element);

            if (!$this->requirementsChecker->isAllowed($element)) {
                throw new Application\ForbiddenRequestException;
            }
        } catch (Application\ForbiddenRequestException $e) {
            $this->flashMessage('Pro vstup do požadované sekce musíte být přihlášen/a s příslušným oprávněním.');

            if (!$this->user->isLoggedIn()) {
                $this->redirect(
                    'Sign:in',
                    ['backSignInUrl' => $this->getHttpRequest()->url->path]
                );
            } elseif (!$this->isLinkCurrent('Homepage:')) {
                $this->redirect('Homepage:');
            } else {
                $this->redirect('Sign:in');
            }
        }
    }

private function serializeAce(Writer $writer, array $ace)
    {
        $writer->startElement('{DAV:}ace');

        switch ($ace['principal']) {
            case '{DAV:}authenticated':
                $principal = new Principal(Principal::AUTHENTICATED);
                break;
            case '{DAV:}unauthenticated':
                $principal = new Principal(Principal::UNAUTHENTICATED);
                break;
            case '{DAV:}all':
                $principal = new Principal(Principal::ALL);
                break;
            default:
                $principal = new Principal(Principal::HREF, $ace['principal']);
                break;
        }

        $writer->writeElement('{DAV:}principal', $principal);
        $writer->startElement('{DAV:}grant');
        $writer->startElement('{DAV:}privilege');

        $writer->writeElement($ace['privilege']);

        $writer->endElement(); // privilege
        $writer->endElement(); // grant

        if (!empty($ace['protected'])) {
            $writer->writeElement('{DAV:}protected');
        }

        $writer->endElement(); // ace
    }

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


Question:
Counts how many "code words" are in a specific text.

@param string $text The text from which the words should be counted

@return int

private static function countCode($text)
    {
        // remove code attribute content, like from href="" or d=""
        $text = preg_replace('/"[^"]*"/i', '', $text);
        // get markdown code
        $regex = '/(?<=(?<!`))`([^`\n\r]+)`(?=(?!`))|```[a-zA-Z]*([^`]*)```/i';
        $markdownCount = preg_match_all($regex, $text, $markdownMatches, PREG_PATTERN_ORDER);
        // Remove markdown code from text, as to not double count
        $text = trim(preg_replace('/(?<=(?<!`))`[^`\n\r]+`(?=(?!`))|```[a-zA-Z]*[^`]*```/i', ' ', $text));

        // get html code elements
        $regex = '/<code>([\s\S]*?)<\/code>/i';
        $htmlCount = preg_match_all($regex, $text, $htmlMatches, PREG_PATTERN_ORDER);

        // check if any matches exist
        if ($markdownCount === 0 && $htmlCount === 0) {
            return 0;
        }
        // concat all code
        $code = implode($markdownMatches[1], ' ').' '.implode($markdownMatches[2], ' ').' '.implode($htmlMatches[1], ' ');

        // replace multiple spaces
        $code = preg_replace(['/\s+/', '/^\s/'], [' ', ''], $code);

        // return the number words in the code blocks
        return count(array_filter(explode(' ', $code)));
    }

public function InExpression()
    {
        $inExpression = new AST\InExpression($this->ArithmeticExpression());

        if ($this->lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $inExpression->not = true;
        }

        $this->match(Lexer::T_IN);
        $this->match(Lexer::T_OPEN_PARENTHESIS);

        if ($this->lexer->isNextToken(Lexer::T_SELECT)) {
            $inExpression->subselect = $this->Subselect();
        } else {
            $literals   = [];
            $literals[] = $this->InParameter();

            while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);
                $literals[] = $this->InParameter();
            }

            $inExpression->literals = $literals;
        }

        $this->match(Lexer::T_CLOSE_PARENTHESIS);

        return $inExpression;
    }

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


Question: Resources in an AST, keyed by type.

def resources_by_type(ast)
      raise_unless_xpath!(ast)
      result = Hash.new { |hash, key| hash[key] = Array.new }
      find_resources(ast).each do |resource|
        result[resource_type(resource)] << resource
      end
      result
    end

public static URI[] downloadJar(String org, String module, String version, boolean transitive) throws IOException {
    Map<String, Object> artifactMap = Maps.newHashMap();
    artifactMap.put("org", org);
    artifactMap.put("module", module);
    artifactMap.put("version", version);
    artifactMap.put("transitive", transitive);
    return downloadJar(artifactMap);
  }

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


Question: // SetNextToken sets the NextToken field's value.

func (s *ListEndpointsInput) SetNextToken(v string) *ListEndpointsInput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question:
Checks whether association rules can be generated.

        :return: whether scheme implements AssociationRulesProducer interface and
        association rules can be generated
        :rtype: bool

def can_produce_rules(self):

        if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"):
            return False
        return javabridge.call(self.jobject, "canProduceRules", "()Z")

private function parseRuleDefinition($key, $definition): Rule
    {
        if (is_string($definition)) {

            $parts = preg_split('/:/', $definition, 2);

            $factory_name = $parts[0];
            $parameters = $parts[1] ?? null;

            $parameters = ! is_null($parameters)
                ? explode(',', $parameters)
                : [];

            $factory_name = trim($factory_name);
            $parameters = array_map('trim', $parameters);

            $factory = $this->getRuleFactory($factory_name);

            $name = is_string($key) ? $key : $factory_name;
            $validate = $factory($parameters);

            return new Rule($name, $validate);

        }

        // is_callable must be AFTER is_string, otherwise factories named like a
        // php function can't be used (ex: date).
        if (is_callable($definition)) {

            return new Rule((string) $key, $definition);

        }

        throw new InvalidRuleFormatException($definition);
    }

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


Question: Free this object.

public void free()
    {
        Record record = null;
        if (this.getMessageSource() instanceof Record)
            record = (Record)this.getMessageSource();

        super.free();

        if (record != null)
        {
            BaseSyncRecordMessageFilterHandler fileListener = (BaseSyncRecordMessageFilterHandler)record.getListener(BaseSyncRecordMessageFilterHandler.class, false);
            if (fileListener != null)
                if (fileListener.getRecordMessageFilter() == this)
            {   // Always
                    // Note: Removing this fileListener will call free again for this object... shouldn't be a problem, since everything has been zeroed --- may want to fix this later
                record.removeListener(fileListener, true);
            }
        }
    }

def as_flow(cls, obj):
        """"""
        if isinstance(obj, cls): return obj
        if is_string(obj):
            return cls.pickle_load(obj)
        elif isinstance(obj, collections.Mapping):
            return cls.from_dict(obj)
        else:
            raise TypeError("Don't know how to convert type %s into a Flow" % type(obj))

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


Question: // InitAPNSClient use for initialize APNs Client.

func InitAPNSClient() error {
	if PushConf.Ios.Enabled {
		var err error
		var authKey *ecdsa.PrivateKey
		var certificateKey tls.Certificate
		var ext string

		if PushConf.Ios.KeyPath != "" {
			ext = filepath.Ext(PushConf.Ios.KeyPath)

			switch ext {
			case ".p12":
				certificateKey, err = certificate.FromP12File(PushConf.Ios.KeyPath, PushConf.Ios.Password)
			case ".pem":
				certificateKey, err = certificate.FromPemFile(PushConf.Ios.KeyPath, PushConf.Ios.Password)
			case ".p8":
				authKey, err = token.AuthKeyFromFile(PushConf.Ios.KeyPath)
			default:
				err = errors.New("wrong certificate key extension")
			}

			if err != nil {
				LogError.Error("Cert Error:", err.Error())

				return err
			}
		} else if PushConf.Ios.KeyBase64 != "" {
			ext = "." + PushConf.Ios.KeyType
			key, err := base64.StdEncoding.DecodeString(PushConf.Ios.KeyBase64)
			if err != nil {
				LogError.Error("base64 decode error:", err.Error())

				return err
			}
			switch ext {
			case ".p12":
				certificateKey, err = certificate.FromP12Bytes(key, PushConf.Ios.Password)
			case ".pem":
				certificateKey, err = certificate.FromPemBytes(key, PushConf.Ios.Password)
			case ".p8":
				authKey, err = token.AuthKeyFromBytes(key)
			default:
				err = errors.New("wrong certificate key type")
			}

			if err != nil {
				LogError.Error("Cert Error:", err.Error())

				return err
			}
		}

		if ext == ".p8" && PushConf.Ios.KeyID != "" && PushConf.Ios.TeamID != "" {
			token := &token.Token{
				AuthKey: authKey,
				// KeyID from developer account (Certificates, Identifiers & Profiles -> Keys)
				KeyID: PushConf.Ios.KeyID,
				// TeamID from developer account (View Account -> Membership)
				TeamID: PushConf.Ios.TeamID,
			}
			if PushConf.Ios.Production {
				ApnsClient = apns2.NewTokenClient(token).Production()
			} else {
				ApnsClient = apns2.NewTokenClient(token).Development()
			}
		} else {
			if PushConf.Ios.Production {
				ApnsClient = apns2.NewClient(certificateKey).Production()
			} else {
				ApnsClient = apns2.NewClient(certificateKey).Development()
			}
		}
	}

	return nil
}

public IAtom configure(IAtom atom, IIsotope isotope) {
        atom.setMassNumber(isotope.getMassNumber());
        atom.setSymbol(isotope.getSymbol());
        atom.setExactMass(isotope.getExactMass());
        atom.setAtomicNumber(isotope.getAtomicNumber());
        atom.setNaturalAbundance(isotope.getNaturalAbundance());
        return atom;
    }

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


Question:
Return rfc or iso String date or datetime as java Date

@param dt string format date
@return Date
@throws BadDateException on format error

public static Date fromDate(final String dt) throws BadDateException {
    try {
      if (dt == null) {
        return null;
      }

      if (dt.indexOf("T") > 0) {
        return fromDateTime(dt);
      }

      if (!dt.contains("-")) {
        return fromISODate(dt);
      }

      return fromRfcDate(dt);
    } catch (Throwable t) {
      throw new BadDateException();
    }
  }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question:
Create thumbnail.

@param  string $filename
@param  integer $width
@param  integer|null $height
@return string

public function create($filename, $width, $height = null)
    {
        try {
            $image = app('image')->make($this->file->realPath)
                ->fit($width, ($height ?: $width))
                ->encode();

            $this->file->storage->put($this->file->path($filename), $image);
        } catch (NotReadableException $e) {
            return null;
        }

        return $this->file->storage->url($this->file->path($filename));
    }

public function send(): void
    {
        // status
        if ($this->httpVersion == Http::VERSION_1_0 || $this->httpVersion == Http::VERSION_1_1) {
            header(sprintf('%s %s %s', $this->httpVersion, $this->status->getCode(), $this->status->getText()));
        } elseif ($this->httpVersion == Http::VERSION_2) {
            header(sprintf('%s %s', $this->httpVersion, $this->status->getCode()));
        }

        // load time
        $exposeAppLoadTime = $this->app->configValue('exposeAppLoadTime');
        if ($exposeAppLoadTime === true || $exposeAppLoadTime === $this->app->env()) {
            $this->sendHeader('X-App-Load-Time', $this->app->loadTime());
        }

        [$contentType, $contentCharset, $contentLength] = $this->body->toArray();

        // content type/charset?/length
        if ($this->body->isImage()) {
            $this->sendHeader('Content-Type', $contentType);
        } elseif ($contentType == '') {
            $this->sendHeader('Content-Type', 'n/a');
        } elseif ($contentCharset == '' || in_array($contentType, ['n/a', 'none'])) {
            $this->sendHeader('Content-Type', $contentType);
        } else {
            $this->sendHeader('Content-Type', sprintf('%s; charset=%s', $contentType, $contentCharset));
        }
        $this->sendHeader('Content-Length', (string) $contentLength);

        // print it baby!
        print $this->body->toString();
    }

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


Question: Initializes the preference, which allows to show the single choice list dialog.

private void initializeShowSingleChoiceListDialogPreference() {
        Preference preference =
                findPreference(getString(R.string.show_single_choice_dialog_preference_key));
        preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(final Preference preference) {
                initializeSingleChoiceListDialog();
                singleChoiceListDialog
                        .setShowAnimation(createRectangularRevealAnimation(preference));
                singleChoiceListDialog
                        .setDismissAnimation(createRectangularRevealAnimation(preference));
                singleChoiceListDialog
                        .setCancelAnimation(createRectangularRevealAnimation(preference));
                singleChoiceListDialog.show();
                return true;
            }

        });
    }

def manipulate(self, stored_instance, component_instance):

        # Store the stored instance...
        self._ipopo_instance = stored_instance

        # ... and the bundle context
        self._context = stored_instance.bundle_context

        # Set the default value for the field: an empty dictionary
        setattr(component_instance, self._field, {})

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


Question: // writeConfigBytesToDisk writes a byte slice down to disk at the specific location of the kubelet config file

func writeConfigBytesToDisk(b []byte, kubeletDir string) error {
	configFile := filepath.Join(kubeletDir, kubeadmconstants.KubeletConfigurationFileName)
	fmt.Printf("[kubelet-start] Writing kubelet configuration to file %q\n", configFile)

	// creates target folder if not already exists
	if err := os.MkdirAll(kubeletDir, 0700); err != nil {
		return errors.Wrapf(err, "failed to create directory %q", kubeletDir)
	}

	if err := ioutil.WriteFile(configFile, b, 0644); err != nil {
		return errors.Wrapf(err, "failed to write kubelet configuration to the file %q", configFile)
	}
	return nil
}

def cli(env, identifier, out_file):
    """"""

    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')

    key = mgr.get_key(key_id)

    if out_file:
        with open(path.expanduser(out_file), 'w') as pub_file:
            pub_file.write(key['key'])

    table = formatting.KeyValueTable(['name', 'value'])
    table.add_row(['id', key['id']])
    table.add_row(['label', key.get('label')])
    table.add_row(['notes', key.get('notes', '-')])
    env.fout(table)

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


Question: Absolute path to the BWA index for EricScript reference data.

def reference_index(self):
        """"""
        if self._db_location:
            ref_indices = glob.glob(os.path.join(self._db_location, "*", self._REF_INDEX))
            if ref_indices:
                return ref_indices[0]

func (toolkit BashToolkit) StepRunCommandArguments(step stepmanModels.StepModel, sIDData models.StepIDData, stepAbsDirPath string) ([]string, error) {
	entryFile := "step.sh"
	if step.Toolkit != nil && step.Toolkit.Bash != nil && step.Toolkit.Bash.EntryFile != "" {
		entryFile = step.Toolkit.Bash.EntryFile
	}

	stepFilePath := filepath.Join(stepAbsDirPath, entryFile)
	cmd := []string{"bash", stepFilePath}
	return cmd, nil
}

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


Question:
Returns a JSDoc annotation for a data type.
    May contain a union of enumerated subtypes.

def fmt_type(data_type):

    if is_struct_type(data_type) and data_type.has_enumerated_subtypes():
        possible_types = []
        possible_subtypes = data_type.get_all_subtypes_with_tags()
        for _, subtype in possible_subtypes:
            possible_types.append(fmt_type_name(subtype))
        if data_type.is_catch_all():
            possible_types.append(fmt_type_name(data_type))
        return fmt_jsdoc_union(possible_types)
    else:
        return fmt_type_name(data_type)

function UMLComponentView() {
        UMLClassifierView.apply(this, arguments);

        // mixin UMLComponentViewMixin
        _.extend(UMLComponentView.prototype, UMLComponentViewMixin);

        this.fillColor = PreferenceManager.get("uml.component.fillColor", "#ffffff") || PreferenceManager.get("view.fillColor", "#ffffff");
        this.stereotypeDisplay  = PreferenceManager.get("uml.component.stereotypeDisplay", UML.SD_LABEL);
        this.suppressAttributes = PreferenceManager.get("uml.component.suppressAttributes", true);
        this.suppressOperations = PreferenceManager.get("uml.component.suppressOperations", true);
    }

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


Question:
// Execute runs the given command on the given client with stdin/stdout/stderr
// connected to the controlling terminal. It returns any error encountered in
// the SSH session, and the exit status of the remote command.

func Execute(client *SSHForwardingClient, cmd string) (error, int) {
	session, finalize, err := makeSession(client)
	if err != nil {
		return err, -1
	}

	defer finalize()

	session.Start(cmd)

	err = session.Wait()
	// the command ran and exited successfully
	if err == nil {
		return nil, 0
	}
	// if the session terminated normally, err should be ExitError; in that
	// case, return nil error and actual exit status of command
	if werr, ok := err.(*gossh.ExitError); ok {
		return nil, werr.ExitStatus()
	}
	// otherwise, we had an actual SSH error
	return err, -1
}

def _endpoint_from_socksport_line(reactor, socks_config):

    if socks_config.startswith('unix:'):
        # XXX wait, can SOCKSPort lines with "unix:/path" still
        # include options afterwards? What about if the path has a
        # space in it?
        return UNIXClientEndpoint(reactor, socks_config[5:])

    # options like KeepAliveIsolateSOCKSAuth can be appended
    # to a SocksPort line...
    if ' ' in socks_config:
        socks_config = socks_config.split()[0]
    if ':' in socks_config:
        host, port = socks_config.split(':', 1)
        port = int(port)
    else:
        host = '127.0.0.1'
        port = int(socks_config)
    return TCP4ClientEndpoint(reactor, host, port)

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


Question: // NumEdges returns the number of edges in this index.

func (s *ShapeIndex) NumEdges() int {
	numEdges := 0
	for _, shape := range s.shapes {
		numEdges += shape.NumEdges()
	}
	return numEdges
}

private void createEdge(Node fromNode, ControlFlowGraph.Branch branch,
      Node toNode) {
    cfg.createNode(fromNode);
    cfg.createNode(toNode);
    cfg.connectIfNotFound(fromNode, branch, toNode);
  }

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


Question:
Changes the input image.  The previous distortion is thrown away only if the input
image has a different shape

public FDistort input( ImageBase input ) {
		if( this.input == null || this.input.width != input.width || this.input.height != input.height ) {
			distorter = null;
		}
		this.input = input;
		inputType = input.getImageType();
		return this;
	}

public function register()
    {
        $this->app->singleton(
            'datatables.fractal', function () {
                $fractal = new Manager;
                $config  = $this->app['config'];
                $request = $this->app['request'];

                $includesKey = $config->get('datatables-fractal.includes', 'include');
                if ($request->get($includesKey)) {
                    $fractal->parseIncludes($request->get($includesKey));
                }

                $serializer = $config->get('datatables-fractal.serializer', DataArraySerializer::class);
                $fractal->setSerializer(new $serializer);

                return $fractal;
            }
        );

        $this->app->singleton(
            'datatables.transformer', function () {
                return new FractalTransformer($this->app->make('datatables.fractal'));
            }
        );

        $this->commands(
            [
                TransformerMakeCommand::class,
            ]
        );
    }

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


Question:
Creates a Descriptor from the provided data.

@param ConstantReflector $data

@return ConstantDescriptor

public function create($data)
    {
        $constantDescriptor = new ConstantDescriptor();
        $constantDescriptor->setName($data->getShortName());
        $constantDescriptor->setValue($data->getValue());
        // Reflection library formulates namespace as global but this is not wanted for phpDocumentor itself
        $constantDescriptor->setNamespace(
            '\\' . (strtolower($data->getNamespace()) == 'global' ? '' :$data->getNamespace())
        );
        $constantDescriptor->setFullyQualifiedStructuralElementName(
            (trim($constantDescriptor->getNamespace(), '\\') ? $constantDescriptor->getNamespace() : '')
            . '\\' . $data->getShortName()
        );

        $this->assembleDocBlock($data->getDocBlock(), $constantDescriptor);

        $constantDescriptor->setLine($data->getLinenumber());

        return $constantDescriptor;
    }

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

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


Question:
Takes a comma separated list of ints, and returns an array of Integers. This is used when processing custom injection
points.

private static List<InjectionData> processIdList(final String list) {
        /* find the individual topic ids */
        final String[] ids = list.split(",");

        List<InjectionData> retValue = new ArrayList<InjectionData>(ids.length);

        /* clean the topic ids */
        for (final String id : ids) {
            final String topicId = id.replaceAll(OPTIONAL_MARKER, "").trim();
            final boolean optional = id.contains(OPTIONAL_MARKER);

            try {
                final InjectionData topicData = new InjectionData(topicId, optional);
                retValue.add(topicData);
            } catch (final NumberFormatException ex) {
                /*
                 * these lists are discovered by a regular expression so we shouldn't have any trouble here with Integer.parse
                 */
                LOG.debug("Unable to convert Injection Point ID into a Number", ex);
                retValue.add(new InjectionData("-1", false));
            }
        }

        return retValue;
    }

public function plugin($md, $ruleName, $tokenType, $iteartor)
    {
        $scan = function($state) use($md, $ruleName, $tokenType, $iteartor) {
            for ($blkIdx = count($state->tokens) - 1; $blkIdx >= 0; $blkIdx--) {
                if ($state->tokens[$blkIdx]->type !== 'inline') {
                    continue;
                }

                $inlineTokens = $state->tokens[$blkIdx]->children;

                for ($i = count($inlineTokens) - 1; $i >= 0; $i--) {
                    if ($inlineTokens[$i]->type !== $tokenType) {
                        continue;
                    }

                    $iteartor($inlineTokens, $i);
                }
            }
        };

        $md->core->ruler->push($ruleName, $scan);
    }

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


Question: Execute HTTP method on path with data

private function run($path, $options)
    {
        $method  = $options['method'];
        $data    = isset($options['data'])    ? $options['data']    : null;
        $params  = isset($options['params'])  ? $options['params']  : null;
        $headers = isset($options['headers']) ? $options['headers'] : array();
        $body    = !empty($data)              ? json_encode($data)  : null;

        // Arrays in constants are in PHP 5.6+
        $allowedHeaders = array(
            'If-None-Match',    // Pairs with `ETag` response header.
            'If-Modified-Since' // Pairs with `Last-Modified` response header.
        );

        $headers = $this->filterOptions($headers, $allowedHeaders);
        $headers['User-Agent']   = $this->userAgent;
        $headers['Content-Type'] = 'application/json';

        if (!empty($headers['If-Modified-Since']) && $headers['If-Modified-Since'] instanceof DateTime) {
            $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s \G\M\T', $headers['If-Modified-Since']->getTimestamp());
        }

        $response = $this->requester->run(array(
            'url'     => self::URL . $this->slug . $path,
            'method'  => $method,
            'params'  => $params,
            'body'    => $body,
            'userpwd' => "$this->email:$this->apiKey",
            'headers' => $headers
        ));

        return $response;
    }

func POST(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {
	return engine().POST(relativePath, handlers...)
}

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


Question: // handle implements a WebSocket handler.

func (r *Reader) handle(ws *websocket.Conn) {
	encode := len(ws.Config().Protocol) > 0 && ws.Config().Protocol[0] == base64BinaryWebSocketProtocol
	defer close(r.err)
	defer ws.Close()
	go ignoreReceives(ws, r.timeout)
	r.err <- messageCopy(ws, r.r, encode, r.ping, r.timeout)
}

def write_response(
        self, status_code: Union[int, constants.HttpStatusCode], *,
        headers: Optional[_HeaderType]=None
            ) -> "writers.HttpResponseWriter":

        self._writer = self.__delegate.write_response(
            constants.HttpStatusCode(status_code),
            headers=headers)

        return self._writer

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


Question:
Normalization and filtering as of Seurat [Satija15]_.

    This uses a particular preprocessing.

    Expects non-logarithmized data. If using logarithmized data, pass `log=False`.

def recipe_seurat(adata, log=True, plot=False, copy=False):

    if copy: adata = adata.copy()
    pp.filter_cells(adata, min_genes=200)
    pp.filter_genes(adata, min_cells=3)
    pp.normalize_per_cell(adata, counts_per_cell_after=1e4)
    filter_result = filter_genes_dispersion(
        adata.X, min_mean=0.0125, max_mean=3, min_disp=0.5, log=not log)
    if plot:
        from ..plotting import _preprocessing as ppp  # should not import at the top of the file
        ppp.filter_genes_dispersion(filter_result, log=not log)
    adata._inplace_subset_var(filter_result.gene_subset)  # filter genes
    if log: pp.log1p(adata)
    pp.scale(adata, max_value=10)
    return adata if copy else None

def download_message(self):
    """"""

    print('Failed to find any ImageNet %s files'% self.subset)
    print('')
    print('If you have already downloaded and processed the data, then make '
          'sure to set --data_dir to point to the directory containing the '
          'location of the sharded TFRecords.\n')
    print('If you have not downloaded and prepared the ImageNet data in the '
          'TFRecord format, you will need to do this at least once. This '
          'process could take several hours depending on the speed of your '
          'computer and network connection\n')
    print('Please see README.md for instructions on how to build '
          'the ImageNet dataset using download_and_preprocess_imagenet.\n')
    print('Note that the raw data size is 300 GB and the processed data size '
          'is 150 GB. Please ensure you have at least 500GB disk space.')

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


Question:
Returns an instance of the command class
@param  string $name The command name in the form 'doCommand'
@return \Ebanx\Command\AbstractCommand
@throws RuntimeException

public static function build($name)
    {
        $class = '\\Ebanx\\Command\\';

        $className = str_replace('do', '', $name);

        if ($className == $name)
        {
            $className = str_replace('get', '', $name);
        }

        $class .= $className;

        // Request command is different depending on the checkout method (Ebanx or direct)
        if ($className == 'Request')
        {
            // Use EBANX direct
            if (\Ebanx\Config::getDirectMode() == true)
            {
                $class .= '\\Direct';
            }
            // Use EBANX checkout
            else
            {
                $class .= '\\Checkout';
            }
        }

        if (class_exists($class))
        {
            return new $class();
        }
        else
        {
            throw new \RuntimeException("Command '$className' doesn't exist.");
        }
    }

public function assertSatisfied()
    {
        foreach ($this->expectations as $expectation) {
            if (!$expectation->isSatisfied()) {
                $comment = $expectation->commentOn($expectation->getMethod(), []);

                if (!$comment) {
                    $comment = "Unsatisfied expectation for method " . $expectation->getMethod();
                }

                throw new UnsatisfiedExpectationException($comment);
            }
        }
    }

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


Question: Return a new identity with the given revision

def rev(self, rev):
        """"""
        d = self.dict
        d['revision'] = rev
        return self.from_dict(d)

func SortByRevision(list []*rspb.Release) {
	s := &sorter{list: list}
	s.less = func(i, j int) bool {
		vi := s.list[i].Version
		vj := s.list[j].Version
		return vi < vj
	}
	sort.Sort(s)
}

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


Question: Be careful this fuction doesn't validate arguments!

function convert(dateTime, pattern, options) {
	// If no pattern provided setting default one
	var defaultPattern = pattern || '%hh%:%mm% %DD%/%MM%/%YYYY%';

	const filters = [
		{
			pattern: /%hh%/g,
			replacement: (function() {
				if(options && options.shortTime && dateTime.getHours() > 12) {
					return dateTime.getHours() - 12;
				} else {
					return validateForOneDigit(dateTime.getHours());
				}
			})()
		},
		{
			pattern: /%mm%/g,
			replacement: validateForOneDigit(dateTime.getMinutes())
		},
		{
			pattern: /%ss%/g,
			replacement: validateForOneDigit(dateTime.getSeconds())
		},
		{
			pattern: /%DD%/g,
			replacement: validateForOneDigit(dateTime.getDate())
		},
		{
			pattern: /%MM%/g,
			replacement: validateForOneDigit(dateTime.getMonth() + 1)
		},
		{
			pattern: /%YYYY%/g,
			replacement: validateForOneDigit(dateTime.getFullYear())
		},
		{
			pattern: /%YY%/g,	//TODO
			replacement: validateForOneDigit(dateTime.getFullYear().toString().slice(2))
		},
		{
			pattern: /%h%/g,
			replacement: (function() {
				if(options && options.shortTime && dateTime.getHours() > 12) {
					return dateTime.getHours() - 12;
				} else {
					return dateTime.getHours();
				}
			})()
		},
		{
			pattern: /%m%/g,
			replacement: dateTime.getMinutes()
		},
		{
			pattern: /%s%/g,
			replacement: dateTime.getSeconds()
		},
		{
			pattern: /%D%/g,
			replacement: dateTime.getDate()
		},
		{
			pattern: /%M%/g,
			replacement: dateTime.getMonth() + 1
		},
		{
			pattern: /%day%/g,
			replacement: days[dateTime.getDay()]
		},
		{
			pattern: /%month%/g,
			replacement: months[dateTime.getMonth()]
		},
		{
			pattern: /%relative%/g,
			replacement: relative(dateTime)
		},
		{
			pattern: /%12h%/g,
			replacement: (function() {
				if(options && options.shortTime) {
					if(dateTime.getHours() > 11) {
						return 'PM';
					} else {
						return 'AM';
					}
				}
			})()
		}
	];

	filters.forEach(function(f) {
		defaultPattern = defaultPattern.replace(f.pattern, f.replacement);
	});

	if(options && options.shortTime &&
	  pattern.indexOf('%12h%') === -1) {
		if(dateTime.getHours() > 11) {
			defaultPattern += ' PM';
		} else {
			defaultPattern += ' AM';
		}
	}

	return defaultPattern;
}

public static function createBoundValidator($methodName, ...$boundArgs)
    {
        return function (...$args) use ($methodName, $boundArgs) {
            return call_user_func_array("self::$methodName", array_merge($boundArgs, $args));
        };
    }

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


Question: InputChannelContext

@Override
	public void queueEnvelope(Envelope envelope) {
		// The sequence number of the envelope to be queued
		final int sequenceNumber = envelope.getSequenceNumber();

		synchronized (this.queuedEnvelopes) {

			if (this.destroyCalled) {
				final Buffer buffer = envelope.getBuffer();
				if (buffer != null) {
					buffer.recycleBuffer();
				}
				return;
			}

			final int expectedSequenceNumber = this.lastReceivedEnvelope + 1;
			if (sequenceNumber != expectedSequenceNumber) {
				// This is a problem, now we are actually missing some data
				reportIOException(new IOException("Expected data packet " + expectedSequenceNumber + " but received " + sequenceNumber));

				// notify that something (an exception) is available
				notifyGateThatInputIsAvailable();

				if (LOG.isDebugEnabled()) {
					LOG.debug("Input channel " + this.toString() + " expected envelope " + expectedSequenceNumber
							+ " but received " + sequenceNumber);
				}

				// rescue the buffer
				final Buffer buffer = envelope.getBuffer();
				if (buffer != null) {
					buffer.recycleBuffer();
				}
			} else {

				this.queuedEnvelopes.add(envelope);
				this.lastReceivedEnvelope = sequenceNumber;
				this.lastSourceID = envelope.getSource();

				// Notify the channel about the new data. notify as much as there is (buffer plus once per event)
				if (envelope.getBuffer() != null) {
					notifyGateThatInputIsAvailable();
				}

				List<? extends AbstractEvent> events = envelope.deserializeEvents();

				if (events != null) {
					for (int i = 0; i < events.size(); i++) {
						notifyGateThatInputIsAvailable();
					}
				}
			}
		}
	}

def connect(self):

        ctx = Context(self.module, self.create_mediator())
        ctx.logger = self.logger
        ctx.default_factory = self.default_factory
        return ctx

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


Question:
Update header

Adds, updates or removes header (if no value is provided)

@param string $field Field name
@param string $value Header value

@access private
@return void

private function updateHeader($field, $value = null)
    {
        $options = $this->getRequestOptions();

        if (!isset($options['headers'])) {
            $options['headers'] = array();
        }

        $options['headers'][$field] = $value;

        $this->setRequestOptions($options);
    }

public function getParameterValue($name)
    {
        return (isset($this->attributes[$name])) ? $this->attributes[$name] : null;
    }

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


Question:
Swaps the keys and values at {@code i} with those at {@code j}

@param keys
@param values
@param i
@param j

private static final <T> void swap(long[] keys, T[] values, double[] probs, int i, int j) {
    long keySwap = keys[i];
    keys[i] = keys[j];
    keys[j] = keySwap;

    T swapValue = values[i];
    values[i] = values[j];
    values[j] = swapValue;

    double swapProb = probs[i];
    probs[i] = probs[j];
    probs[j] = swapProb;
  }

public final ProtoParser.enum_body_return enum_body(Proto proto, Message message, EnumGroup enumGroup) throws RecognitionException {
        ProtoParser.enum_body_return retval = new ProtoParser.enum_body_return();
        retval.start = input.LT(1);

        Object root_0 = null;

        ProtoParser.enum_field_return enum_field124 = null;

        ProtoParser.annotation_entry_return annotation_entry125 = null;

        ProtoParser.option_entry_return option_entry126 = null;

        try {
            // com/dyuproject/protostuff/parser/ProtoParser.g:538:5: ( enum_field[proto, message, enumGroup] | annotation_entry[proto] | option_entry[proto, enumGroup] )
            int alt24=3;
            switch ( input.LA(1) ) {
            case ID:
                {
                alt24=1;
                }
                break;
            case AT:
                {
                alt24=2;
                }
                break;
            case OPTION:
                {
                alt24=3;
                }
                break;
            default:
                if (state.backtracking>0) {state.failed=true; return retval;}
                NoViableAltException nvae =
                    new NoViableAltException("", 24, 0, input);

                throw nvae;
            }

            switch (alt24) {
                case 1 :
                    // com/dyuproject/protostuff/parser/ProtoParser.g:538:9: enum_field[proto, message, enumGroup]
                    {
                    root_0 = (Object)adaptor.nil();

                    pushFollow(FOLLOW_enum_field_in_enum_body2132);
                    enum_field124=enum_field(proto, message, enumGroup);

                    state._fsp--;
                    if (state.failed) return retval;
                    if ( state.backtracking==0 ) adaptor.addChild(root_0, enum_field124.getTree());

                    }
                    break;
                case 2 :
                    // com/dyuproject/protostuff/parser/ProtoParser.g:539:9: annotation_entry[proto]
                    {
                    root_0 = (Object)adaptor.nil();

                    pushFollow(FOLLOW_annotation_entry_in_enum_body2143);
                    annotation_entry125=annotation_entry(proto);

                    state._fsp--;
                    if (state.failed) return retval;
                    if ( state.backtracking==0 ) adaptor.addChild(root_0, annotation_entry125.getTree());

                    }
                    break;
                case 3 :
                    // com/dyuproject/protostuff/parser/ProtoParser.g:540:9: option_entry[proto, enumGroup]
                    {
                    root_0 = (Object)adaptor.nil();

                    pushFollow(FOLLOW_option_entry_in_enum_body2154);
                    option_entry126=option_entry(proto, enumGroup);

                    state._fsp--;
                    if (state.failed) return retval;
                    if ( state.backtracking==0 ) adaptor.addChild(root_0, option_entry126.getTree());

                    }
                    break;

            }
            retval.stop = input.LT(-1);

            if ( state.backtracking==0 ) {

            retval.tree = (Object)adaptor.rulePostProcessing(root_0);
            adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
            }
        }
        catch (RecognitionException re) {
            reportError(re);
            recover(input,re);
    	retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);

        }
        finally {
        }
        return retval;
    }

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


Question: ECMA-262 12.2.9 Template Literals

function parseTemplateElement(option) {
        var node, token;

        if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
            throwUnexpectedToken();
        }

        node = new Node();
        token = lex();

        return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
    }

func (w *ResourcesWriter) Execute(data *ResourceData) error {
	return w.ExecuteTemplate("resource", resourceT, nil, data)
}

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


Question:
生成小于查询的SQL片段.
@param field 数据库字段
@param value 值
@return ZealotKhala实例

public ZealotKhala lessThan(String field, Object value) {
        return this.doNormal(ZealotConst.ONE_SPACE, field, value, ZealotConst.LT_SUFFIX, true);
    }

func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {
	var (
		res    interface{}
		isNull bool
	)
	switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {
	case types.ETInt:
		var intRes int64
		intRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)
		if mysql.HasUnsignedFlag(tp.Flag) {
			res = uint64(intRes)
		} else {
			res = intRes
		}
	case types.ETReal:
		res, isNull, err = sf.EvalReal(sf.GetCtx(), row)
	case types.ETDecimal:
		res, isNull, err = sf.EvalDecimal(sf.GetCtx(), row)
	case types.ETDatetime, types.ETTimestamp:
		res, isNull, err = sf.EvalTime(sf.GetCtx(), row)
	case types.ETDuration:
		res, isNull, err = sf.EvalDuration(sf.GetCtx(), row)
	case types.ETJson:
		res, isNull, err = sf.EvalJSON(sf.GetCtx(), row)
	case types.ETString:
		res, isNull, err = sf.EvalString(sf.GetCtx(), row)
	}

	if isNull || err != nil {
		d.SetValue(nil)
		return d, err
	}
	d.SetValue(res)
	return
}

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


Question:
Retrieve the header title to display

@return string

protected function getTitle()
    {
        if ($this->formTitle) {
            return $this->formTitle;
        } elseif ($this->createData) {
            return sprintf($this->_('New %s...'), $this->getTopic());
        } else {
            return sprintf($this->_('Edit %s'), $this->getTopic());
        }
    }

public function render(OutputInterface $output, ResultCollection $results)
    {
        $output->write($this->getHeader());

        $table = new Table($output);
        $table->setHeaders(['File', 'Times Changed', 'Complexity', 'Score']);
        $table->addRows($results->toArray());
        $table->render();

        $output->write("\n");
    }

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


Question:
Get the page name.

@return string

public function getCollectionName()
    {
        if (isset($this->vObj)) {
            return isset($this->vObj->cvName) ? $this->vObj->cvName : null;
        }

        return isset($this->cvName) ? $this->cvName : null;
    }

def comicPageLink(self, comic, url, prevUrl):
        """"""
        pageInfo = self.getPageInfo(comic, url)
        pageInfo['prev'] = prevUrl

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


Question: // GetSpaceForBinding returns the space name associated with the specified endpoint.

func (u *Unit) GetSpaceForBinding(bindingName string) (string, error) {
	app, err := u.Application()
	if err != nil {
		return "", errors.Trace(err)
	}

	bindings, err := app.EndpointBindings()
	if err != nil {
		return "", errors.Trace(err)
	}
	boundSpace, known := bindings[bindingName]
	if !known {
		// If default binding is not explicitly defined we'll use default space
		if bindingName == environs.DefaultSpaceName {
			return environs.DefaultSpaceName, nil
		}
		return "", errors.NewNotValid(nil, fmt.Sprintf("binding name %q not defined by the unit's charm", bindingName))
	}
	return boundSpace, nil
}

func (c *ChannelData) URI() string {
	return fmt.Sprintf("%s://%s/%s", c.Protocol, c.Server, c.Channel)
}

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


Question:
Sets the report formats to use.

@param string $reports A list of report types, delimited by spaces,
commas or semicolons.

@return void

public function setReports($reports)
    {
        $this->_reports = array();
        $token          = ' ,;';
        $report         = strtok($reports, $token);

        while ($report !== false) {
            $this->_reports[] = $reports;
            $report           = strtok($token);
        }

    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
          [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
          [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
          [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
          [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
          [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
          [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
          [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
          [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
          [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
          [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
          [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
          [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ],
          [ '--exact-matching', '-8', GetoptLong::NO_ARGUMENT ],
          [ '--job-notes', '-k', GetoptLong::OPTIONAL_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--help', '-h'
              help
              exit 0
            when '--tag', '-t'
              @tags << arg
            when '--tag-use-and', '-a'
              @match_all = true
            when '--tag-use-or', '-o'
              @match_all = false
            when '--array', '-a'
              @array_names << arg
            when '--deployment', '-e'
              @deployment_names << arg
            when '--template', '-m'
              @template = arg
            when '--script', '-s'
              set_action(:action_rightscript)
              if arg == ""
                # Empty but not nil means show list of operational scripts to choose from
                @script = ""
              else
                @script = arg
              end
            when '--ssh', '-x'
              set_action(:action_ssh)
              @break_array_into_instances = true
              if arg == ""
                print "Enter SSH command line to execute: "
                @ssh = gets.chomp
              else
                @ssh = arg
              end
            when '--ssh-user', '-u'
              @ssh_user = arg
            when '--input', '-i'
              arg =~ /(.+)=(.+)/
              @inputs[$1]=$2
            when '--set-template', '-m'
              set_action(:action_set)
              @template = arg
            when '--set-tag', '-w'
              set_action(:action_set)
              @set_tags << arg
            when '--report', '-b'
              set_action(:action_report)
              @report = arg
              @@verbose = false
              @@quiet = true
              @break_array_into_instances = true
              @concurrency = 5 if @concurrency == 1
            when '--progress', '-p'
              @progress = @progress ? false : true
            when '--noprompt', '-z'
              @prompt = false
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--hold', '-7'
              @hold = true
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--limit', '-l'
              @limit_start, @limit_end = arg.split(',')
            when '--verbose', '-v'
              @@verbose = true
              Log.threshold = Logger::DEBUG
            when '--quiet', '-q'
              @@quiet = true
            when '--dont-check-templates', '-0'
              @dont_check_templates_for_script = true
            when '--version'
              puts VERSION
              exit 0
            when '--chimpd'
              @use_chimpd = true
              unless arg.empty?
                if arg =~ /[\d]+\.[\d]+\.[\d]+\.[\d]+:[\d]+/
                  @chimpd_host, @chimpd_port = arg.split(':')
                  @chimpd_port = @chimpd_port.to_i
                else
                  @chimpd_port = arg.to_i
                end
              end
            when '--chimpd-wait-until-done'
              @use_chimpd = true
              @chimpd_wait_until_done = true
            when '--dry-run', '-n'
              @dry_run = true
            when '--ignore-errors', '-9'
              @ignore_errors = true
            when '--group', '-g'
              @group = arg.to_sym
            when '--group-type'
              @group_type = arg.to_sym
            when '--group-concurrency'
              @group_concurrency = arg.to_i
            when '--job-notes'
              @job_notes = arg
            when '--timing-log'
              @timing_log = arg
            when '--timeout'
              @timeout = arg
            when '--noverify'
              @verify = false
            when '--exact-matching'
              @exact = true
          end
        end

        if @use_chimpd && ( @script.nil? || @script.empty? )
          if @chimpd_wait_until_done == false
            puts "#######################################################"
            puts "ERROR: --script cannot be empty when sending to chimpd"
            puts "#######################################################"
            exit 1
          end
        end

      rescue GetoptLong::InvalidOption => ex
        help
        exit 1
      end

      #
      # Before we're totally done parsing command line options,
      # let's make sure that a few things make sense
      #
      if @group_concurrency > @concurrency
        @concurrency = @group_concurrency
      end
    end

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


Question:
Removes the referencing list items from the given item

@param \Aimeos\MW\View\Iface $view View object
@param array $ids List of referenced IDs

protected function deleteItems( \Aimeos\MW\View\Iface $view, array $ids )
	{
		$cntl = \Aimeos\Controller\Frontend::create( $this->getContext(), 'customer' );
		$item = $cntl->uses( ['product' => ['watch']] )->get();

		foreach( $ids as $id )
		{
			if( ( $listItem = $item->getListItem( 'product', 'watch', $id ) ) !== null ) {
				$cntl->deleteListItem( 'product', $listItem );
			}
		}

		$cntl->store();
	}

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question:
Injects the number of layouts connected to the shared layout
provided by the event.

public function onBuildView(CollectViewParametersEvent $event): void
    {
        $view = $event->getView();
        if (!$view instanceof LayoutViewInterface) {
            return;
        }

        if ($view->getContext() !== ViewInterface::CONTEXT_ADMIN) {
            return;
        }

        $layout = $view->getLayout();

        $relatedLayoutsCount = 0;
        if ($layout->isShared() && $layout->isPublished()) {
            $relatedLayoutsCount = $this->layoutService->getRelatedLayoutsCount($layout);
        }

        $event->addParameter('related_layouts_count', $relatedLayoutsCount);
    }

public function create()
    {
        // Is this user allowed to do this?
        if (!$this->repository->isUserAllowed('create'))
        {
            Session::flash('status_code', 400 );
            $message = "You are not allowed to create ".$this->table_type_plural;
            Session::flash('message', $message);
            return view('formhandling::warnings/' . config('lasallecmsadmin.admin_template_name') . '/user_not_allowed', [
                'package_title'        => $this->package_title,
                'table_type_plural'    => $this->table_type_plural,
                'table_type_singular'  => $this->table_type_singular,
                'resource_route_name'  => $this->resource_route_name,
                'HTMLHelper'           => HTMLHelper::class,
            ]);
        }

        return view('formhandling::lookuptables/' . config('lasallecmsadmin.admin_template_name') . '/create', [
            'package_title'        => $this->package_title,
            'table_type_plural'    => $this->table_type_plural,
            'table_type_singular'  => $this->table_type_singular,
            'resource_route_name'  => $this->resource_route_name,
            'DatesHelper'          => DatesHelper::class,
            'HTMLHelper'           => HTMLHelper::class,
        ]);
    }

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


Question:
****************************************
运行代码
****************************************

function runCode(code, context) {
    let model = {},
        sandbox = { __dirname: path.cwd(), ...context };

    // 配置沙盒
    sandbox.module = { exports: model };
    sandbox.exports = model;
    sandbox.require = name => require(
        name.match(/^\.{0,2}\//) ? path.resolve(sandbox.__dirname, name) : name
    );

    // 配置文件名
    if (!sandbox.__filename) {
        sandbox.__filename = path.resolve(sandbox.__dirname, 'vm.js');
    }

    // 沙盒运行
    vm.createContext(sandbox);
    vm.runInContext(code, sandbox);

    // 返回结果
    return sandbox.module.exports;
}

function f_rol_sil_kullanici(_kul_id, _tahta_id, _rol_id) {
        if (_rol_id) {
            return result.dbQ.hget_json_parse(result.kp.tahta.hsUyeleri(_tahta_id), _kul_id)
                .then(function (_arrUyeRolId) {
                    // tek bir sayı ya da bir dizi gelebilir ve biz diziyle yola devam etmek için concat yapıyoruz
                    _arrUyeRolId = [].concat(_arrUyeRolId);
                    var idxOfRolId = _arrUyeRolId.indexOf(_rol_id);
                    l.info("idxOfRolId>" + idxOfRolId);

                    if (idxOfRolId == -1) {
                        return 0;
                    } else {
                        _arrUyeRolId.splice(idxOfRolId, 1);
                        return result.dbQ.hset(result.kp.tahta.hsUyeleri(_tahta_id), _kul_id, JSON.stringify(_arrUyeRolId));
                    }
                });
        } else {
            l.warning("Silinecek aktif bir rol bulunamadı");
        }
    }

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


Question:
@param          $entry
@param callable $closure

@return bool

public static function delegateNegated($entry, \Closure $closure)
    {
        $isNegated = function (&$property) {
            return $property[0] === '!' && $property = substr($property, 1);
        };

        $negated = is_scalar($entry) ? $isNegated($entry) : false;
        $result = $closure($entry);

        return $negated !== $result ? ($negated ? !$result : $result) : false;
    }

public function getSelector()
	{
		$direct_settings = array(
			'className', 'css', 'id', 'linkText', 'name', 'partialLinkText', 'tagName', 'xpath', 'label',
		);

		foreach ( $direct_settings as $direct_setting ) {
			if ( $this->$direct_setting ) {
				return array($direct_setting => $this->$direct_setting);
			}
		}

		if ( $this->how && $this->using ) {
			if ( !in_array($this->how, $direct_settings) ) {
				throw new AnnotationException(
					"FindBy annotation expects 'how' to be one of \\QATools\\QATools\\PageObject\\How class constants",
					AnnotationException::TYPE_INCORRECT_USAGE
				);
			}

			return array($this->how => $this->using);
		}

		throw new AnnotationException(
			sprintf(
				"FindBy annotation requires one of '%s' or both 'how' and 'using' parameters specified",
				implode("', '", $direct_settings)
			),
			AnnotationException::TYPE_INCORRECT_USAGE
		);
	}

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


Question: Builds a http object using the data given

def build_http_object(uri)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true if uri.scheme == 'https'
      if @ssl_enabled
        http.cert_store = @cert_store if @cert_store
      else http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      http.read_timeout = @timeout if @timeout # Timeout for a request
      http.open_timeout = @timeout if @timeout # Timeout for a connection
      http
    end

public function listRequestLogs(DiagnosticsApi\ListRequestLogsOptions $options = null)
    {
        list($response) = $this->listRequestLogsWithHttpInfo($options);
        return $response;
    }

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


Question:
Parse a '+' redis simple string response but forward the offsets
onto convertBufferRange to generate a string.
@param {JavascriptRedisParser} parser
@returns {undefined|string|Buffer}

function parseSimpleString (parser) {
  const start = parser.offset
  const buffer = parser.buffer
  const length = buffer.length - 1
  var offset = start

  while (offset < length) {
    if (buffer[offset++] === 13) { // \r\n
      parser.offset = offset + 1
      if (parser.optionReturnBuffers === true) {
        return parser.buffer.slice(start, offset - 1)
      }
      return parser.buffer.toString('utf8', start, offset - 1)
    }
  }
}

function(packedValue)
    {

        var result;

        var t = typeof(packedValue);
        if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
        {
            result = this.handleError(packedValue);
        }
        else if (packedValue instanceof Array)
        {
            result = [];
            for (var i = 0; i < packedValue.length; i++)
            {
                result[i] = this.deserialize(packedValue[i]);
            }
        }
        else if (t == "object")
        {
            for(var i = 0; i < packedValue.newTypes.length; i++)
            {
                this.addTypeDataToCache(packedValue.newTypes[i]);
            }
            for (var aRefID in packedValue.newRefs)
            {
                this.createProxy(aRefID, packedValue.newRefs[aRefID]);
            }
            if (packedValue.type == FABridge.TYPE_PRIMITIVE)
            {
                result = packedValue.value;
            }
            else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
            {
                result = this.getFunctionProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
            {
                result = this.getProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
            {
                result = packedValue.value;
            }
        }
        return result;
    }

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


Question:
Returns the requested content back in unicode.

    :param r: Response object to get unicode content from.

    Tried:

    1. charset from content-type
    2. fall back and replace all unicode characters

    :rtype: str

def get_unicode_from_response(r):

    warnings.warn((
        'In requests 3.0, get_unicode_from_response will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    tried_encodings = []

    # Try charset from content-type
    encoding = get_encoding_from_headers(r.headers)

    if encoding:
        try:
            return str(r.content, encoding)
        except UnicodeError:
            tried_encodings.append(encoding)

    # Fall back:
    try:
        return str(r.content, encoding, errors='replace')
    except TypeError:
        return r.content

def store_seriestext(str, encoding)  # :nodoc:
    ruby_19 { str = convert_to_ascii_if_ascii(str) }

    record   = 0x100D          # Record identifier.
    length   = 0x0000          # Number of bytes to follow.
    id       = 0x0000          # Text id.
    # str                      # Text.
    # encoding                 # String encoding.
    cch      = str.bytesize      # String length.

    encoding ||= 0

    # Character length is num of chars not num of bytes
    cch /= 2 if encoding != 0

    # Change the UTF-16 name from BE to LE
    str = str.unpack('v*').pack('n*') if encoding != 0

    length = 4 + str.bytesize

    header = [record, length].pack('vv')
    data  = [id].pack('v')
    data += [cch].pack('C')
    data += [encoding].pack('C')

    append(header, data, str)
  end

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


Question: // underlyingPtrType dereferences a pointer

func underlyingPtrType(val interface{}) (interface{}, bool) {
	refVal := reflect.ValueOf(val)

	switch refVal.Kind() {
	case reflect.Ptr:
		if refVal.IsNil() {
			return nil, false
		}
		convVal := refVal.Elem().Interface()
		return convVal, true
	}

	return nil, false
}

def delete_ptr_records(self, device, ip_address=None):

        device_type = self._resolve_device_type(device)
        href, svc_name = self._get_ptr_details(device, device_type)
        uri = "/rdns/%s?href=%s" % (svc_name, href)
        if ip_address:
            uri = "%s&ip=%s" % (uri, ip_address)
        resp, resp_body = self._async_call(uri, method="DELETE",
                has_response=False,
                error_class=exc.PTRRecordDeletionFailed)
        return resp_body.get("status") == "COMPLETED"

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


Question: Reset the display.

def reset(self):
        """"""
        if self._rst is None:
            return
        # Set reset high for a millisecond.
        self._rst.value = True
        time.sleep(0.001)
        # Set reset low for 10 milliseconds.
        self._rst.value = False
        time.sleep(0.010)
        # Set reset high again.
        self._rst.value = False

public void setDescription(final String DESCRIPTION) {
        if (null == description) {
            _description = DESCRIPTION;
            fireTileEvent(VISIBILITY_EVENT);
            fireTileEvent(REDRAW_EVENT);
        } else {
            description.set(DESCRIPTION);
        }
    }

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


Question:
/*
(non-Javadoc)

@see com.baidu.bjf.remoting.protobuf.utils.compiler.AbstractCompiler#doCompile(java.lang.String,
java.lang.String, java.io.OutputStream)

@Override
    public synchronized Class<?> doCompile(String name, String sourceCode, OutputStream os) throws Throwable {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Begin to compile source code: class is '{}'", name);
        }

        int i = name.lastIndexOf('.');
        String packageName = i < 0 ? "" : name.substring(0, i);
        String className = i < 0 ? name : name.substring(i + 1);
        JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode);
        javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName,
                className + ClassUtils.JAVA_EXTENSION, javaFileObject);

        DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
        Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options, null,
                Arrays.asList(new JavaFileObject[] { javaFileObject })).call();
        if (result == null || !result.booleanValue()) {
            throw new IllegalStateException(
                    "Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector.getDiagnostics());
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("compile source code done: class is '{}'", name);
            LOGGER.debug("loading class '{}'", name);
        }

        Class<?> retClass = classLoader.loadClass(name);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("loading class done  '{}'", name);
        }

        if (os != null) {
            byte[] bytes = classLoader.loadClassBytes(name);
            if (bytes != null) {
                os.write(bytes);
                os.flush();
            }
        }
        return retClass;
    }

final public List SetString() throws ParseException {
                     List ans = new ArrayList(); Token tok;
    jj_consume_token(11);
    tok = jj_consume_token(STRING_LITERAL);
      ans.add(ParseUtil.parseStringLiteral(tok.image));
    label_2:
    while (true) {
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case 13:
        ;
        break;
      default:
        jj_la1[15] = jj_gen;
        break label_2;
      }
      jj_consume_token(13);
      tok = jj_consume_token(STRING_LITERAL);
        ans.add(ParseUtil.parseStringLiteral(tok.image));
    }
    jj_consume_token(12);
    {if (true) return ans;}
    throw new Error("Missing return statement in function");
  }

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


Question:
Sets the {@link ReporterMetrics} instance to use.

@param metrics The metrics instance

@Inject
    public void setReporterMetrics(@Nullable ReporterMetrics metrics) {
        if (metrics != null) {
            builder.metrics(metrics);
        }
    }

def _get_stitch_report_path(self):
        """"""
        if self.Parameters['-r'].isOn():
            stitch_path = self._absolute(str(self.Parameters['-r'].Value))
            return stitch_path
        elif self.Parameters['-r'].isOff():
            return None

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


Question:
cu: cmp and exid with ~ as a delimiter

{@inheritdoc}

public function format(ParameterBag $trackingParameters)
    {
        $cu = null;

        if (
            $trackingParameters->has('c')
            && $trackingParameters->has('u')
        ) {
            $cu = sprintf(
                '%s~%s',
                $trackingParameters->get('c'),
                $trackingParameters->get('u')
            );
        }

        return [
            'cu' => $cu,
        ];
    }

def _ExtractList(self, fields, ignores=(",",), terminators=()):
    """"""
    extracted = []
    i = 0
    for i, field in enumerate(fields):
      # Space-separated comma; ignore, but this is not a finished list.
      # Similar for any other specified ignores (eg, equals sign).
      if field in ignores:
        continue

      # However, some fields are specifically meant to terminate iteration.
      if field in terminators:
        break

      extracted.append(field.strip("".join(ignores)))
      # Check for continuation; this will either be a trailing comma or the
      # next field after this one being a comma. The lookahead here is a bit
      # nasty.
      if not (field.endswith(",") or
              set(fields[i + 1:i + 2]).intersection(ignores)):
        break

    return extracted, fields[i + 1:]

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