Question:
{@inheritdoc}

{@inheritdoc}

@param array $array
{@inheritdoc}

public function copyFromArray(array &$array)
    {
        // grantType
        $this->setGrantType(
            GrantType::valueOf(
                LanguageUtility::getFromArray('grantType', $array)));

        // clientId
        $this->setClientId(
            LanguageUtility::getFromArray('clientId', $array));

        // subject
        $this->setSubject(
            LanguageUtility::getFromArray('subject', $array));

        // scopes
        $this->setScopes(
            LanguageUtility::getFromArray('scopes', $array));

        // accessTokenDuration
        $this->setAccessTokenDuration(
            LanguageUtility::getFromArray('accessTokenDuration', $array));

        // refreshTokenDuration
        $this->setRefreshTokenDuration(
            LanguageUtility::getFromArray('refreshTokenDuration', $array));

        // properties
        $properties = LanguageUtility::getFromArray('properties', $array);
        $this->setProperties(
            LanguageUtility::convertArrayToArrayOfArrayCopyable(
                $properties, __NAMESPACE__ . '\Property'));

        // clientIdAliasUsed
        $this->setClientIdAliasUsed(
            LanguageUtility::getFromArrayAsBoolean('clientIdAliasUsed', $array));

        // accessToken
        $this->setAccessToken(
            LanguageUtility::getFromArray('accessToken', $array));

        // refreshToken
        $this->setRefreshToken(
            LanguageUtility::getFromArray('refreshToken', $array));
    }

protected function createController($controller)
    {
        if (false === strpos($controller, '::')) {
            throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
        }

        list($class, $method) = explode('::', $controller, 2);

        if (!class_exists($class)) {
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
        }

        $controller = new $class();
        if ($controller instanceof ContainerAwareInterface) {
            $controller->setContainer($this->container);
        }

        if ($this->container->has('dashboard.view')) {
            $view = $this->container->get('dashboard.view');
            $loader = $view->getLoader();

            if ($path = $this->getViewsPath($controller, $this->container->getParameter('dashboard.widgets_dir'))) {
                $loader->addPath($path);
                $view->setLoader($loader);
                $this->container->set('view', $view);
            }
        }

        return array($controller, $method);
    }

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


Question: // NumErrorWarnings gets warning and error count.

func (sc *StatementContext) NumErrorWarnings() (ec, wc string) {
	var (
		ecNum uint16
		wcNum int
	)
	sc.mu.Lock()
	ecNum = sc.mu.errorCount
	wcNum = len(sc.mu.warnings)
	sc.mu.Unlock()

	if ecNum == 0 {
		ec = zero
	} else {
		ec = strconv.Itoa(int(ecNum))
	}

	if wcNum == 0 {
		wc = zero
	} else {
		wc = strconv.Itoa(wcNum)
	}
	return
}

func (mh *MethodHandler) StatusCodes(codes ...int) *MethodHandler {
	if mh.statusCodes == nil {
		mh.statusCodes = make([]int, 0)
	}
	mh.statusCodes = append(mh.statusCodes, codes...)
	return mh
}

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


Question:
Stores 2nd parameter at stack pointer (SP) + X, being
    X 1st parameter.

    1st operand must be a SIGNED integer.

def _pstoref16(ins):

    value = ins.quad[2]
    offset = ins.quad[1]
    indirect = offset[0] == '*'
    if indirect:
        offset = offset[1:]

    I = int(offset)
    if I >= 0:
        I += 4  # Return Address + "push IX"

    output = _f16_oper(value)

    if indirect:
        output.append('ld bc, %i' % I)
        output.append('call __PISTORE32')
        REQUIRES.add('pistore32.asm')
        return output

    # direct store
    output.append('ld bc, %i' % I)
    output.append('call __PSTORE32')
    REQUIRES.add('pstore32.asm')

    return output

function writeNaptr(buff, val, label_index) {
  assertUndefined(val.order, 'NAPTR record requires "order"');
  assertUndefined(val.preference, 'NAPTR record requires "preference"');
  assertUndefined(val.flags, 'NAPTR record requires "flags"');
  assertUndefined(val.service, 'NAPTR record requires "service"');
  assertUndefined(val.regexp, 'NAPTR record requires "regexp"');
  assertUndefined(val.replacement, 'NAPTR record requires "replacement"');
  buff.writeUInt16BE(val.order & 0xFFFF);
  buff.writeUInt16BE(val.preference & 0xFFFF);
  buff.writeUInt8(val.flags.length);
  buff.write(val.flags, val.flags.length, 'ascii');
  buff.writeUInt8(val.service.length);
  buff.write(val.service, val.service.length, 'ascii');
  buff.writeUInt8(val.regexp.length);
  buff.write(val.regexp, val.regexp.length, 'ascii');
  namePack(val.replacement, buff, label_index);
  return WRITE_RESOURCE_DONE;
}

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


Question: // TaskIdFromNodeAndId indicates to return the task on the given node with specified id.

func (s *TasksGetTaskService) TaskIdFromNodeAndId(nodeId string, id int64) *TasksGetTaskService {
	s.taskId = fmt.Sprintf("%s:%d", nodeId, id)
	return s
}

function _method(node, print) {
  var value = node.value;
  var kind = node.kind;
  var key = node.key;

  if (kind === "method" || kind === "init") {
    if (value.generator) {
      this.push("*");
    }
  }

  if (kind === "get" || kind === "set") {
    this.push(kind + " ");
  }

  if (value.async) this.push("async ");

  if (node.computed) {
    this.push("[");
    print.plain(key);
    this.push("]");
  } else {
    print.plain(key);
  }

  this._params(value, print);
  this.space();
  print.plain(value.body);
}

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


Question:
Write the `summary` JSON to `cache_dir`.

    Updated the accessed timestamp to now before writing.

def write_summary(summary: dict, cache_dir: str):

    # update the summary last-accessed timestamp
    summary['accessed'] = time()
    with open(join(cache_dir, 'summary.json'), 'w') as summary_file:
        summary_file.write(json.dumps(summary, indent=4, sort_keys=True))

func (a *AssetsCache) GenerateCacheKey(assetPath string) (*AssetCacheKey, error) {
	info, err := os.Stat(assetPath)
	if err != nil {
		return nil, err
	}
	key := info.ModTime().Unix()
	return &AssetCacheKey{assetPath, key}, nil
}

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


Question:
Processes this test, when one of its tokens is encountered.

@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param integer              $stackPtr  The position of the current token in
the token stack.

@return void

public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $fileName = $phpcsFile->getFilename();
        if ($this->shouldIgnoreMissingNamespace($fileName)) {
            return;
        }

        $tokens = $phpcsFile->getTokens();
        $errorData = array(strtolower($tokens[$stackPtr]['content']));
        $namespace = $phpcsFile->findPrevious(T_NAMESPACE, ($stackPtr - 1));
        if ($namespace === false) {
            $error = 'Each %s must be in a namespace of at least one level (a top-level vendor name)';
            $phpcsFile->addError($error, $stackPtr, 'MissingNamespace', $errorData);
        }
    }

public static function readFile(string $filename, string $rootDir = '.', ParserInterface $parser = null): array
    {
        $data = ['@import' => $filename];

        $story = new Complex($rootDir);
        $parser = $parser ?? new Standard;

        $parser->parse($data, $story);
        return $data;
    }

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


Question:
Creates and returns TextView objects based on WebElements

@return an ArrayList with TextViews

private ArrayList <TextView> createAndReturnTextViewsFromWebElements(boolean javaScriptWasExecuted){
		ArrayList<TextView> webElementsAsTextViews = new ArrayList<TextView>();

		if(javaScriptWasExecuted){
			for(WebElement webElement : webElementCreator.getWebElementsFromWebViews()){
				if(isWebElementSufficientlyShown(webElement)){
					RobotiumTextView textView = new RobotiumTextView(inst.getContext(), webElement.getText(), webElement.getLocationX(), webElement.getLocationY());
					webElementsAsTextViews.add(textView);
				}
			}
		}
		return webElementsAsTextViews;
	}

private static void initializeNode(Element node) {
        node.attr(CONTENT_SCORE, Integer.toString(0));

        String tagName = node.tagName();
        if ("div".equalsIgnoreCase(tagName)) {
            incrementContentScore(node, 5);
        } else if ("pre".equalsIgnoreCase(tagName)
                || "td".equalsIgnoreCase(tagName)
                || "blockquote".equalsIgnoreCase(tagName)) {
            incrementContentScore(node, 3);
        } else if ("address".equalsIgnoreCase(tagName)
                || "ol".equalsIgnoreCase(tagName)
                || "ul".equalsIgnoreCase(tagName)
                || "dl".equalsIgnoreCase(tagName)
                || "dd".equalsIgnoreCase(tagName)
                || "dt".equalsIgnoreCase(tagName)
                || "li".equalsIgnoreCase(tagName)
                || "form".equalsIgnoreCase(tagName)) {
            incrementContentScore(node, -3);
        } else if ("h1".equalsIgnoreCase(tagName)
                || "h2".equalsIgnoreCase(tagName)
                || "h3".equalsIgnoreCase(tagName)
                || "h4".equalsIgnoreCase(tagName)
                || "h5".equalsIgnoreCase(tagName)
                || "h6".equalsIgnoreCase(tagName)
                || "th".equalsIgnoreCase(tagName)) {
            incrementContentScore(node, -5);
        }

        incrementContentScore(node, getClassWeight(node));
    }

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


Question:
Edit the details of Content.

@param Request $request
@param int     $id

@return Response

public function editAction(Request $request, $id)
    {
        /** @var ContentManager $manager */
        $manager = $this->get('opifer.content.content_manager');
        $em = $manager->getEntityManager();
        $content = $manager->getRepository()->find($id);
        $content = $manager->createMissingValueSet($content);

        // Load the contentTranslations for the content group
        if ($content->getTranslationGroup() !== null) {
            $contentTranslations = $content->getTranslationGroup()->getContents()->filter(function($contentTranslation) use ($content) {
                return $contentTranslation->getId() !== $content->getId();
            });

            $content->setContentTranslations($contentTranslations);
        }

        $form = $this->createForm(ContentType::class, $content);

        $originalContentItems = new ArrayCollection();
        foreach ($content->getContentTranslations() as $contentItem) {
            $originalContentItems->add($contentItem);
        }

        $form->handleRequest($request);

        if ($form->isValid()) {
            if (null === $content->getPublishAt()) {
                $content->setPublishAt($content->getCreatedAt());
            }

            if ($content->getTranslationGroup() === null) {
                // Init new group
                $translationGroup = new TranslationGroup();
                $content->setTranslationGroup($translationGroup);
            }

            // Make sure all the contentTranslations have the same group as content
            $contentTranslationIds = [$content->getId()];
            foreach($content->getContentTranslations() as $contentTranslation) {
                if ($contentTranslation->getTranslationGroup() === null) {
                    $contentTranslation->setTranslationGroup($content->getTranslationGroup());
                    $em->persist($contentTranslation);
                }

                $contentTranslationIds[] = $contentTranslation->getId();
            }

            // Remove possible contentTranslations from the translationGroup
            $queryBuilder = $manager->getRepository()->createQueryBuilder('c');
            $queryBuilder->update()
                ->set('c.translationGroup', 'NULL')
                ->where($queryBuilder->expr()->eq('c.translationGroup', $content->getTranslationGroup()->getId()))
                ->where($queryBuilder->expr()->notIn('c.id', $contentTranslationIds))
                ->getQuery()
                ->execute();

            $em->persist($content);

            $em->flush();

            return $this->redirectToRoute('opifer_content_content_index');
        }

        return $this->render($this->getParameter('opifer_content.content_edit_view'), [
            'content' => $content,
            'form' => $form->createView(),
        ]);
    }

public function delete()
    {
        if (!$this->hasRequestParameter('uri') || !$this->hasRequestParameter('path') || !$this->hasRequestParameter('lang')) {
            throw new common_exception_MissingParameter();
        }

        $item = $this->getResource($this->getRequestParameter('uri'));
        $itemLang = $this->getRequestParameter('lang');

        $resolver = new ItemMediaResolver($item, $itemLang);
        $asset = $resolver->resolve($this->getRequestParameter('path'));
        $deleted = $asset->getMediaSource()->delete($asset->getMediaIdentifier());

        return $this->returnJson(array('deleted' => $deleted));
    }

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


Question:
Compare two version numbers represented as strings.

@param  String  a  Version a
@param  String  b  Version b
@return Number

function cmpVersion(a, b) {
    "use strict";
    var i, cmp, len, re = /(\.0)+[^\.]*$/;
    a = versionToString(a);
    b = versionToString(b);
    a = (a + '').replace(re, '').split('.');
    b = (b + '').replace(re, '').split('.');
    len = Math.min(a.length, b.length);
    for (i = 0; i < len; i++) {
        cmp = parseInt(a[i], 10) - parseInt(b[i], 10);
        if (cmp !== 0) {
            return cmp;
        }
    }
    return a.length - b.length;
}

private CompositeExpression parseComparisonRange() {
        Token token = tokens.lookahead();
        CompositeExpression expr;
        switch (token.type) {
            case EQUAL:
                tokens.consume();
                expr = eq(parseVersion());
                break;
            case NOT_EQUAL:
                tokens.consume();
                expr = neq(parseVersion());
                break;
            case GREATER:
                tokens.consume();
                expr = gt(parseVersion());
                break;
            case GREATER_EQUAL:
                tokens.consume();
                expr = gte(parseVersion());
                break;
            case LESS:
                tokens.consume();
                expr = lt(parseVersion());
                break;
            case LESS_EQUAL:
                tokens.consume();
                expr = lte(parseVersion());
                break;
            default:
                expr = eq(parseVersion());
        }
        return expr;
    }

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


Question: // SetReadDeadline sets the deadline for future Read calls.

func (bufc *bufConn) SetReadDeadline(t time.Time) error {
	return bufc.conn.SetReadDeadline(t)
}

def __sync(self):
    """"""
    pad_length = _BLOCK_SIZE - self.__reader.tell() % _BLOCK_SIZE
    if pad_length and pad_length != _BLOCK_SIZE:
      data = self.__reader.read(pad_length)
      if len(data) != pad_length:
        raise EOFError('Read %d bytes instead of %d' %
                       (len(data), pad_length))

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


Question:
Produce help output related to operands.

    Input:
       Request Handle

def showOperandLines(rh):

    if rh.function == 'HELP':
        rh.printLn("N", "  For the GetHost function:")
    else:
        rh.printLn("N", "Sub-Functions(s):")
    rh.printLn("N", "      diskpoolnames - " +
        "Returns the names of the directory manager disk pools.")
    rh.printLn("N", "      diskpoolspace - " +
        "Returns disk pool size information.")
    rh.printLn("N", "      fcpdevices    - " +
        "Lists the FCP device channels that are active, free, or")
    rh.printLn("N", "                      offline.")
    rh.printLn("N", "      general       - " +
        "Returns the general information related to the z/VM")
    rh.printLn("N", "                      hypervisor environment.")
    rh.printLn("N", "      help          - Returns this help information.")
    rh.printLn("N", "      version       - Show the version of this function")
    if rh.subfunction != '':
        rh.printLn("N", "Operand(s):")
    rh.printLn("N", "      <poolName>    - Name of the disk pool.")

    return

func (c *Client) PutPolicy(vhost string, name string, policy Policy) (res *http.Response, err error) {
	body, err := json.Marshal(policy)
	if err != nil {
		return nil, err
	}

	req, err := newRequestWithBody(c, "PUT", "policies/"+PathEscape(vhost)+"/"+PathEscape(name), body)
	if err != nil {
		return nil, err
	}

	res, err = executeRequest(c, req)
	if err != nil {
		return nil, err
	}

	return res, nil
}

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


Question:
Sets properties of renderers using data from current row

@param mixed $data the data object being used to render the cell
renderers of this field.

protected function setupRenderers($data)
    {
        if (count($this->renderers) === 0) {
            throw new SwatException(
                'No renderer has been provided for this column.'
            );
        }

        $sensitive = $this->view->isSensitive();

        // Set the properties of the renderers to the value of the data field.
        foreach ($this->renderers as $renderer) {
            $this->renderers->applyMappingsToRenderer($renderer, $data);
            $renderer->sensitive = $renderer->sensitive && $sensitive;
        }
    }

def main(list_ids, model, contact_server, raw_data_id, show_raw,
         mysql_cfg='mysql_online'):
    """"""
    if list_ids:
        preprocessing_desc, _, _ = _get_system(model)
        raw_datapath = os.path.join(utils.get_project_root(),
                                    preprocessing_desc['data-source'])
        _list_ids(raw_datapath)
    else:
        if contact_server:
            data = _fetch_data_from_server(raw_data_id, mysql_cfg)
            print("hwrt version: %s" % hwrt.__version__)
            if data is not None:
                display_data(data['data'], data['id'], model, show_raw)
        else:
            logging.info("RAW_DATA_ID %i does not exist or "
                         "database connection did not work.", raw_data_id)
            # The data was not on the server / the connection to the server did
            # not work. So try it again with the model data
            preprocessing_desc, _, _ = _get_system(model)
            raw_datapath = os.path.join(utils.get_project_root(),
                                        preprocessing_desc['data-source'])
            handwriting = _get_data_from_rawfile(raw_datapath, raw_data_id)
            if handwriting is None:
                logging.info("Recording with ID %i was not found in %s",
                             raw_data_id,
                             raw_datapath)
            else:
                print("hwrt version: %s" % hwrt.__version__)
                display_data(handwriting.raw_data_json,
                             handwriting.formula_id,
                             model,
                             show_raw)

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


public function append(QRbitstream $arg)
    {
        if (is_null($arg)) {
            return -1;
        }

        if($arg->size() == 0) {
            return 0;
        }

        if($this->size() == 0) {
            $this->data = $arg->data;
            return 0;
        }

        $this->data = array_values(array_merge($this->data, $arg->data));

        return 0;
    }

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question: // IsChaincodeDeployed returns true if the chaincode with given name and version is deployed

func IsChaincodeDeployed(chainid, ccName, ccVersion string, ccHash []byte, sccp sysccprovider.SystemChaincodeProvider) (bool, error) {
	qe, err := sccp.GetQueryExecutorForLedger(chainid)
	if err != nil {
		return false, fmt.Errorf("Could not retrieve QueryExecutor for channel %s, error %s", chainid, err)
	}
	defer qe.Done()

	// XXX We are leaking details of the LSCC table structure to other parts of the code, and this is terrible
	chaincodeDataBytes, err := qe.GetState("lscc", ccName)
	if err != nil {
		return false, fmt.Errorf("Could not retrieve state for chaincode %s on channel %s, error %s", ccName, chainid, err)
	}

	if chaincodeDataBytes == nil {
		return false, nil
	}

	chaincodeData := &ChaincodeData{}
	err = proto.Unmarshal(chaincodeDataBytes, chaincodeData)
	if err != nil {
		return false, fmt.Errorf("Unmarshalling ChaincodeQueryResponse failed, error %s", err)
	}
	return chaincodeData.CCVersion() == ccVersion && bytes.Equal(chaincodeData.Hash(), ccHash), nil
}

public function publishNodeAction(NodeInterface $node, Workspace $selectedWorkspace)
    {
        $this->publishingService->publishNode($node);
        $this->addFlashMessage($this->translator->translateById('workspaces.selectedChangeHasBeenPublished', [], null, null, 'Modules', 'Neos.Neos'));
        $this->redirect('show', null, null, ['workspace' => $selectedWorkspace]);
    }

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


Question: Convert ctypes pointer to buffer type.

def ctypes2buffer(cptr, length):
    """"""
    if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
        raise RuntimeError('expected char pointer')
    res = bytearray(length)
    rptr = (ctypes.c_char * length).from_buffer(res)
    if not ctypes.memmove(rptr, cptr, length):
        raise RuntimeError('memmove failed')
    return res

func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
	// This code assumes that bufio.Writer.buf[:1] is passed to the
	// bufio.Writer's underlying writer.
	var wh writeHook
	bw.Reset(&wh)
	bw.WriteByte(0)
	bw.Flush()

	bw.Reset(originalWriter)

	return wh.p[:cap(wh.p)]
}

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


Question:
Get the autoloader paths to scan for an autoloader.

@return string[]|false Array of strings with autoloader paths, or false
to skip.

protected function get_autoloader_paths() {
		$autoloader_paths = array(
			WP_CLI_VENDOR_DIR . '/autoload.php',
		);

		$custom_vendor = $this->get_custom_vendor_folder();
		if ( false !== $custom_vendor ) {
			array_unshift(
				$autoloader_paths,
				WP_CLI_ROOT . '/../../../' . $custom_vendor . '/autoload.php'
			);
		}

		\WP_CLI::debug(
			sprintf(
				'Fallback autoloader paths: %s',
				implode( ', ', $autoloader_paths )
			),
			'bootstrap'
		);

		return $autoloader_paths;
	}

public function getOptional(int $type = AII::TYPE_BUILTIN | AII::TYPE_UNTYPED | AII::TYPE_CLASS):array
    {
        $includeUntyped = ($type & AII::TYPE_UNTYPED) === AII::TYPE_UNTYPED;
        $includeBuiltin = ($type & AII::TYPE_BUILTIN) === AII::TYPE_BUILTIN;
        $includeClass = ($type & AII::TYPE_CLASS) === AII::TYPE_CLASS;

        $names = [];
        foreach ($this->info->getNames() as $name) {
            if ($this->info->isRequired($name) ) {
                continue;
            }
            if ($this->hasExplicitValue($name)) {
                continue;
            }
            $type = $this->getType($name);
            if ( ! $includeUntyped && is_null($type) ) {
                continue;
            }
            if ( ! $includeBuiltin && ! is_null($type) && Reflector::isBuiltinType($type) ) {
                continue;
            }
            if ( ! $includeClass && ! is_null($type) && ! Reflector::isBuiltinType($type) ) {
                continue;
            }
            $names[] = $name;
        }
        return $names;
    }

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


Question:
This method is called on every reference that is in the .class file.
@param typeReference
@return

private boolean shouldIgnore(String typeReference)
    {
        typeReference = typeReference.replace('/', '.').replace('\\', '.');
        return JavaClassIgnoreResolver.singletonInstance().matches(typeReference);
    }

public static void modify(
			int calleeValKind,
			Object callee,
			String calleeClass,
			String fieldName,
			int callerValKind,
			Object caller,
			String callerClass) {
		System.err.println("modify(          "+
				valAndValKindToString(callee, calleeClass, calleeValKind)+
				" . "+fieldName+", "+
//				"calleeClass="+calleeClass+", "+
				"caller="+valAndValKindToString(caller, callerClass, callerValKind)+", "+
//				"callerClass="+callerClass+", "+
				")");
	}

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


Question:
// hostToIPs attempts to parse a hostname into an ip.
// If that doesn't work it will perform a lookup and try to
// find one ipv4 and one ipv6 in the results.

func hostToIPs(hostname string) (ips []net.IP) {
	if ip := net.ParseIP(hostname); ip != nil {
		ips = []net.IP{ip}
	} else if allIPs, err := net.LookupIP(hostname); err == nil {
		ips = ipsTo4And6(allIPs)
	}
	if len(ips) == 0 {
		logging.VeryVerbose.Printf("cannot translate hostname %q into an ipv4 or ipv6 address", hostname)
	}
	return
}

func (h HealthcheckType) String() string {
	switch h {
	case HCTypeDNS:
		return "DNS"
	case HCTypeHTTP:
		return "HTTP"
	// TODO(angusc): Drop HTTPS as a separate type.
	case HCTypeHTTPS:
		return "HTTP" // NB: Not HTTPS
	case HCTypeICMP:
		return "ICMP"
	case HCTypeRADIUS:
		return "RADIUS"
	case HCTypeTCP:
		return "TCP"
	// TODO(angusc): Drop TCPTLS as a separate type.
	case HCTypeTCPTLS:
		return "TCP" // NB: Not TCPTLS
	case HCTypeUDP:
		return "UDP"
	}
	return "(unknown)"
}

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


Question:
// JSONError sets Internal Server Error status,
// serializes and writes a json-formatted response to user

func (ctx *Context) JSONError(v interface{}) error {
	ctx.Err500()
	return ctx.JSON(v)
}

def comet_view(self, request):

        request_id = self.id_for_request(request)
        if not request_id:
            request.write(HttpResponse(403).as_bytes())
            request.finish()
            return

        data = {
            'headers': request.headers,
            'arguments': request.arguments,
            'remote_ip': request.remote_ip,
            'request_id': request_id,
        }
        message_kind = 'comet-%s' % (request.method,)
        if request.method == 'POST':
            data['body'] = simplejson.loads(request.body)
            request.write(HttpResponse(201).as_bytes())
            request.finish()
        else:
            self.pending_requests[request_id].append(request)
        self.publish(Message(message_kind, datetime.now(), data))

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


Question:
Replace self internals with result.

        Parameters
        ----------
        verify_is_copy : boolean, default True
            provide is_copy checks

def _update_inplace(self, result, verify_is_copy=True):

        # NOTE: This does *not* call __finalize__ and that's an explicit
        # decision that we may revisit in the future.

        self._reset_cache()
        self._clear_item_cache()
        self._data = getattr(result, '_data', result)
        self._maybe_update_cacher(verify_is_copy=verify_is_copy)

func serviceWatch(params map[string]interface{}) (WatcherFunc, error) {
	stale := false
	if err := assignValueBool(params, "stale", &stale); err != nil {
		return nil, err
	}

	var (
		service string
		tags    []string
	)
	if err := assignValue(params, "service", &service); err != nil {
		return nil, err
	}
	if service == "" {
		return nil, fmt.Errorf("Must specify a single service to watch")
	}
	if err := assignValueStringSlice(params, "tag", &tags); err != nil {
		return nil, err
	}

	passingOnly := false
	if err := assignValueBool(params, "passingonly", &passingOnly); err != nil {
		return nil, err
	}

	fn := func(p *Plan) (BlockingParamVal, interface{}, error) {
		health := p.client.Health()
		opts := makeQueryOptionsWithContext(p, stale)
		defer p.cancelFunc()
		nodes, meta, err := health.ServiceMultipleTags(service, tags, passingOnly, &opts)
		if err != nil {
			return nil, nil, err
		}
		return WaitIndexVal(meta.LastIndex), nodes, err
	}
	return fn, nil
}

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


Question: for debugging: gradient check

function () {
			var N = this.N;

			var cg = this.costGrad(this.Y); // evaluate gradient
			var cost = cg.cost;
			var grad = cg.grad;

			var e = 1e-5;
			for (var i = 0; i < N; i++) {
				for (var d = 0; d < this.dim; d++) {
					var yold = this.Y[i][d];

					this.Y[i][d] = yold + e;
					var cg0 = this.costGrad(this.Y);

					this.Y[i][d] = yold - e;
					var cg1 = this.costGrad(this.Y);

					var analytic = grad[i][d];
					var numerical = (cg0.cost - cg1.cost) / ( 2 * e );
					console.log(i + ',' + d + ': gradcheck analytic: ' + analytic + ' vs. numerical: ' + numerical);

					this.Y[i][d] = yold;
				}
			}
		}

public void setColor(String value) {

        if (COLOR_TRANSPARENT.indexOf(value) == 0) {
            setColor(Simapi.COLOR_TRANSPARENT);
        } else {
            setColor(CmsStringUtil.getColorValue(value, Simapi.COLOR_TRANSPARENT, SCALE_PARAM_COLOR));
        }
    }

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


Question: // UnmarshalJSON enables paths to be decoded as JSON using the encoding/json package.

func (p *Path) UnmarshalJSON(data []byte) error {
	var pointSet PointSet

	err := json.Unmarshal(data, &pointSet)
	if err != nil {
		return err
	}
	p.PointSet = pointSet
	return nil
}

def dispatch_hook(cls, _pkt, _underlayer=None, *args, **kargs):
        """"""
        for klass in cls._payload_class:
            if hasattr(klass, "can_handle") and \
                    klass.can_handle(_pkt, _underlayer):
                return klass
        print("DCE/RPC payload class not found or undefined (using Raw)")
        return Raw

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


Question:
Returns the project's version
@return string    The version of the project

public function getVersion()
    {
        $composer = $this->loadJsonFileFromRoot("composer.json");

        if (!isset($composer->version)){
            throw new \Exception("composer.json does not contain a version");
        }

        return $composer->version;
    }

def do_dirty(self, subcmd, opts):

        for comp_name, comp in components.comp_names.items():
            releases = get_released_versions(comp_name)
            if len(releases) == 0:
                print(comp_name + ' - ' + 'No tagged releases')
            else:
                latest_tag = '-'.join(releases[0])
                data = get_changed_since_tag(latest_tag, comp.path)
                if len(data) > 0:
                    print(comp_name + ' - ' + 'Changed files in component tree')

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


Question:
When applying ShapeStyles, we create child elements for fill and stroke. According to Microsoft, this is the
proper way to go.

private static void applyShapeStyle(Element element, ShapeStyle style) {
		// First check the presence of the fill and stroke elements:
		NodeList<Element> fills = element.getElementsByTagName("fill");
		if (fills.getLength() == 0) {
			Element stroke = Dom.createElementNS(Dom.NS_VML, "stroke");
			element.appendChild(stroke);
			Element fill = Dom.createElementNS(Dom.NS_VML, "fill");
			element.appendChild(fill);
			fills = element.getElementsByTagName("fill");
		}

		// Then if fill-color then filled=true:
		if (style.getFillColor() != null) {
			element.setAttribute("filled", "true");
			fills.getItem(0).setAttribute("color", style.getFillColor());
			fills.getItem(0).setAttribute("opacity", Float.toString(style.getFillOpacity()));
		} else {
			element.setAttribute("filled", "false");
		}

		// Then if stroke-color then stroke=true:
		if (style.getStrokeColor() != null) {
			element.setAttribute("stroked", "true");
			NodeList<Element> strokes = element.getElementsByTagName("stroke");
			strokes.getItem(0).setAttribute("color", style.getStrokeColor());
			strokes.getItem(0).setAttribute("opacity", Float.toString(style.getStrokeOpacity()));
			element.setAttribute("strokeweight", Float.toString(style.getStrokeWidth()));
		} else {
			element.setAttribute("stroked", "false");
		}
	}

public void set(Segment1D<?, ?> segment, double curviline, double shift) {
		assert segment != null : AssertMessages.notNullParameter(0);
		segmentProperty().set(new WeakReference<>(segment));
		xProperty().set(curviline);
		yProperty().set(shift);
	}

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


Question:
Get b58 string from multiaddr or peerinfo

@param {Multiaddr|PeerInfo} peer
@return {*}

function getB58String (peer) {
    let b58Id = null
    if (multiaddr.isMultiaddr(peer)) {
      const relayMa = multiaddr(peer)
      b58Id = relayMa.getPeerId()
    } else if (PeerInfo.isPeerInfo(peer)) {
      b58Id = peer.id.toB58String()
    }

    return b58Id
  }

protected function mb_chr($code)
    {
        if (function_exists('mb_chr')) {
            return mb_chr($code);
        } else {
            if (0x80 > $code %= 0x200000) {
                $s = chr($code);
            } elseif (0x800 > $code) {
                $s = chr(0xc0 | $code >> 6) . chr(0x80 | $code & 0x3f);
            } elseif (0x10000 > $code) {
                $s = chr(0xe0 | $code >> 12) . chr(0x80 | $code >> 6 & 0x3f) . chr(0x80 | $code & 0x3f);
            } else {
                $s = chr(0xf0 | $code >> 18) . chr(0x80 | $code >> 12 & 0x3f) . chr(0x80 | $code >> 6 & 0x3f) . chr(0x80 | $code & 0x3f);
            }

            return $s;
        }
    }

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


Question:
Transforms a string (number) to an object (chat).

@param  string $chatID
@return Chat|null
@throws TransformationFailedException if object (chat) is not found.

public function reverseTransform($deviceID)
    {
        // no chat number? It's optional, so that's ok
        if (!$deviceID) {
            return;
        }

        $reDevice = $this->em->getRepository('SopinetChatBundle:Device');
        $device = $reDevice->find($deviceID);

        if (null === $device) {
            // causes a validation error
            // this message is not shown to the user
            // see the invalid_message option
            throw new TransformationFailedException(sprintf(
                'An chat with id "%s" does not exist!',
                $deviceID
            ));
        }

        return $device;
    }

private static SQLTransform getTransform(TypeName typeName) {
		if (typeName.isPrimitive()) {
			return getPrimitiveTransform(typeName);
		}

		if (typeName instanceof ArrayTypeName) {
			ArrayTypeName typeNameArray = (ArrayTypeName) typeName;
			TypeName componentTypeName = typeNameArray.componentType;

			if (TypeUtility.isEquals(componentTypeName, Byte.TYPE.toString())) {
				return new ByteArraySQLTransform();
			} else {
				return new ArraySQLTransform();
			}
		} else if (typeName instanceof ParameterizedTypeName) {
			ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
			if (TypeUtility.isList(parameterizedTypeName)) {
				return new ListSQLTransformation();
			} else if (TypeUtility.isSet(parameterizedTypeName)) {
				return new SetSQLTransformation();
			} else if (TypeUtility.isMap(parameterizedTypeName)) {
				return new MapSQLTransformation();
			}
		}

		String name = typeName.toString();

		if (name.startsWith("java.lang")) {
			return getLanguageTransform(typeName);
		}

		if (name.startsWith("java.util")) {
			return getUtilTransform(typeName);
		}

		if (name.startsWith("java.math")) {
			return getMathTransform(typeName);
		}

		if (name.startsWith("java.net")) {
			return getNetTransform(typeName);
		}

		if (name.startsWith("java.sql")) {
			return getSqlTransform(typeName);
		}

		if (TypeUtility.isEnum(typeName)) {
			return new EnumSQLTransform(typeName);
		}

		return new ObjectSQLTransform();
	}

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


Question: // ParseLogLevel parses string representation of LogLevel.

func ParseLogLevel(level string) LogLevel {
	switch strings.ToLower(level) {
	case "debug":
		return DebugLevel
	case "info":
		return InfoLevel
	case "warn", "warning":
		return WarnLevel
	case "error":
		return ErrorLevel
	case "fatal":
		return FatalLevel
	case "panic":
		return PanicLevel
	default:
		return InfoLevel
	}
}

@Deprecated
    public void error(Object message, Object[] params) {
        doLog(Level.ERROR, FQCN, message, params, null);
    }

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


Question:
Attempt to detect the number of GPUs on this machine.

    TODO(rkn): This currently assumes Nvidia GPUs and Linux.

    Returns:
        The number of GPUs if any were detected, otherwise 0.

def _autodetect_num_gpus():

    proc_gpus_path = "/proc/driver/nvidia/gpus"
    if os.path.isdir(proc_gpus_path):
        return len(os.listdir(proc_gpus_path))
    return 0

def devices(self):
        """"""
        context = Context()

        existing_devices = context.list_devices(subsystem="hidraw")
        future_devices = self._get_future_devices(context)

        for hidraw_device in itertools.chain(existing_devices, future_devices):
            hid_device = hidraw_device.parent
            if hid_device.subsystem != "hid":
                continue

            cls = HID_DEVICES.get(hid_device.get("HID_NAME"))
            if not cls:
                continue

            for child in hid_device.parent.children:
                event_device = child.get("DEVNAME", "")
                if event_device.startswith("/dev/input/event"):
                    break
            else:
                continue

            try:
                device_addr = hid_device.get("HID_UNIQ", "").upper()
                if device_addr:
                    device_name = "{0} {1}".format(device_addr,
                                                   hidraw_device.sys_name)
                else:
                    device_name = hidraw_device.sys_name

                yield cls(name=device_name,
                          addr=device_addr,
                          type=cls.__type__,
                          hidraw_device=hidraw_device.device_node,
                          event_device=event_device)

            except DeviceError as err:
                self.logger.error("Unable to open DS4 device: {0}", err)

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


Question:
Return the service for Result

@return ResultService

protected function getQtiResultService()
    {
        if (!$this->service) {
            $this->service = $this->getServiceManager()->get(ResultService::SERVICE_ID);
        }
        return $this->service;
    }

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

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


Question:
Add a single record to the export data.

@param MutableBag    $contentTypeBag
@param ClassMetadata $metadata
@param Content       $entity

private function addRecord(MutableBag $contentTypeBag, ClassMetadata $metadata, Content $entity)
    {
        $values = [];
        foreach ($metadata->getFieldMappings() as $field) {
            $fieldName = $field['fieldname'];
            $val = $entity->$fieldName;
            if (in_array($field['type'], ['date', 'datetime'])) {
                $val = (string) $entity->$fieldName;
            }
            if (is_callable([$val, 'serialize'])) {
                /** @var Entity $val */
                $val = $val->serialize();
            }
            $values[$fieldName] = $val;
        }

        unset($values['id']);
        $values['_id'] = $entity->getContentType() . '/' . $entity->getSlug();
        $contentTypeBag->add($values);
    }

def save_storage(self, instance, schema):
        """"""
        for field_schema, fields in iterate_fields(instance, schema):
            name = field_schema['name']
            value = fields[name]
            if field_schema.get('type', '').startswith('basic:json:'):
                if value and not self.pk:
                    raise ValidationError(
                        'Data object must be `created` before creating `basic:json:` fields')

                if isinstance(value, int):
                    # already in Storage
                    continue

                if isinstance(value, str):
                    file_path = self.location.get_path(filename=value)  # pylint: disable=no-member
                    if os.path.isfile(file_path):
                        try:
                            with open(file_path) as file_handler:
                                value = json.load(file_handler)
                        except json.JSONDecodeError:
                            with open(file_path) as file_handler:
                                content = file_handler.read()
                                content = content.rstrip()
                                raise ValidationError(
                                    "Value of '{}' must be a valid JSON, current: {}".format(name, content)
                                )

                storage = self.storages.create(  # pylint: disable=no-member
                    name='Storage for data id {}'.format(self.pk),
                    contributor=self.contributor,
                    json=value,
                )

                # `value` is copied by value, so `fields[name]` must be changed
                fields[name] = storage.pk

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


Question: Creates a negotiator used for ALTS client.

public static AltsProtocolNegotiator createClientNegotiator(
      final TsiHandshakerFactory handshakerFactory, final LazyChannel lazyHandshakerChannel) {
    final class ClientAltsProtocolNegotiator extends AltsProtocolNegotiator {

      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) {
        TsiHandshaker handshaker = handshakerFactory.newHandshaker(grpcHandler.getAuthority());
        return new BufferUntilAltsNegotiatedHandler(
            grpcHandler,
            new TsiHandshakeHandler(new NettyTsiHandshaker(handshaker)),
            new TsiFrameHandler());
      }

      @Override
      public void close() {
        logger.finest("ALTS Client ProtocolNegotiator Closed");
        lazyHandshakerChannel.close();
      }
    }

    return new ClientAltsProtocolNegotiator();
  }

function(xmlElement) {
    this.arguments_ = [];
    for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) {
      if (childNode.nodeName.toLowerCase() == 'arg') {
        this.arguments_.push(childNode.getAttribute('name'));
      }
    }
    this.updateParams_();
    Blockly.Procedures.mutateCallers(this);

    // Show or hide the statement input.
    this.setStatements_(xmlElement.getAttribute('statements') !== 'false');
  }

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


Question:
Load Object Collection

@param string $objType The object type as string.
@return \Charcoal\Model\Collection

protected function loadObjectCollection($objType)
    {
        $proto  = $this->modelFactory()->get($objType);
        $loader = $this->collectionLoader();
        $loader->setModel($proto);
        $loader->addFilter('active', true);

        $this->objCollection = $loader->load();

        return $this->objCollection;
    }

public static function createFromData(array $data): self
    {
        if (!isset($data['method'])) {
            throw new DomainException(self::REQUIRED_METHOD);
        }

        switch ($data['method']) {
            case self::METHOD_ACCOUNT_WEIGHTS:
                $instruction = new AccountWeights($data);

                break;
            case self::METHOD_ACQUIRER_WEIGHTS:
                $instruction = new AcquirerWeights($data);

                break;
            default:
                throw new DomainException(
                    sprintf(self::UNEXPECTED_METHOD, implode(', ', self::methods()))
                );
        }

        return $instruction;
    }

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


Question:
ID compatibility hack

    return: dict

def _set_id(infos):
    '''

    '''
    if infos:
        cid = None
        if infos.get("Id"): cid = infos["Id"]
        elif infos.get("ID"): cid = infos["ID"]
        elif infos.get("id"): cid = infos["id"]
        if "Id" not in infos:
            infos["Id"] = cid
        infos.pop("id",None)
        infos.pop("ID",None)
    return infos

def mac(self, mac):

        self._mac = mac
        if mac:
            self.duid = ib_utils.generate_duid(mac)
        elif not hasattr(self, 'duid'):
            self.duid = None

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


Question: Focus at the last file or directory of which name starts with the given String.

def find_reverse(str)
      index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str}
      move_cursor items.size - index - 1 if index
    end

function find_program(program_dir) {

  const files_in_program_dir = fs.readdirSync(program_dir);

  for (let i = 0; i < files_in_program_dir.length; i++) {
    const file = files_in_program_dir[i];
    if (file.includes('Adobe After Effects'))
      return path.join(program_dir, file);
  }

  return null;
}

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


Question:
Rotates a vector around an axis.

@param  vector  vector to be rotated around axis
@param  axis    axis of rotation
@param  angle   angle to vector rotate around
@return         rotated vector
author:         egonw

public static Vector3d rotate(Vector3d vector, Vector3d axis, double angle) {
        Matrix3d rotate = new Matrix3d();
        rotate.set(new AxisAngle4d(axis.x, axis.y, axis.z, angle));
        Vector3d result = new Vector3d();
        rotate.transform(vector, result);
        return result;
    }

protected function makeAvatar( $image ) {
		$width    = $this->getWidth();
		$height   = $this->getHeight();
		$bgColor  = $this->getBackgroundColor();
		$name     = $this->getInitials();
		$fontFile = $this->findFontFile();
		$color    = $this->getColor();
		$fontSize = $this->getFontSize();

		if ( $this->getRounded() && $this->getSmooth() ) {
			$width *= 5;
			$height *= 5;
		}

		$avatar = $image->canvas( $width, $height, ! $this->getRounded() ? $bgColor : null );

		if ( $this->getRounded() ) {
			$avatar = $avatar->circle( $width - 2, $width / 2, $height / 2, function ( $draw ) use ( $bgColor ) {
				return $draw->background( $bgColor );
			} );
		}

		if ( $this->getRounded() && $this->getSmooth() ) {
			$width /= 5;
			$height /= 5;
			$avatar->resize( $width, $height );
		}

		return $avatar->text( $name, $width / 2, $height / 2, function ( AbstractFont $font ) use ( $width, $color, $fontFile, $fontSize ) {
			$font->file( $fontFile );
			$font->size( $width * $fontSize );
			$font->color( $color );
			$font->align( 'center' );
			$font->valign( 'center' );
		} );
	}

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@Override
	public EClass getIfcEvaporativeCooler() {
		if (ifcEvaporativeCoolerEClass == null) {
			ifcEvaporativeCoolerEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
					.getEClassifiers().get(235);
		}
		return ifcEvaporativeCoolerEClass;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question: Morph log data by timestamp range (single log)

def filter_data(self, data, value=None, utc=False, args=None):
        """"""
        if args:
            if not args.range:
                return data
        if not value:
            value = args.range
            utc = args.utc
        ourlimits = value.split('-')

        newdata = {}
        if 'parser' in data.keys():
            newdata['parser'] = data['parser']
            newdata['source_path'] = data['source_path']
            newdata['source_file'] = data['source_file']
            newdata['source_file_mtime'] = data['source_file_mtime']
            newdata['source_file_year'] = data['source_file_year']
        newdata['entries'] = []

        firstdate = int(ourlimits[0].ljust(14, '0'))
        lastdate = int(ourlimits[1].ljust(14, '0'))
        for entry in data['entries']:
            if utc:
                if 'numeric_date_stamp_utc' in entry:
                    if 'numeric_date_stamp_utc' in entry:
                        if '.' in entry['numeric_date_stamp_utc']:
                            dstamp = int(
                                    entry['numeric_date_stamp_utc'].split(
                                        '.')[0])
                        else:
                            dstamp = int(entry['numeric_date_stamp_utc'])
                        if dstamp >= firstdate:
                            if dstamp <= lastdate:
                                newdata['entries'].append(entry)
            else:
                if 'numeric_date_stamp' in entry:
                    if '.' in entry['numeric_date_stamp']:
                        dstamp = int(
                                entry['numeric_date_stamp'].split('.')[0])
                    else:
                        dstamp = int(entry['numeric_date_stamp'])
                    if dstamp >= firstdate:
                        if dstamp <= lastdate:
                            newdata['entries'].append(entry)

        return newdata

public function format(string $level, string $message, array $context)
    {
        $search = [
            '%MODULE%' => $context['_module'] ?? "",
            '%LEVEL%' => strtoupper($level),
            '%MESSAGE%' => Logger::fillPlaceholders($message, $context),
            '%DATE%' => date($this->date_format)
        ];

        return str_replace(array_keys($search), array_values($search), $this->format);
    }

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


Question:
// SanitizeFileName replaces dangerous characters in a string
// so the return value can be used as a safe file name.

func SanitizeFileName(fileName string) string {
	ext := filepath.Ext(fileName)
	cleanExt := sanitize.BaseName(ext)
	if cleanExt == "" {
		cleanExt = ".unknown"
	}
	return strings.Replace(fmt.Sprintf(
		"%s.%s",
		sanitize.BaseName(fileName[:len(fileName)-len(ext)]),
		cleanExt[1:],
	), "-", "_", -1)
}

function (uri, fromUri, source) {
        if (!/^\./.test(uri) || EXTNAME_RE.test(uri)) {

            var line;

            // 如果只出现一次这个字符串，很容易确认模板错误行
            if (source.split(uri).length === 2) {
                source.split(/\n/).forEach(function (code, index) {
                    if (code.indexOf(uri) !== -1) {
                        line = index + 1;
                        source = code.trim();
                    }
                });
            }

            var error = {
                name: 'Syntax Error',
                line: line,
                source: source,
                message: 'Template must be a relative path, and can not have a suffix.'
            };

            if (fromUri) {
                error.filename = fromUri;
            }

            throw error;
        }
    }

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


Question:
Loads a native library with the given {@link LoadPolicy load policy}.

@param clazz
The class whose classloader should be used to resolve shipped libraries
@param name
The name of the class.
@param policy
The load policy.

public void loadLibrary(Class<?> clazz, String name, LoadPolicy policy) {
        if (loaded.contains(name)) {
            return;
        }

        switch (policy) {
            case PREFER_SHIPPED:
                try {
                    loadShippedLibrary(clazz, name);
                } catch (LoadLibraryException ex) {
                    try {
                        loadSystemLibrary(name);
                    } catch (LoadLibraryException ex2) {
                        throw ex;
                    }
                }
                break;
            case PREFER_SYSTEM:
                try {
                    loadSystemLibrary(name);
                } catch (LoadLibraryException ex) {
                    try {
                        loadShippedLibrary(clazz, name);
                    } catch (LoadLibraryException ex2) {
                        throw ex;
                    }
                }
                break;
            case SHIPPED_ONLY:
                loadShippedLibrary(clazz, name);
                break;
            case SYSTEM_ONLY:
                loadSystemLibrary(name);
                break;
            default:
                throw new IllegalStateException("Unknown policy " + policy);
        }

        loaded.add(name);
    }

public void marshall(XMLClassifier xMLClassifier, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(xMLClassifier.getName(), NAME_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getClassification(), CLASSIFICATION_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getCreationTime(), CREATIONTIME_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getLastUpdated(), LASTUPDATED_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getVersion(), VERSION_BINDING);
            protocolMarshaller.marshall(xMLClassifier.getRowTag(), ROWTAG_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


int getTrieSize()  {
        int size = 0;
        try {
            // The trie serialize function returns the size of the data written.
            //    null output stream says give size only, don't actually write anything.
            size = fTrie.serialize(null, true, dm );
        } catch (IOException e) {
            Assert.assrt (false);
        }
        return size;
    }

function paragraph(eat, value, silent) {
  var self = this
  var settings = self.options
  var commonmark = settings.commonmark
  var gfm = settings.gfm
  var tokenizers = self.blockTokenizers
  var interruptors = self.interruptParagraph
  var index = value.indexOf(lineFeed)
  var length = value.length
  var position
  var subvalue
  var character
  var size
  var now

  while (index < length) {
    // Eat everything if there’s no following newline.
    if (index === -1) {
      index = length
      break
    }

    // Stop if the next character is NEWLINE.
    if (value.charAt(index + 1) === lineFeed) {
      break
    }

    // In commonmark-mode, following indented lines are part of the paragraph.
    if (commonmark) {
      size = 0
      position = index + 1

      while (position < length) {
        character = value.charAt(position)

        if (character === tab) {
          size = tabSize
          break
        } else if (character === space) {
          size++
        } else {
          break
        }

        position++
      }

      if (size >= tabSize && character !== lineFeed) {
        index = value.indexOf(lineFeed, index + 1)
        continue
      }
    }

    subvalue = value.slice(index + 1)

    // Check if the following code contains a possible block.
    if (interrupt(interruptors, tokenizers, self, [eat, subvalue, true])) {
      break
    }

    // Break if the following line starts a list, when already in a list, or
    // when in commonmark, or when in gfm mode and the bullet is *not* numeric.
    if (
      tokenizers.list.call(self, eat, subvalue, true) &&
      (self.inList ||
        commonmark ||
        (gfm && !decimal(trim.left(subvalue).charAt(0))))
    ) {
      break
    }

    position = index
    index = value.indexOf(lineFeed, index + 1)

    if (index !== -1 && trim(value.slice(position, index)) === '') {
      index = position
      break
    }
  }

  subvalue = value.slice(0, index)

  if (trim(subvalue) === '') {
    eat(subvalue)

    return null
  }

  /* istanbul ignore if - never used (yet) */
  if (silent) {
    return true
  }

  now = eat.now()
  subvalue = trimTrailingLines(subvalue)

  return eat(subvalue)({
    type: 'paragraph',
    children: self.tokenizeInline(subvalue, now)
  })
}

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


Question:
@param $object News

@return string

public function generatePermalink($object = null)
    {
        $manager = $this->getContainer()->get('compo_news.manager.news');

        if (null === $object) {
            return $manager->getNewsIndexPermalink();
        }

        return $manager->getNewsShowPermalink($object);
    }

public function addExpression(
            O\Expression $expression,
            IParameterHasher $hasher,
            IFunction $context = null,
            $data = null
    ) {
        $this->parameters[] = new ExpressionParameter($expression, $hasher, $context, $data);
    }

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


Question:
// AddModifier binds a custom modifier command to the GJSON syntax.
// This operation is not thread safe and should be executed prior to
// using all other gjson function.

func AddModifier(name string, fn func(json, arg string) string) {
	modifiers[name] = fn
}

@com.fasterxml.jackson.annotation.JsonProperty("uploadId")
    public void setUploadId(String uploadId) {
        this.uploadId = uploadId;
    }

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


Question:
Parse command line arguments and return only the non-default ones

        :Retruns: dict
            a dict of any non-default args passed on the command-line.

def load_cli_args(self):

        parser = argparse.ArgumentParser(description='QTPyLib Reporting',
                                         formatter_class=argparse.ArgumentDefaultsHelpFormatter)

        parser.add_argument('--port', default=self.args["port"],
                            help='HTTP port to use', type=int)
        parser.add_argument('--host', default=self.args["host"],
                            help='Host to bind the http process to')
        parser.add_argument('--blotter',
                            help='Use this Blotter\'s MySQL server settings')
        parser.add_argument('--nopass',
                            help='Skip password for web app (flag)',
                            action='store_true')

        # only return non-default cmd line args
        # (meaning only those actually given)
        cmd_args, _ = parser.parse_known_args()
        args = {arg: val for arg, val in vars(
            cmd_args).items() if val != parser.get_default(arg)}
        return args

func newTerminalPrompter() *terminalPrompter {
	p := new(terminalPrompter)
	// Get the original mode before calling NewLiner.
	// This is usually regular "cooked" mode where characters echo.
	normalMode, _ := liner.TerminalMode()
	// Turn on liner. It switches to raw mode.
	p.State = liner.NewLiner()
	rawMode, err := liner.TerminalMode()
	if err != nil || !liner.TerminalSupported() {
		p.supported = false
	} else {
		p.supported = true
		p.normalMode = normalMode
		p.rawMode = rawMode
		// Switch back to normal mode while we're not prompting.
		normalMode.ApplyMode()
	}
	p.SetCtrlCAborts(true)
	p.SetTabCompletionStyle(liner.TabPrints)
	p.SetMultiLineMode(true)
	return p
}

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


Question:
Set modelPage

@param \Haven\CmsBundle\Entity\TemplatePage $modelPage

@return Page

public function setModelPage(\Haven\CmsBundle\Entity\TemplatePage $modelPage = null) {
        $this->model_page = $modelPage;

        return $this;
    }

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

        return $sInput;
    }

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


Question:
Extra logic for the field.

Adds all sub-fields.

@access public
@param array $args The arguments of the field.

public function init( $args = [] ) {

		self::$typography_controls[] = $args['settings'];

		$config_id = isset( $args['kirki_config'] ) ? $args['kirki_config'] : 'global';

		$this->add_main_field( $config_id, $args );
		$this->add_sub_fields( $config_id, $args );

		add_action( 'customize_controls_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
	}

protected function getPluginNamespace()
    {
        if ($this->getArgumentNamespace() !== null) {
            return $this->getArgumentNamespace();
        }

        if ($this->node instanceof NodeInterface) {
            $nodeArgumentNamespace = $this->node->getProperty('argumentNamespace');
            if ($nodeArgumentNamespace !== null) {
                return $nodeArgumentNamespace;
            }

            $nodeArgumentNamespace = $this->node->getNodeType()->getName();
            $nodeArgumentNamespace = str_replace(':', '-', $nodeArgumentNamespace);
            $nodeArgumentNamespace = str_replace('.', '_', $nodeArgumentNamespace);
            $nodeArgumentNamespace = strtolower($nodeArgumentNamespace);
            return $nodeArgumentNamespace;
        }

        $argumentNamespace = str_replace([':', '.', '\\'], ['_', '_', '_'], ($this->getPackage() . '_' . $this->getSubpackage() . '-' . $this->getController()));
        $argumentNamespace = strtolower($argumentNamespace);

        return $argumentNamespace;
    }

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


Question:
Whether a mapping entry is defined for a given $qtiClassName.

@param string $qtiClassName A QTI class name.
@param string $ns
@return boolean Whether a mapping entry is defined.

public function hasMappingEntry($qtiClassName, $ns = 'qtism')
    {
        $mapping = &$this->getMapping();

        return isset($mapping[$ns]) && isset($mapping[$ns][$qtiClassName]);
    }

private String convertMethodKeyObject(final KeyGenerator methodGenerator, final Object keyValue) {
        String res = "";
        if (keyValue instanceof String) {
            res = (String) keyValue;
        } else {
            try {

                // The default annotation value is toString
                final List<Method> converterList = ClassUtility.retrieveMethodList(keyValue.getClass(), methodGenerator.value());

                Method converter = null;
                for (final Method m : converterList) {
                    if (m.getParameterTypes().length == 0) {
                        converter = m;
                    }
                }

                if (converter == null) {
                    LOGGER.log(METHOD_NOT_FOUND, methodGenerator.value(), keyValue.getClass().getSimpleName());
                } else {
                    // The toString will be called for a string
                    final Object localKey = converter.invoke(keyValue);

                    if (localKey == null) {
                        LOGGER.log(NULL_METHOD_KEY_STRING, converter.getName(), keyValue.getClass().getSimpleName());
                    } else {
                        res = localKey.toString();
                    }
                }
            } catch (final SecurityException e) {
                LOGGER.log(NO_TOSTRING_KEY_METHOD, methodGenerator.value(), keyValue.getClass().getSimpleName(), e);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                LOGGER.log(METHOD_KEY_TOSTRING_FAILURE, methodGenerator.value(), keyValue.getClass().getSimpleName(), e);
            }
        }
        return res + "|";
    }

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


Question:
Creates a new InventoryItem entity.

@Route("/create", name="stock_inventoryitem_create")
@Method("POST")
@Template("FlowerStockBundle:InventoryItem:new.html.twig")

public function createAction(Request $request)
    {
        $inventoryitem = new InventoryItem();
        $form = $this->createForm(new InventoryItemType(), $inventoryitem);
        if ($form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($inventoryitem);
            $em->flush();

            return $this->redirect($this->generateUrl('stock_inventory_show', array('id' => $inventoryitem->getInventory()->getId())));
        }

        return array(
            'inventoryitem' => $inventoryitem,
            'form' => $form->createView(),
        );
    }

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

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

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

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

        return $parameters;
    }

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


Question: // WithContext adds the context to the get identity ID params

func (o *GetIdentityIDParams) WithContext(ctx context.Context) *GetIdentityIDParams {
	o.SetContext(ctx)
	return o
}

func GetUid(name string) (int, error) {
	switch name {
	case "nobody":
		return NobodyUid, nil

	case "root":
		return RootUid, nil

	default:
		userInfo, err := user.Lookup(name)
		if err != nil {
			return 0, err
		}

		return strconv.Atoi(userInfo.Uid)
	}
}

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


Question:
Create new TableAlias for path
@param table the table name
@param path the path from the target table of the query to this TableAlias.

private TableAlias createTableAlias(String table, String path)
    {
        TableAlias alias;

        if (table == null)
        {
            getLogger().warn("Creating TableAlias without table for path: " + path);
        }

        String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // + m_pathToAlias.size();
        alias = new TableAlias(table, aliasName);
        setTableAliasForPath(path, null, alias);
        m_logger.debug("createTableAlias2: path: " + path + " tableAlias: " + alias);

        return alias;
    }

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

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


Question:
// getIDFromPrefix calculates the log stream's hash ID from its Prefix/Name
// fields, which must be populated else this function will panic.

func (p *LogPrefix) getIDFromPrefix() HashID {
	if p.Prefix == "" {
		panic("empty prefix")
	}
	return makeHashID(p.Prefix)
}

private static function parseRangeHeader($header)
    {
        if (preg_match('/bytes=(?P<first>\d+)-(?P<last>\d+)?/', $header, $matches)) {
            return [
                (int) $matches['first'],
                isset($matches['last']) ? (int) $matches['last'] : null,
            ];
        }

        return false;
    }

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


Question:
Get ID list from database
@return array

protected function getIDListFromDB() : array
    {
        if ($this->sValue == ProductListStore::SORT_PRICE_ASC) {
            $arElementIDList = $this->getByPriceASC();
        } elseif ($this->sValue == ProductListStore::SORT_PRICE_DESC) {
            $arElementIDList = $this->getByPriceDESC();
        } elseif ($this->sValue == ProductListStore::SORT_NEW) {
            $arElementIDList = $this->getNewProductList();
        } elseif ($this->sValue == ProductListStore::SORT_NO) {
            $arElementIDList = $this->getProductList();
        } elseif (preg_match('%^'.ProductListStore::SORT_PRICE_ASC.'\|.+%', $this->sValue)) {
            $arElementIDList = $this->getByPriceTypeASC();
        } elseif (preg_match('%^'.ProductListStore::SORT_PRICE_DESC.'\|.+%', $this->sValue)) {
            $arElementIDList = $this->getByPriceTypeDESC();
        } else {
            $arElementIDList = $this->getCustomSortingList();
        }

        return $arElementIDList;
    }

protected function saveIDList($arElementIDList)
    {
        $arCacheTags = $this->getCacheTagList();
        $sCacheKey = $this->getCacheKey();

        //Set cache data
        CCache::forever($arCacheTags, $sCacheKey, $arElementIDList);
    }

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


Question:
Gets a parameter that does a simple replacement without localization.

@param defaultValue String to replace parameter with.

public static ConversationHsmLocalizableParameter defaultValue(final String defaultValue) {
        ConversationHsmLocalizableParameter parameter = new ConversationHsmLocalizableParameter();
        parameter.defaultValue = defaultValue;

        return parameter;
    }

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

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


Question:
Set the item properties.

@param  array  $properties

@return self

private function setProperties(array $properties)
    {
        $this->setType($properties);
        $this->setRoot($properties);
        $this->attributes = MenuItemAttributes::make(
            array_pull($properties, 'attributes', [])
        );
        $this->properties = array_only($properties, [
            'url', 'route', 'action', 'content', 'icon', 'active', 'position',
        ]);

        return $this;
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question:
Creates a new ghost model with the UID $uid and registers it.

@param int $uid the UID of the to-create ghost

@return \Tx_Oelib_Model a ghost model with the UID $uid

protected function createGhost($uid)
    {
        /** @var \Tx_Oelib_Model $model */
        $model = GeneralUtility::makeInstance($this->modelClassName);
        $model->setUid($uid);
        $model->setLoadCallback([$this, 'load']);
        $this->map->add($model);

        return $model;
    }

def classify_identifier(did):

    if _is_unused_did(did):
        return 'unused on this Member Node'
    elif is_sid(did):
        return 'a Series ID (SID) of a revision chain'
    elif is_local_replica(did):
        return 'a Persistent ID (PID) of a local replica'
    elif is_unprocessed_local_replica(did):
        return (
            'a Persistent ID (PID) of an accepted but not yet processed local replica'
        )
    elif is_archived(did):
        return 'a Persistent ID (PID) of a previously archived local object'
    elif is_obsoleted(did):
        return 'a Persistent ID (PID) of a previously updated (obsoleted) local object'
    elif is_resource_map_db(did):
        return 'a Persistent ID (PID) of a local resource map'
    elif is_existing_object(did):
        return 'a Persistent ID (PID) of an existing local object'
    elif is_revision_chain_placeholder(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing revision of a local '
            'replica'
        )
    elif is_resource_map_member(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing object aggregated in '
            'a local Resource Map'
        )
    logger.warning('Unable to classify known identifier. did="{}"'.format(did))
    return '<UNKNOWN>'

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


Question:
Set model attribute. Extend laravel attribute casting mutators by serialized array
@param string $key
@param mixed $value
@return LaravelModel

public function setAttribute($key, $value)
    {
        if ($value !== null && $this->isSerializeCastable($key)) {
            $value = $this->asSerialize($value);
        }

        return parent::setAttribute($key, $value);
    }

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

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


Question: Download all FashionMNIST files to directory unless they are there.

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

public function load($locator, $line = null)
    {
        foreach ($this->manager->locateResources($locator) as $resource) {
            if ($resource->getSpecFilename() == $locator){
                return parent::load($locator, $line);
            }
        }

        return new Suite;
    }

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


Question:
If not already created, a new session-config element will be created and returned.
Otherwise, the first existing session-config element will be returned.
@return the instance defined for the element session-config

public SessionConfigType<WebAppType<T>> getOrCreateSessionConfig()
   {
      List<Node> nodeList = childNode.get("session-config");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new SessionConfigTypeImpl<WebAppType<T>>(this, "session-config", childNode, nodeList.get(0));
      }
      return createSessionConfig();
   }

def create_node(**kwargs):
    '''

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

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

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

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

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

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

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

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

    return {}

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


Question: Register any application services.

public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/config/image-controller.php',
            'image-controller'
        );

        $config = $this->app->config['image-controller'];

        $this->appendRoute($config);

        $this->app->bind('image-controller', 'Flipbox\ImageController\ImageUploader');
    }

func (s *CreateApplicationRequest) SetTags(v map[string]*string) *CreateApplicationRequest {
	s.Tags = v
	return s
}

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


Question: // Not creates a NOT expression.

func (e BoolExprBuilder) Not() BoolExprBuilder {
	return BoolExprBuilder{
		&NotExpr{
			Op:   astNotExpr,
			Expr: &ParenBoolExpr{Expr: e.BoolExpr},
		}}
}

public function notEquals($column, $value, $conjunction = 'AND')
    {
        return $this->addExpression(new Condition\Basic($column, '!=', $value, $conjunction));
    }

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


Question:
重载清除缓存
@param string $cachename
@return boolean

protected function removeCache($cachename){
        $file = $this->cachedir . $cachename . '.cache';
        if ( is_file($file) ) {
            @unlink($file);
        }
        return true;
    }

def exists?(key, parameters = {})
      begin
        @memcached.get(normalize(key, parameters)) && true
      rescue  Memcached::Stored
        true
      rescue Memcached::NotFound
        nil
      end
    end

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


Question:
Evaluates whether the label expression is true when an entity owns the given set of
{@link LabelAtom}s.

public final boolean matches(final Collection<LabelAtom> labels) {
        return matches(new VariableResolver<Boolean>() {
            public Boolean resolve(String name) {
                for (LabelAtom a : labels)
                    if (a.getName().equals(name))
                        return true;
                return false;
            }
        });
    }

func processPredicate(ce ConsumedElement) (*predicate.Predicate, string, string, bool, error) {
	var (
		nP             *predicate.Predicate
		pID            string
		pAnchorBinding string
		temporal       bool
	)
	raw := ce.Token().Text
	p, err := predicate.Parse(raw)
	if err == nil {
		// A fully specified predicate was provided.
		nP = p
		return nP, pID, pAnchorBinding, nP.Type() == predicate.Temporal, nil
	}
	// The predicate may have a binding on the anchor.
	cmps := predicateRegexp.FindAllStringSubmatch(raw, 2)
	if len(cmps) != 1 || (len(cmps) == 1 && len(cmps[0]) != 3) {
		return nil, "", "", false, fmt.Errorf("failed to extract partially defined predicate %q, got %v instead", raw, cmps)
	}
	id, ta := cmps[0][1], cmps[0][2]
	pID = id
	if ta != "" {
		pAnchorBinding = ta
		temporal = true
	}
	return nil, pID, pAnchorBinding, temporal, nil
}

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


Question: // Initializes and returns a cpuinfo profiler.

func NewProfiler() (prof *Profiler, err error) {
	p, err := info.NewProfiler()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p}, nil
}

void _emitJcc(INST_CODE code, Label label, final int hint) {
        if (hint == 0) {
            emitX86(code, label);
        } else {
            emitX86(code, label, Immediate.imm(hint));
        }
    }

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


Question:
Process the results from episode processing.

        :param list data: result instances

def process(self, data):

        fields = []
        for res in data:
            for epname, out in six.iteritems(res.status):
                fields.append(
                    [out.get('state'),
                     epname,
                     out.get('formatted_filename'),
                     out.get('messages')])

        if fields:
            table.write_output(fields)

def _parse(self):

        responses = []
        for child in self._element:
            weight = int_attribute(child, 'weight', 1)
            self._log.debug('Parsing random entry with weight {weight}: {entry}'
                            .format(weight=weight, entry=child.text))

            # If the random element doesn't contain any tags, just store the text and return
            if not len(child):
                responses.append((child.text, weight))
                continue

            # Otherwise, parse all the available tags
            responses.append((tuple(self.trigger.agentml.parse_tags(child, self.trigger)), weight))
        self._responses = tuple(responses)

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


Question:
Unpack archive

@param  string  $path  archive path
@param  array   $arc   archiver command and arguments (same as in $this->archivers)
@return void
@author Dmitry (dio) Levashov
@author Alexey Sukhotin

protected function _unpack($path, $arc) {
		$cwd = getcwd();
		$dir = $this->_dirname($path);
		chdir($dir);
		$cmd = $arc['cmd'].' '.$arc['argc'].' '.escapeshellarg($this->_basename($path));
		$this->procExec($cmd, $o, $c);
		chdir($cwd);
	}

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: // RemoveInfraContainer removes a container from the container state store

func (c *ContainerServer) RemoveInfraContainer(ctr *oci.Container) {
	c.state.infraContainers.Delete(ctr.ID())
}

func indexDelete(storer Storer, tx *bolt.Tx, key []byte, originalData interface{}) error {
	indexes := storer.Indexes()

	for name, index := range indexes {
		err := indexUpdate(storer.Type(), name, index, tx, key, originalData, true)
		if err != nil {
			return err
		}
	}

	return nil
}

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


Question:
Checks whether the provided value is an instance of either this type or a subclass of this type.

@param mixed $value
@return boolean

public function isAssignableFromValue($value)
    {
        if (!is_object($value))
            return false;

        if (get_class($value) === $this->getName())
            return true;

        return is_subclass_of($value, $this->className);
    }

def superseeded_by(self, other_service):
        """"""
        if not other_service or \
                other_service.__class__ != self.__class__ or \
                other_service.protocol != self.protocol or \
                other_service.port != self.port:
            return False

        # If this service does not have a login id but the other one does, then
        # we should return True here
        return not self.device_credentials and other_service.device_credentials

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


Question:
@param int $id

@return bool

public function fulfil($id)
	{
		$endpoint = new Fulfil($this->getTransport());
		$endpoint->setId($id);

		try {
			$result = $endpoint->performRequest();
		} catch (ResourceNotFoundException $e) {
			return false;
		}

		return $result['status'] == 204;
	}

public function setNumberOfShards($value)
    {
        assert(null === $value || is_numeric($value));
        $this->_numberOfShards = $value;
    }

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


Question:
Put a single BatchEntry to the cache for later processing.

@param batchEntry
the batchEntry to write to the cache.

void put(final AbstractBatchEntry batchEntry) {
    try {
        this.queue.put(batchEntry);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    if (this.queue.size() >= this.actions) {
      this.scheduler.submit(new Runnable() {
        @Override
        public void run() {
          write();
        }
      });
    }
  }

public void marshall(ElastiCacheInstanceDetails elastiCacheInstanceDetails, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getFamily(), FAMILY_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getNodeType(), NODETYPE_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getRegion(), REGION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getProductDescription(), PRODUCTDESCRIPTION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getCurrentGeneration(), CURRENTGENERATION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getSizeFlexEligible(), SIZEFLEXELIGIBLE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
(see Riot::AssertionMacro#devaluate)
 @param [Regex, String] expected the string or regex to be used in comparison

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

def legend_data
      if relevant_data?
        retval = []
        layers.each do |layer|
          retval << layer.legend_data
        end
        retval
      else
        nil
      end
    end

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