Question:
r"""Old func-way of class `Versions`, here for backwards compatibility.

    ``mode`` is not used any longer, dummy here.

def versions(mode=None, add_pckg=None, ncol=4):

    """
    # Issue warning
    mesg = ("\n    Func `versions` is deprecated and will " +
            "be removed; use Class `Versions` instead.")
    warnings.warn(mesg, DeprecationWarning)

    return Versions(add_pckg, ncol)

public function setMode($arg) {
        $this->mode = strtolower($arg) == self::LIVE ? self::LIVE : self::SANDBOX;
        return $this;
    }

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


Question:
@param \Symfony\Component\HttpFoundation\Request $request

@return \Symfony\Component\HttpFoundation\Response

public function listAction(Request $request): Response
    {
        $currentPage = $request->query->getInt(self::PAGINATION_PARAM_NAME, 1);

        $contentDraftsDataset = $this->datasetFactory->contentDrafts();
        $contentDraftsDataset->load();

        $pagination = new Pagerfanta(
            new ArrayAdapter($contentDraftsDataset->getContentDrafts())
        );
        $pagination->setMaxPerPage($this->defaultPaginationLimit);
        $pagination->setCurrentPage(min($currentPage, $pagination->getNbPages()));

        $removeContentDraftForm = $this->formFactory->removeContentDraft(
            $this->createContentRemoveData($pagination)
        );

        return $this->render('@ezdesign/admin/content_draft/list.html.twig', [
            'pager' => $pagination,
            'form_remove' => $removeContentDraftForm->createView(),
        ]);
    }

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

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


Question:
// NewLeadershipSettingsAccessor creates a new
// LeadershipSettingsAccessor.

func NewLeadershipSettingsAccessor(
	authorizer facade.Authorizer,
	registerWatcherFn RegisterWatcherFn,
	getSettingsFn GetSettingsFn,
	leaderCheckFn LeaderCheckFn,
	mergeSettingsChunkFn MergeSettingsChunkFn,
) *LeadershipSettingsAccessor {

	return &LeadershipSettingsAccessor{
		authorizer:           authorizer,
		registerWatcherFn:    registerWatcherFn,
		getSettingsFn:        getSettingsFn,
		leaderCheckFn:        leaderCheckFn,
		mergeSettingsChunkFn: mergeSettingsChunkFn,
	}
}

def _init_harness(self):

        self._hc = HarnessController(self.result_dir)
        self._hc.stop()
        time.sleep(1)
        self._hc.start()
        time.sleep(2)

        harness_config = ConfigParser.ConfigParser()
        harness_config.read('%s\\Config\\Configuration.ini' % settings.HARNESS_HOME)
        if harness_config.has_option('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate') and \
                harness_config.getboolean('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate'):
            logger.error('BrowserAutoNavigate in Configuration.ini should be False')
            raise FailError('BrowserAutoNavigate in Configuration.ini should be False')
        if settings.MIXED_DEVICE_TYPE:
            if harness_config.has_option('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection') and \
                    not harness_config.getboolean('THREAD_HARNESS_CONFIG', 'EnableDeviceSelection'):
                logger.error('EnableDeviceSelection in Configuration.ini should be True')
                raise FailError('EnableDeviceSelection in Configuration.ini should be True')

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


Question: // checkpointAndSave grabs a container lock to safely call container.CheckpointTo

func (daemon *Daemon) checkpointAndSave(container *container.Container) error {
	container.Lock()
	defer container.Unlock()
	if err := container.CheckpointTo(daemon.containersReplica); err != nil {
		return fmt.Errorf("Error saving container state: %v", err)
	}
	return nil
}

def process(self, pipeline):
        """"""
        output = []
        for entry in pipeline:
            key = list(entry.keys())[0]
            # an environment block can be repeated
            if key == "env":
                self.data.env_list[0].update(entry[key])
                self.logger.debug("Updating environment at level 0 with %s",
                                  self.data.env_list[0])
                continue

            # after validation it can't be anything else but a stage
            # and the title is inside the round brackets:
            stage = Stage(self, re.match(r"stage\((?P<title>.*)\)", key).group("title"))
            result = stage.process(entry[key])
            output += result['output']
            if not result['success']:
                return {'success': False, 'output': output}

        # logging the output of the cleanup shell when registered
        for line in self.cleanup():
            output.append(line)
            self.logger.info(" | %s", line)

        self.event.succeeded()
        return {'success': True, 'output': output}

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


Question:
// UploadToContainer uploads a tar archive to be extracted to a path in the
// filesystem of the container.
//
// See https://goo.gl/g25o7u for more details.

func (c *Client) UploadToContainer(id string, opts UploadToContainerOptions) error {
	url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts)

	return c.stream("PUT", url, streamOptions{
		in:      opts.InputStream,
		context: opts.Context,
	})
}

func ParseDockerURL(arg string) (*ParsedDockerURL, error) {
	r, err := reference.ParseNormalizedNamed(arg)
	if err != nil {
		return nil, err
	}

	var tag, digest string
	switch x := r.(type) {
	case reference.Canonical:
		digest = x.Digest().String()
	case reference.NamedTagged:
		tag = x.Tag()
	default:
		tag = defaultTag
	}

	indexURL, remoteName := docker.SplitReposName(reference.FamiliarName(r))

	return &ParsedDockerURL{
		OriginalName: arg,
		IndexURL:     indexURL,
		ImageName:    remoteName,
		Tag:          tag,
		Digest:       digest,
	}, nil
}

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


Question:
@param InputInterface  $input
@param OutputInterface $output

@return int|void

protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var int|null $page */
        $page = $input->getArgument('page');

        if ($page < 1) {
            $page = 1;
        }

        $output->writeln(sprintf(
            'Current page: <comment>%d</comment>',
            $page
        ));

        // Get the tweets
        $tweets = $this->em
            ->getRepository('AsyncTweetsBundle:Tweet')
            ->getWithUsers($page);

        if (!$tweets) {
            $output->writeln('<info>No tweet to display.</info>');

            return 0;
        }

        $this->displayTweets($output, $tweets);
    }

def _interactive_loop(self, sin: IO[str], sout: IO[str]) -> None:
        """"""
        self._sin = sin
        self._sout = sout
        tasknum = len(all_tasks(loop=self._loop))
        s = '' if tasknum == 1 else 's'
        self._sout.write(self.intro.format(tasknum=tasknum, s=s))
        try:
            while not self._closing.is_set():
                self._sout.write(self.prompt)
                self._sout.flush()
                try:
                    user_input = sin.readline().strip()
                except Exception as e:
                    msg = 'Could not read from user input due to:\n{}\n'
                    log.exception(msg)
                    self._sout.write(msg.format(repr(e)))
                    self._sout.flush()
                else:
                    try:
                        self._command_dispatch(user_input)
                    except Exception as e:
                        msg = 'Unexpected Exception during command execution:\n{}\n'  # noqa
                        log.exception(msg)
                        self._sout.write(msg.format(repr(e)))
                        self._sout.flush()
        finally:
            self._sin = None  # type: ignore
            self._sout = None

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


Question:
Upload a chunk of data using HTTP POST body.

@param string $uri  Upload URI
@param string $data Contents to upload

@return string|array

protected function uploadChunk($uri, $data)
    {
        $response = $this->client->request(
            'POST',
            $uri,
            [
                'headers' => [
                    'Content-Length' => strlen($data),
                    'Content-Type'   => 'application/octet-stream',
                ],
                'body' => $data,
            ]
        );

        return (string) $response->getBody();
    }

private UploadRequestProcessor getUploadRequestProcessor(TransferContext transferContext) {
        LOGGER.entering(transferContext);
        String contentType = transferContext.getHttpServletRequest().getContentType() != null ? transferContext
                .getHttpServletRequest().getContentType().toLowerCase() : "unknown";
        if (contentType.contains(AbstractUploadRequestProcessor.MULTIPART_CONTENT_TYPE)) {

            // Return a Multipart request processor
            UploadRequestProcessor uploadRequestProcessor = new MultipartUploadRequestProcessor(
                    transferContext);
            LOGGER.exiting(uploadRequestProcessor);
            return uploadRequestProcessor;
        }
        if (contentType.contains(AbstractUploadRequestProcessor.APPLICATION_URLENCODED_CONTENT_TYPE)) {

            // Return normal Urlencoded request processor
            UploadRequestProcessor uploadRequestProcessor = new ApplicationUploadRequestProcessor(
                    transferContext);
            LOGGER.exiting(uploadRequestProcessor);
            return uploadRequestProcessor;
        }
        throw new ArtifactUploadException("Content-Type should be either: "
                + AbstractUploadRequestProcessor.MULTIPART_CONTENT_TYPE + " or: "
                + AbstractUploadRequestProcessor.APPLICATION_URLENCODED_CONTENT_TYPE + " for file uploads");
    }

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


Question: // ListNetworkEndpoints returns all the endpoints associated with the endpoint group in zone and optionally their status.

func (g *Cloud) ListNetworkEndpoints(name, zone string, showHealthStatus bool) ([]*computebeta.NetworkEndpointWithHealthStatus, error) {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newNetworkEndpointGroupMetricContext("list_networkendpoints", zone)
	healthStatus := "SKIP"
	if showHealthStatus {
		healthStatus = "SHOW"
	}
	req := &computebeta.NetworkEndpointGroupsListEndpointsRequest{
		HealthStatus: healthStatus,
	}
	l, err := g.c.BetaNetworkEndpointGroups().ListNetworkEndpoints(ctx, meta.ZonalKey(name, zone), req, filter.None)
	return l, mc.Observe(err)
}

def get_network():
    """"""
    meta = SoftLayer.MetadataManager()
    network_tables = []
    for network_func in [meta.public_network, meta.private_network]:
        network = network_func()

        table = formatting.KeyValueTable(['name', 'value'])
        table.align['name'] = 'r'
        table.align['value'] = 'l'
        table.add_row(['mac addresses',
                       formatting.listing(network['mac_addresses'],
                                          separator=',')])
        table.add_row(['router', network['router']])
        table.add_row(['vlans',
                       formatting.listing(network['vlans'], separator=',')])
        table.add_row(['vlan ids',
                       formatting.listing(network['vlan_ids'], separator=',')])
        network_tables.append(table)

    return network_tables

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


Question:
(non-PHPdoc).

@see Azine\EmailBundle\Services.RecipientProviderInterface::getNewsletterRecipientIDs()

public function getNewsletterRecipientIDs()
    {
        $qb = $this->managerRegistry->getManager()->createQueryBuilder()
            ->select('n.id')
            ->from($this->userClass, 'n')
            ->where('n.'.$this->newsletterField.' = true')
            ->andWhere('n.enabled = 1') // exclude inactive users
            ;
        $results = $qb->getQuery()->execute();
        $ids = array();
        foreach ($results as $next) {
            $ids[] = $next['id'];
        }

        return $ids;
    }

public function toArray()
    {
        return array(
                'eid'          => $this->eid,
                'id'           => $this->id,
                'description'  => $this->description,
                'months'       => $this->months,
                'startfee'     => $this->startFee,
                'invoicefee'   => $this->invoiceFee,
                'interestrate' => $this->interestRate,
                'minamount'    => $this->minAmount,
                'country'      => $this->country,
                'type'         => $this->type,
                'expire'       => $this->expire
        );
    }

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


Question: Create SetCookies from a Response.

public static function fromResponse(ResponseInterface $response) : SetCookies
    {
        return new static(array_map(function (string $setCookieString) : SetCookie {
            return SetCookie::fromSetCookieString($setCookieString);
        }, $response->getHeader(static::SET_COOKIE_HEADER)));
    }

public function route_logout($args) {
		$retval = $this->adm_logout($args);
		if ($retval[0] === 0)
			$this->core->send_cookie(
				$this->adm_get_token_name(), '',
				time() - (3600 * 48), '/');
		return $this->core->pj($retval);
	}

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


Question:
Attack can be only increased, not added.

@return SpellAttack|null

public function getCurrentSpellAttack(): ?SpellAttack
    {
        $spellAttackWithAddition = $this->getSpellAttackWithAddition();
        if (!$spellAttackWithAddition) {
            return null;
        }

        return new SpellAttack(
            [
                $spellAttackWithAddition->getValue()
                + (int)$this->getParameterBonusFromModifiers(ModifierMutableSpellParameterCode::SPELL_ATTACK),
                0 // no addition
            ],
            Tables::getIt()
        );
    }

public function updateRuleData(Rule $rule): void
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->update('ngbm_rule_data')
            ->set('enabled', ':enabled')
            ->set('priority', ':priority')
            ->where(
                $query->expr()->eq('rule_id', ':rule_id')
            )
            ->setParameter('rule_id', $rule->id, Type::INTEGER)
            ->setParameter('enabled', $rule->enabled, Type::BOOLEAN)
            ->setParameter('priority', $rule->priority, Type::INTEGER);

        $query->execute();
    }

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


Question:
Transforms a {@code Sort.Order} object into a comparator item.

@param sortOrder the {@code Sort.Order} object
@return the comparator item

public static ComparatorItem fromSortOrder(Sort.Order sortOrder) {
    if (sortOrder == null || sortOrder.getProperty() == null
        || sortOrder.getProperty().trim().length() == 0) {
      return null;
    }
    boolean nullIsFirst = Sort.NullHandling.NULLS_FIRST.equals(sortOrder.getNullHandling());
    return new ComparatorItem(sortOrder.getProperty(), sortOrder.isAscending(),
        sortOrder.isIgnoreCase(),
        nullIsFirst);
  }

public static Result convert(final Object res) throws QConnectorException {
		if (res == null) {
			return new EmptyResult();
		}
		// table
		if (res instanceof c.Flip) {
			return new FlipResult("", (c.Flip) res);
		}
		// dict
		if (res instanceof c.Dict) {
			final c.Dict dict = (c.Dict) res;
			if ((dict.x instanceof c.Flip) && (dict.y instanceof c.Flip)) {
				final c.Flip key = (c.Flip) dict.x;
				final c.Flip data = (c.Flip) dict.y;
				return new FlipFlipResult("", key, data);
			}
		}
		if (res instanceof Object[]) {
			final Object[] oa = (Object[]) res;
			if ((oa.length == 2) && (oa[0] instanceof String) && (oa[1] instanceof c.Flip)) {
				final String table = (String) oa[0];
				final c.Flip flip = (c.Flip) oa[1];
				return new FlipResult(table, flip);
			} else if ((oa.length == 3) && (oa[1] instanceof String) && (oa[2] instanceof c.Flip)) {
				final String table = (String) oa[1];
				final c.Flip flip = (c.Flip) oa[2];
				return new FlipResult(table, flip);
			} else {
				return new ListResult<Object>(oa);
			}
		}
		// list
		if (res instanceof byte[]) {
			return new ListResult<Byte>(ArrayUtils.toObject((byte[]) res));
		}

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


Question: Converts a given name into a valid class name

function toClassName(name) {
  var result = '';
  var upNext = false;
  for (var i = 0; i < name.length; i++) {
    var c = name.charAt(i);
    var valid = /[\w]/.test(c);
    if (!valid) {
      upNext = true;
    } else if (upNext) {
      result += c.toUpperCase();
      upNext = false;
    } else if (result === '') {
      result = c.toUpperCase();
    } else {
      result += c;
    }
  }
  if (/[0-9]/.test(result.charAt(0))) {
    result = '_' + result;
  }
  return result;
}

def normalize_klass_for_type_name(klass)
      case klass
      when Symbol then klass
      when Array then ARRAY_KEY
      when Set then SET_KEY
      when String then underscore(klass)
      else
        underscore(klass.name)
      end
    end

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


Question:
If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy
        value. See the docs on the suspend_signal_handler method of the io module for more information.

def should_execute(self, workload):

        if not self._suspended.is_set():
            return True
        workload = unwrap_workload(workload)
        return hasattr(workload, 'keep_alive') and getattr(workload, 'keep_alive')

def click_signal(target_usage, target_vendor_id):
    """"""
    # usually you'll find and open the target device, here we'll browse for the
    # current connected devices
    all_devices = hid.HidDeviceFilter(vendor_id = target_vendor_id).get_devices()

    if not all_devices:
        print("Can't find target device (vendor_id = 0x%04x)!" % target_vendor_id)
    else:
        # search for our target usage
        # target pageId, usageId

        for device in all_devices:
            try:
                device.open()
                # browse output reports, we could search over feature reports also,
                # changing find_output_reports() to find_feature_reports()
                for report in device.find_output_reports():
                    if target_usage in report:
                        # found out target!
                        report[target_usage] = 1 # yes, changing values is that easy
                        # at this point you could change different usages at a time...
                        # and finally send the prepared output report
                        report.send()
                        # now toggle back the signal
                        report[target_usage] = 0
                        report.send()
                        print("\nUsage clicked!\n")
                        return
            finally:
                device.close()
        print("The target device was found, but the requested usage does not exist!\n")

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


Question: // SetReplicationTaskArn sets the ReplicationTaskArn field's value.

func (s *ReloadTablesInput) SetReplicationTaskArn(v string) *ReloadTablesInput {
	s.ReplicationTaskArn = &v
	return s
}

@Override
    public Request<MonitorInstancesRequest> getDryRunRequest() {
        Request<MonitorInstancesRequest> request = new MonitorInstancesRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

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


Question: // XXX_OneofFuncs is for the internal use of the proto package.

func (*CollectionConfig) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _CollectionConfig_OneofMarshaler, _CollectionConfig_OneofUnmarshaler, _CollectionConfig_OneofSizer, []interface{}{
		(*CollectionConfig_StaticCollectionConfig)(nil),
	}
}

private void createFunction(String name, GeometryFunction function) {
		try {
			Function.create(getGeoPackage().getConnection().getConnection(),
					name, function);
		} catch (SQLException e) {
			log.log(Level.SEVERE, "Failed to create function: " + name, e);
		}
	}

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


Question:
Renders a navigation node object.

@param navigation_node $item The navigation node to render.
@return string HTML fragment

protected function render_navigation_node(navigation_node $item) {
        $content = $item->get_content();
        $title = $item->get_title();
        if ($item->icon instanceof renderable && !$item->hideicon) {
            $icon = $this->render($item->icon);
            $content = $icon.$content; // use CSS for spacing of icons
        }
        if ($item->helpbutton !== null) {
            $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
        }
        if ($content === '') {
            return '';
        }
        if ($item->action instanceof action_link) {
            $link = $item->action;
            if ($item->hidden) {
                $link->add_class('dimmed');
            }
            if (!empty($content)) {
                // Providing there is content we will use that for the link content.
                $link->text = $content;
            }
            $content = $this->render($link);
        } else if ($item->action instanceof moodle_url) {
            $attributes = array();
            if ($title !== '') {
                $attributes['title'] = $title;
            }
            if ($item->hidden) {
                $attributes['class'] = 'dimmed_text';
            }
            $content = html_writer::link($item->action, $content, $attributes);

        } else if (is_string($item->action) || empty($item->action)) {
            $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
            if ($title !== '') {
                $attributes['title'] = $title;
            }
            if ($item->hidden) {
                $attributes['class'] = 'dimmed_text';
            }
            $content = html_writer::tag('span', $content, $attributes);
        }
        return $content;
    }

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:
Getters for data that also work with implicit transfersyntax

    :param tag: the tag to read

def get_is_value(tag):

    # data is int formatted as string so convert te string first and cast to int
    if tag.VR == 'OB' or tag.VR == 'UN':
        value = int(tag.value.decode("ascii").replace(" ", ""))
        return value
    return int(tag.value)

private function buildFieldsParameter() {
        list($parentEntities, $childrenEntities) = $this->getParentAndChildrenEntities();

        $parameter = new Swagger\Parameter();
        $parameter->setName('fields');
        $parameter->setDescription(
            'Can be fields on this entity, parent entities, or children entities. Specify entities other than this one with type.field. Eligible entities are: '
            . implode(', ', array_merge($parentEntities, $childrenEntities)) . '. Optional.'
        );
        $parameter->setParamType('query');
        $parameter->setType('string');
        $parameter->setAllowMultiple(true);
        return $parameter;
    }

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


Question:
Given a purchasable, resolve the name.

@param PurchasableInterface $purchasable Purchasable
@param string               $separator   Separator

@return false|string Name resolved or false if invalid object

public function resolveName(
        PurchasableInterface $purchasable,
        $separator = self::DEFAULT_SEPARATOR
    ) {
        foreach ($this->nameResolvers as $nameResolver) {
            $nameResolverNamespace = $nameResolver->getPurchasableNamespace();
            if ($purchasable instanceof $nameResolverNamespace) {
                return $nameResolver->resolveName(
                    $purchasable,
                    $separator
                );
            }
        }

        return false;
    }

public static MethodInstance getGetter(Class clazz, String prop) throws PageException, NoSuchMethodException {
	String getterName = "get" + StringUtil.ucFirst(prop);
	MethodInstance mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(getterName), ArrayUtil.OBJECT_EMPTY);

	if (mi == null) {
	    String isName = "is" + StringUtil.ucFirst(prop);
	    mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(isName), ArrayUtil.OBJECT_EMPTY);
	    if (mi != null) {
		Method m = mi.getMethod();
		Class rtn = m.getReturnType();
		if (rtn != Boolean.class && rtn != boolean.class) mi = null;
	    }
	}

	if (mi == null) throw new ExpressionException("No matching property [" + prop + "] found in [" + Caster.toTypeName(clazz) + "]");
	Method m = mi.getMethod();

	if (m.getReturnType() == void.class)
	    throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] for Property [" + getterName + "] must have return type not void");

	return mi;
    }

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


Question: // EnableSnapshots allows the compactor to perform snapshots.

func (c *Compactor) EnableSnapshots() {
	c.mu.Lock()
	c.snapshotsEnabled = true
	if c.snapshotsInterrupt == nil {
		c.snapshotsInterrupt = make(chan struct{})
	}
	c.mu.Unlock()
}

def manipulate(self, stored_instance, component_instance):

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

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

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

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


Question:
Tells whether two string literals are equal by comparing their values.

@param ValueObjectInterface $stringLiteral

@return bool

public function sameValueAs(ValueObjectInterface $stringLiteral)
    {
        if (false === Util::classEquals($this, $stringLiteral)) {
            return false;
        }

        return $this->toNative() === $stringLiteral->toNative();
    }

function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) {
  const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1;

  let optionValue;
  if (Array.isArray(queryString[optionName])) {
    optionValue = queryString[optionName][0];
  } else {
    optionValue = queryString[optionName];
  }

  if (queryStringHasTLSOption) {
    if (Array.isArray(queryString[optionName])) {
      const firstValue = queryString[optionName][0];
      queryString[optionName].forEach(tlsValue => {
        if (tlsValue !== firstValue) {
          throw new MongoParseError('All values of ${optionName} must be the same.');
        }
      });
    }
  }

  return optionValue;
}

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


Question:
Set 'Suggested Sort' for the comments of the submission.

        Comments can be sorted in one of (confidence, top, new, hot,
        controversial, old, random, qa, blank).

        :returns: The json response from the server.

def set_suggested_sort(self, sort='blank'):

        url = self.reddit_session.config['suggested_sort']
        data = {'id': self.fullname, 'sort': sort}
        return self.reddit_session.request_json(url, data=data)

public function run()
    {

        $model = $this->model;

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && isset($_POST['ajax'])) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return \yii\widgets\ActiveForm::validate($model);
        }

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {

                if ($this->isSaveAndNew) {
                    Yii::$app->response->format = Response::FORMAT_JSON;
                    return [
                        'message' => 'saveAndNew',
                        'saveAndNewUrl' => $this->saveAndNewUrl,
                    ];
                }

                Yii::$app->getSession()->setFlash('success', $this->successMsg);
                Yii::$app->response->format = Response::FORMAT_JSON;
                return [
                    'message' => 'success',
                    'success' => true,
                ];
            }

            Yii::$app->getSession()->setFlash('error', $this->errorMsg);
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                'message' => 'error',
                'success' => false,
                'error' => Json::encode($model->getErrors()),
            ];
        }

        return $this->controller->renderAjax($this->view, array_merge([
            'model' => $model,
        ], $this->params));
    }

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


Question: // SetLimit sets the Limit field's value.

func (s *ListSubscribedRuleGroupsInput) SetLimit(v int64) *ListSubscribedRuleGroupsInput {
	s.Limit = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question: Get the table name.

public String getTableNames(boolean bAddQuotes)
    {
        return (m_tableName == null) ? Record.formatTableNames(ISSUE_HISTORY_FILE, bAddQuotes) : super.getTableNames(bAddQuotes);
    }

public function getTables($which_connection='')
    {
        if ($which_connection == '') {
            $which_connection=$this->default_db;
        }
        $conn = $this->connections[$which_connection];

        return $conn->MetaTables();
    }

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


Question: // Get is used to fetch an entry

func (c *CassandraBackend) Get(ctx context.Context, key string) (*physical.Entry, error) {
	defer metrics.MeasureSince([]string{"cassandra", "get"}, time.Now())

	v := []byte(nil)
	stmt := fmt.Sprintf(`SELECT value FROM "%s" WHERE bucket = ? AND key = ? LIMIT 1`, c.table)
	q := c.sess.Query(stmt, c.bucket(key), key)
	if err := q.Scan(&v); err != nil {
		if err == gocql.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}

	return &physical.Entry{
		Key:   key,
		Value: v,
	}, nil
}

def rdtxt_gos(go_file, prt):
        """"""
        goids_all = set()
        if not os.path.exists(go_file):
            raise RuntimeError("CAN NOT READ GO FILE: {FILE}\n".format(FILE=go_file))
        re_go = re.compile(r'(GO:\d{7})+?')
        re_com = re.compile(r'^\s*#')  # Lines starting with a '#' are comment lines and ignored
        with open(go_file) as ifstrm:
            for line in ifstrm:
                # Skip lines that are comments
                if re_com.search(line):
                    continue
                # Search for GO IDs on the line
                goids_found = re_go.findall(line)
                if goids_found:
                    goids_all.update(goids_found)
            if prt:
                prt.write("  {N} GO IDs READ: {TXT}\n".format(N=len(goids_all), TXT=go_file))
        return goids_all

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


Question: Return a MATCH query string from a CompoundMatchQuery.

def emit_code_from_ir(compound_match_query, compiler_metadata):
    """"""
    # If the compound match query contains only one match query,
    # just call `emit_code_from_single_match_query`
    # If there are multiple match queries, construct the query string for each
    # individual query and combine them as follows.
    #
    # SELECT EXPAND($result)
    # LET
    #    $optional__0 = (
    #        <query_string_0>
    #    ),
    #    $optional__1 = (
    #        <query_string_1>
    #    ),
    #    $optional__2 = (
    #        <query_string_2>
    #    ),
    #
    #    . . .
    #
    #    $result = UNIONALL($optional__0, $optional__1, . . . )

    match_queries = compound_match_query.match_queries
    if len(match_queries) == 1:
        query_string = emit_code_from_single_match_query(match_queries[0])
    elif len(match_queries) > 1:
        query_string = emit_code_from_multiple_match_queries(match_queries)
    else:
        raise AssertionError(u'Received CompoundMatchQuery with an empty list of MatchQueries: '
                             u'{}'.format(match_queries))

    return query_string

function ironmqGet(path, params, cb) {

    var search = qs.stringify(params)
    search = search ? ('?' + search) : ''

    request.get({ url     : baseUrl + path + search
                , headers : headers}
              , parseResponse(cb))
      .end()
  }

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


Question:
Convert an attribute value template into PHP

NOTE: escaping must be performed by the caller

@link https://www.w3.org/TR/1999/REC-xslt-19991116#dt-attribute-value-template

@param  string $attrValue Attribute value template
@return string

protected function convertAttributeValueTemplate($attrValue)
	{
		$phpExpressions = [];
		foreach (AVTHelper::parse($attrValue) as $token)
		{
			if ($token[0] === 'literal')
			{
				$phpExpressions[] = var_export($token[1], true);
			}
			else
			{
				$phpExpressions[] = $this->convertXPath($token[1]);
			}
		}

		return implode('.', $phpExpressions);
	}

public function getAttribute($attribute)
    {
        switch ($attribute) {
            case \PDO::ATTR_AUTOCOMMIT:
                return true;
            case \PDO::ATTR_CASE:
            case \PDO::ATTR_CLIENT_VERSION:
            case \PDO::ATTR_CONNECTION_STATUS:
                return $this->client->connected;
            case \PDO::ATTR_DRIVER_NAME:
            case \PDO::ATTR_ERRMODE:
                return 'Swoole Style';
            case \PDO::ATTR_ORACLE_NULLS:
            case \PDO::ATTR_PERSISTENT:
            case \PDO::ATTR_PREFETCH:
            case \PDO::ATTR_SERVER_INFO:
                return self::$options['timeout'];
            case \PDO::ATTR_SERVER_VERSION:
                return 'Swoole Mysql';
            case \PDO::ATTR_TIMEOUT:
            default:
                throw new \InvalidArgumentException('Not implemented yet!');
        }
    }

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


Question:
format the double value as a string. includes the currency symbol as part of the response.
note: will not do any conversion (we assume that dValue is already in the correct currency).

@param float $dValue

@return string

public function GetFormattedCurrency($dValue)
    {
        $oLocal = &TCMSLocal::GetActive();
        $sValue = $oLocal->FormatNumber($dValue, 2).' '.$this->GetCurrencyDisplaySymbol();

        return $sValue;
    }

public static function get(string $url, array $options = []) : array {
		$result = [
			'success' => false,
			'error' => [],
			'data' => null
		];
		if (strpos($url, '?') !== false) {
			$url.= '&';
		} else {
			$url.= '?';
		}
		$url.= http_build_query2($options['params']);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result['data'] = curl_exec($ch);
		if (!empty($options['json'])) {
			$result['data'] = json_decode($result['data'], true);
		}
		curl_close($ch);
		$result['success'] = true;
		return $result;
	}

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


Question:
Creates a date.
@param {number} year
@param {number} month
@param {number} day
@return {Date}

function(year, month, day) {
    var date = new Date(Date.UTC(year, month - 1, day));
    return date;
  }

private static function deserializePlayReadyLicenseTemplate($xmlElement)
    {
        if (!isset($xmlElement->PlayRight)) {
            throw new \RuntimeException("The PlayReadyLicenseTemplate must contains an 'PlayRight' element");
        }

        if (!isset($xmlElement->ContentKey)) {
            throw new \RuntimeException("The PlayReadyLicenseTemplate must contains an 'ContentKey' element");
        }

        $result = new PlayReadyLicenseTemplate();

        if (isset($xmlElement->AllowTestDevices)) {
            $result->setAllowTestDevices($xmlElement->AllowTestDevices == 'true');
        }

        if (isset($xmlElement->BeginDate)) {
            if (isset($xmlElement->BeginDate->attributes(Resources::XSI_XML_NAMESPACE)->nil) &&
                $xmlElement->BeginDate->attributes(Resources::XSI_XML_NAMESPACE)->nil == 'true') {
                $result->setBeginDate(null);
            } else {
                $result->setBeginDate(new \DateTime((string) $xmlElement->BeginDate));
            }
        }

        if (isset($xmlElement->ExpirationDate)) {
            if (isset($xmlElement->ExpirationDate->attributes(Resources::XSI_XML_NAMESPACE)->nil) &&
               $xmlElement->ExpirationDate->attributes(Resources::XSI_XML_NAMESPACE)->nil == 'true') {
                $result->setExpirationDate(null);
            } else {
                $result->setExpirationDate(new \DateTime((string) $xmlElement->setExpirationDate));
            }
        }

        if (isset($xmlElement->RelativeBeginDate)) {
            $result->setRelativeBeginDate(new \DateInterval((string) $xmlElement->RelativeBeginDate));
        }

        if (isset($xmlElement->RelativeExpirationDate)) {
            $result->setRelativeExpirationDate(new \DateInterval((string) $xmlElement->RelativeExpirationDate));
        }

        if (isset($xmlElement->GracePeriod)) {
            $result->setGracePeriod(new \DateInterval((string) $xmlElement->GracePeriod));
        }

        $result->setPlayRight(self::deserializePlayReadyPlayRight($xmlElement->PlayRight));

        if (isset($xmlElement->LicenseType)) {
            $result->setLicenseType((string) $xmlElement->LicenseType);
        }

        $result->setContentKey(self::deserializePlayReadyContentKey($xmlElement->ContentKey));

        return $result;
    }

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


Question:
Gets the locale currently set within either the session or cookie.

@param HTTPRequest $request
@return null|string The locale, if available

protected function getPersistLocale(HTTPRequest $request)
    {
        $key = $this->getPersistKey();

        // Skip persist if key is unset
        if (empty($key)) {
            return null;
        }

        // check session then cookies
        $session = $request->getSession();
        if ($session->isStarted() && ($locale = $session->get($key))) {
            return $locale;
        }

        if (static::config()->get('persist_cookie') && ($locale = Cookie::get($key))) {
            return $locale;
        }

        return null;
    }

def getLanguage(self, body, ):

        resourcePath = '/text/detect_language'
        method = 'POST'

        queryParams = {}
        headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'}
        postData = None

        postData = body
        response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams)
        return language_rest.LanguageRest(**response.json())

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


Question:
Returns the descriptor representing the type of the value of the map field. Returns null if the
map value isn't a message.

@Nullable
  public static Descriptor getMapValueMessageType(FieldDescriptor mapField) {
    FieldDescriptor valueDesc = mapField.getMessageType().findFieldByName("value");
    if (valueDesc.getType() == FieldDescriptor.Type.MESSAGE) {
      return valueDesc.getMessageType();
    } else {
      return null;
    }
  }

def sitemap_meta_description
      return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false)
    end

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


Question:
activate the composer plugins
@param Composer $composer the composer instance
@param IOInterface $io the Input Output Interface of the console
@return void

public function activate(Composer $composer, IOInterface $io)
    {
        $this->composer = $composer;
        $this->io = $io;
        if(isset($this->composer->getPackage()->getExtra()['auto-require']['vendor-name'])) {
            $this->vendorName = $this->composer->getPackage()->getExtra()['auto-require']['vendor-name'];
        } else {
            $this->vendorName = 'yourpackage';
        }
        if(isset($this->composer->getPackage()->getExtra()['auto-require']['path-scheme'])) {
            $this->pathScheme = $this->composer->getPackage()->getExtra()['auto-require']['path-scheme'];
        } else {
            $this->pathScheme = '{vendorName}/{vendorName}.{name}';
        }
    }

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

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

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

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

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

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

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

        methods = {}

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

        service.methods = methods

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

        return service

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


Question: Send email notifications needed.

def email(self, comment, entry, request):

        current_language = get_language()
        try:
            activate(settings.LANGUAGE_CODE)
            site = Site.objects.get_current()
            if self.auto_moderate_comments or comment.is_public:
                self.do_email_notification(comment, entry, site)
            if comment.is_public:
                self.do_email_authors(comment, entry, site)
                self.do_email_reply(comment, entry, site)
        finally:
            activate(current_language)

public function registerClientScript()
    {
    	$view = $this->getView();
    	PNotifyAsset::register($view);

    	$options = empty($this->pluginOptions) ? '' : Json::encode($this->pluginOptions);
    	$js = "new PNotify(".$options.");";

    	$view->registerJs($js);
    }

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


Question:
Try to gracefully disconnect from each network, unload all scripts and
 exit properly.

 @param [optional, Symbol] signal The signal received by the system, if any.

def quit signal = :SIGINT
      @networks.each do |network|
        network.transmit :QUIT, 'Got SIGINT?'
        network.disconnect
      end

      EventMachine.stop
    end

def clear(*signals):

    signals = signals if signals else receivers.keys()

    for signal in signals:
        receivers[signal].clear()

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


Question:
Create order

REST: POST /order/domain/zone/new
@param minimized [required] Create only mandatory records
@param zoneName [required] Name of the zone to create

public OvhOrder domain_zone_new_POST(Boolean minimized, String zoneName) throws IOException {
		String qPath = "/order/domain/zone/new";
		StringBuilder sb = path(qPath);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "minimized", minimized);
		addBody(o, "zoneName", zoneName);
		String resp = exec(qPath, "POST", sb.toString(), o);
		return convertTo(resp, OvhOrder.class);
	}

protected function getBodyParametersFromDocBlock(array $tags)
    {
        $parameters = collect($tags)
            ->filter(function ($tag) {
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
            })
            ->mapWithKeys(function ($tag) {
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
                if (empty($content)) {
                    // this means only name and type were supplied
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
                    $required = false;
                    $description = '';
                } else {
                    list($_, $name, $type, $required, $description) = $content;
                    $description = trim($description);
                    if ($description == 'required' && empty(trim($required))) {
                        $required = $description;
                        $description = '';
                    }
                    $required = trim($required) == 'required' ? true : false;
                }

                $type = $this->normalizeParameterType($type);
                list($description, $example) = $this->parseDescription($description, $type);
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;

                return [$name => compact('type', 'description', 'required', 'value')];
            })->toArray();

        return $parameters;
    }

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


Question:
returns number of elements in sequence

This is a terminal operation.

@return  int
@XmlIgnore

public function count(): int
    {
        $amount = 0;
        // iterate with $key so the key consumer from peek() can have a look
        foreach ($this->elements as $key => $element) {
            $amount++;
        }

        return $amount;
    }

def cli(ctx, all, top, nostyle, nowarn, warn, project_dir):
    """"""

    exit_code = SCons(project_dir).lint({
        'all': all,
        'top': top,
        'nostyle': nostyle,
        'nowarn': nowarn,
        'warn': warn
    })
    ctx.exit(exit_code)

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


Question:
Parse XML to build an array of known images

@param array $xml

@return \Pressbooks\Entities\Cloner\Media[]

public function buildListOfKnownMedia( $xml ) {

		$known_media = [];

		foreach ( $xml['posts'] as $item ) {
			if ( $item['post_type'] !== 'attachment' ) {
				continue; // Not an attachment, skip
			}
			$x = [];
			foreach ( $item['postmeta'] as $meta ) {
				if ( $meta['key'] === '_wp_attachment_metadata' ) {
					$x = maybe_unserialize( $meta['value'] );
					break;
				}
			}
			if ( ! is_array( $x ) || empty( $x ) ) {
				continue; // Something went wrong, skip
			}

			$m = $this->createMediaEntity( $item );
			if ( preg_match( $this->downloads->getPregSupportedImageExtensions(), $m->sourceUrl ) ) {
				$prefix = str_replace( $this->downloads->basename( $m->sourceUrl ), '', $x['file'] ); // 2017/08
				foreach ( $x['sizes'] as $size => $info ) {
					$attached_file = $prefix . $info['file']; // 2017/08/foo-bar-300x225.png
					$known_media[ $attached_file ] = $m;
				}
			} else {
				$attached_file = media_strip_baseurl( $m->sourceUrl ); // 2017/08/foo-bar.ext
				$known_media[ $attached_file ] = $m;
			}
		}

		return $known_media;
	}

public function save()
    {
        // If initialized from an SRU record, we need to fetch the
        // remaining parts of the Bib record.
        $this->init();

        // Inject the MARC record
        $marcXml = new QuiteSimpleXMLElement($this->_marc->toXML('UTF-8', false, false));
        $this->data->first('record')->replace($marcXml);

        // Serialize
        $newData = $this->data->asXML();

        // Alma doesn't like namespaces
        $newData = str_replace(' xmlns="http://www.loc.gov/MARC21/slim"', '', $newData);

        return $this->client->putXML($this->url(), $newData);
    }

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


Question:
Clears the asset cache.

@access public

public function clearAssetCache()
    {
        foreach ($this->cachedFiles as $hash => $fileData) {
            if (!$this->fileBackend->isWritable($fileData['file'])) {
                continue;
            }

            $this->fileBackend->deleteFile($fileData['file']);
        }

        $this->cachedFiles = array();
        $this->saveAssetsCache();
    }

protected function flushApiCache($folderId = 0, $page = 0)
    {
        Yii::$app->storage->flushArrays();
        $this->deleteHasCache('storageApiDataFolders');
        $this->deleteHasCache(['storageApiDataFiles', (int) $folderId, (int) $page]);
    }

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


Question:
Set shipping methods to the ShippingOptions object

@param $shippingMethods

protected function getShippingOptionsData($shippingMethods)
    {
        $shippingOptionsModel = $this->shippingOptionsInterfaceFactory->create();

        $shippingTaxModel = $this->shippingTaxInterfaceFactory->create();
        $shippingTaxModel->setAmount(0);

        $shippingOptionsModel->setShippingOptions($shippingMethods);
        $shippingOptionsModel->setTaxResult($shippingTaxModel);

        return $shippingOptionsModel;
    }

public static com.liferay.commerce.model.CommerceShipmentItem addCommerceShipmentItem(
		com.liferay.commerce.model.CommerceShipmentItem commerceShipmentItem) {
		return getService().addCommerceShipmentItem(commerceShipmentItem);
	}

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


Question:
发送错误
@param  resource $handle       连接fd
@param  string   $errorMessage 错误内容
@return [type]               [description]

public static function sendError($handle, $errorMessage) {
        $buffer = self::_parseError($errorMessage);
        return self::_writeToServer($handle, $buffer);
    }

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

        return;
    }

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


Question:
Print a general expression, using specified
{@link org.rythmengine.utils.Escape escape method}

@param o
@param escape
@return the current builder

public TemplateBuilder pe(Object o, Escape escape) {
        if (null != o) {
            if (o instanceof RawData) {
                return (TemplateBuilder) p(o);
            }
            if (null == escape) {
                escape = __defaultEscape();
            }
            switch (escape) {
                case RAW:
                    return (TemplateBuilder) p(S.raw(o));
                case HTML:
                    return (TemplateBuilder) p(S.escapeHtml(o));
                case JSON:
                    return (TemplateBuilder) p(S.escapeJson(o));
                case JS:
                    return (TemplateBuilder) p(S.escapeJavaScript(o));
                case CSV:
                    return (TemplateBuilder) p(S.escapeCsv(o));
                case XML:
                    return (TemplateBuilder) p(S.escapeXml(o));
            }
        }
        return this;
    }

def spider_url(zap_helper, url, context_name, user_name):
    """"""
    console.info('Running spider...')
    with helpers.zap_error_handler():
        zap_helper.run_spider(url, context_name, user_name)

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


Question:
/*
Set the optional RoutingDestination field in the message header.

Javadoc description supplied by CommonMessageHeaders interface.

public void setRoutingDestination(JsDestinationAddress value) {
    if (value != null) {
      jmo.setField(ControlAccess.ROUTINGDESTINATION_VALUE_NAME, value.getDestinationName());
      if (value.getME() != null) {
        jmo.setField(ControlAccess.ROUTINGDESTINATION_VALUE_MEID, value.getME().toByteArray());
      }
      else {
        jmo.setField(ControlAccess.ROUTINGDESTINATION_VALUE_MEID, null);
      }
      jmo.setField(ControlAccess.ROUTINGDESTINATION_VALUE_BUSNAME, value.getBusName());
    }
    else {
      jmo.setChoiceField(ControlAccess.ROUTINGDESTINATION, ControlAccess.IS_ROUTINGDESTINATION_EMPTY);
    }
  }

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

        return parameter;
    }

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


Question:
/*
Parse a list of Length/Coords

private static List<Length>  parseLengthList(String val) throws SVGParseException
   {
      if (val.length() == 0)
         throw new SVGParseException("Invalid length list (empty string)");

      List<Length>  coords = new ArrayList<>(1);

      TextScanner scan = new TextScanner(val);
      scan.skipWhitespace();

      while (!scan.empty())
      {
         float scalar = scan.nextFloat();
         if (Float.isNaN(scalar))
            throw new SVGParseException("Invalid length list value: "+scan.ahead());
         Unit  unit = scan.nextUnit();
         if (unit == null)
            unit = Unit.px;
         coords.add(new Length(scalar, unit));
         scan.skipCommaWhitespace();
      }
      return coords;
   }

def polygon_from_points(points):

    polygon = []
    for pair in points.split(" "):
        x_y = pair.split(",")
        polygon.append([float(x_y[0]), float(x_y[1])])
    return polygon

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


Question:
Gets the tag class with the given id.

@param id Id of the tag.
@return The tag class with the given id, or null if it cannot be found.

public static Class<? extends Tag> getClassFor(int id) {
        if(!idToTag.containsKey(id)) {
            return null;
        }

        return idToTag.get(id);
    }

public static Type getReturnType(final String methodDescriptor) {
    // Skip the first character, which is always a '('.
    int currentOffset = 1;
    // Skip the argument types, one at a each loop iteration.
    while (methodDescriptor.charAt(currentOffset) != ')') {
      while (methodDescriptor.charAt(currentOffset) == '[') {
        currentOffset++;
      }
      if (methodDescriptor.charAt(currentOffset++) == 'L') {
        while (methodDescriptor.charAt(currentOffset++) != ';') {
          // Skip the argument descriptor content.
        }
      }
    }
    return getType(methodDescriptor, currentOffset + 1, methodDescriptor.length());
  }

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


Question: Log requests to console

function logConsole() {

    return function (req, res, next) {

        console.log('Received request: ' + req.method + ' ' + req.originalUrl);

        next();
    };
}

func RecordAndReplay(cmd []string, wd string, quiet bool, debugInfoDirs []string) (p *Process, tracedir string, err error) {
	tracedir, err = Record(cmd, wd, quiet)
	if tracedir == "" {
		return nil, "", err
	}
	p, err = Replay(tracedir, quiet, debugInfoDirs)
	return p, tracedir, err
}

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


Question:
Check for cached resource item exists
        :param path: str
        :return: bool

def check_cached_item(self, path):

        item_path = '%s/%s/%s' % (
                current_app.static_folder,
                self.cache_folder,
                path.strip('/')
            )

        if os.path.isfile(item_path):
            return '%s/%s/%s' % (current_app.static_url_path, self.cache_folder, path.strip('/'))
        else:
            return False

protected void getURIs(String lcacheArchives, String lcacheFiles) {
    String archives[] = StringUtils.getStrings(lcacheArchives);
    String files[] = StringUtils.getStrings(lcacheFiles);
    fileURIs = StringUtils.stringToURI(files);
    archiveURIs = StringUtils.stringToURI(archives);
  }

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


Question: // MFilterType ...

func (cm AsStandard) MFilterType(filter string) *metadata.MFilterType {
	mft := metadata.MFilterType{}
	mi := metadata.MIFilterType
	for _, cd := range cm.Elements[mi.Name] {
		if cd.Attr["Filter"] != filter {
			continue
		}
		metadata.FieldTransfer(cd.Attr).To(&mft)
		for _, entry := range cd.Entries() {
			tmp := metadata.FilterType{}
			entry.SetFields(&tmp)
			mft.FilterType = append(mft.FilterType, tmp)
		}
	}
	return &mft
}

public function write($message, $level = null)
    {
        if ($this->isSilent()) {
            return;
        }

        if ($level && ($this->verbosity < $level)) {
            return;
        }

        $message = $this->filter->filter($message);
        $this->adapter->write($message);
    }

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


Question:
Set the reading position, excluding the header.

@param recordIndex is the index of the next record to read.
@param byteIndex is the index of the next byte to read (excluding the header).
@throws IOException in case of error.

protected void setReadingPosition(int recordIndex, int byteIndex) throws IOException {
		if (this.seekEnabled) {
			this.nextExpectedRecordIndex = recordIndex;
			this.buffer.position(byteIndex);
		} else {
			throw new SeekOperationDisabledException();
		}
	}

public static <C> SlicePredicate getPredicate(ColumnSlice<C> columns, Serializer<C> colSer) {
        // Get all the columns
        if (columns == null) {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setSlice_range(new SliceRange(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), false,
                    Integer.MAX_VALUE));
            return predicate;
        }
        // Get a specific list of columns
        if (columns.getColumns() != null) {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setColumn_namesIsSet(true);
            predicate.column_names = colSer.toBytesList(columns.getColumns());
            return predicate;
        }
        else {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setSlice_range(new SliceRange((columns.getStartColumn() == null) ? ByteBuffer.wrap(new byte[0])
                    : ByteBuffer.wrap(colSer.toBytes(columns.getStartColumn())),
                    (columns.getEndColumn() == null) ? ByteBuffer.wrap(new byte[0]) : ByteBuffer.wrap(colSer
                            .toBytes(columns.getEndColumn())), columns.getReversed(), columns.getLimit()));
            return predicate;
        }
    }

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


Question:
Used to double methods added to an object after creation

        :param str attr_name: the name of the original attribute to return
        :return: Attribute or None.
        :rtype: func

def get_callable_attr(self, attr_name):

        if not hasattr(self.doubled_obj, attr_name):
            return None

        func = getattr(self.doubled_obj, attr_name)
        if not is_callable(func):
            return None

        attr = Attribute(
            func,
            'attribute',
            self.doubled_obj if self.is_class_or_module() else self.doubled_obj_type,
        )
        self.attrs[attr_name] = attr
        return attr

public function withType(Type $type): self
    {
        $metadata = clone $this;
        $metadata->type = $type;

        return $metadata;
    }

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


public void addTangoPeriodicListener(ITangoPeriodicListener listener, boolean stateless)
                throws DevFailed
    {
		event_listeners.add(ITangoPeriodicListener.class, listener);
        event_identifier = subscribe_periodic_event(attr_name, filters, stateless);
    }

def text message
      @suggested_w = @width || (FFI::NCurses.COLS * 0.80).floor
      @suggested_h = @height || (FFI::NCurses.LINES * 0.80).floor

      message_col = 3
      r = 2
      display_length = @suggested_w-4
      display_length -= message_col
      clr = @color || :white
      bgclr = @bgcolor || :black

      if message.is_a? Array
        l = longest_in_list message
        if l > @suggested_w
          if l < FFI::NCurses.COLS
            #@suggested_w = l
            @suggested_w = FFI::NCurses.COLS-2
          else
            @suggested_w = FFI::NCurses.COLS-2
          end
          display_length = @suggested_w-6
        end
        # reduce width and height if you can based on array contents
      else
        message = wrap_text(message, display_length).split("\n")
      end
      # now that we have moved to textpad that +8 was causing black lines to remain after the text
      message_height = message.size #+ 8
      # reduce if possible if its not required.
      #
      r1 = (FFI::NCurses.LINES-@suggested_h)/2
      r1 = r1.floor
      w = @suggested_w
      c1 = (FFI::NCurses.COLS-w)/2
      c1 = c1.floor
      @suggested_row = r1
      @suggested_col = c1
      brow = @button_row || @suggested_h-4
      available_ht = brow - r + 1
      message_height = [message_height, available_ht].min
      # replaced 2014-04-14 - 23:51
      message_label = Canis::TextPad.new @form, {:name=>"message_label", :text => message,
        :row => r, :col => message_col, :width => display_length, :suppress_borders => true,
        :height => message_height, :bgcolor => bgclr , :color => clr}
      #message_label.set_content message
      yield message_label if block_given?

    end

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


Question:
获取map类型的source对象
@return

public Map<String,Object> asMap(){
		if(source == null)
			return null;
		return (Map<String,Object>)source;
	}

public static function route() :void {

		// marker
		Profiler::setMarker('Router.route', 'framework');
		// get the requested url
		$request_url = Request::getUrl();
		// get the requested method
		$request_method = Request::getMethod();
		// Loop over each route and test to see if they are valid
		foreach(self::$_routes as $route) {
			// if the route matches
			if(self::routeMatch($request_url, $request_method, $route)) {
				// get it
				$matching_route = $route;
				// stop trying
				break;
			}
		}
		// marker
		Profiler::releaseMarker('Router.route');
		// if no match is found and we don't have an error route to fallback on
		if(!isset($matching_route)) {
			// throw a native exception since there is no cleaner alternative
			Throw new Exception('Router::route() no matching route', 404);
		}
		// send the matching route to the dispatcher
		self::forward($matching_route);

	}

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


Question: // Convert_v1_User_To_user_User is an autogenerated conversion function.

func Convert_v1_User_To_user_User(in *v1.User, out *user.User, s conversion.Scope) error {
	return autoConvert_v1_User_To_user_User(in, out, s)
}

@Nonnull
	public static LCharToFltFunction charToFltFunctionFrom(Consumer<LCharToFltFunctionBuilder> buildingFunction) {
		LCharToFltFunctionBuilder builder = new LCharToFltFunctionBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

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


Question:
根据Content上传

@param string $content
@param string $type
@param array $option
@return array

public function uploadByContent($content, $type = '', $option = [])
    {
        // 临时文件
        $tmp_file = Common::tmpFile('upload');
        file_put_contents($tmp_file, $content);

        // 上传完删除文件
        $this->onDone = function ($data) {
            @unlink($data['path']);
        };

        return $this->uploadByPath($tmp_file, $type, $option);
    }

public function render()
    {
        $htmlContent = '';
        $htmlContent .= $this->charset->render();
        $htmlContent .= $this->meta->render();
        $htmlContent .= $this->title->render();
        $htmlContent .= $this->link->render();
        $htmlContent .= $this->css->render();
        $htmlContent .= $this->icon->render();
        return $htmlContent;
    }

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


Question: // UnmarshalBinary parses the given binary slice as a Message.

func (m *Message) UnmarshalBinary(data []byte) error {
	if len(data) < 4 {
		return errors.New("short packet")
	}

	if data[0]>>6 != 1 {
		return errors.New("invalid version")
	}

	m.Type = COAPType((data[0] >> 4) & 0x3)
	tokenLen := int(data[0] & 0xf)
	if tokenLen > 8 {
		return ErrInvalidTokenLen
	}

	m.Code = COAPCode(data[1])
	m.MessageID = binary.BigEndian.Uint16(data[2:4])

	if tokenLen > 0 {
		m.Token = make([]byte, tokenLen)
	}
	if len(data) < 4+tokenLen {
		return errors.New("truncated")
	}
	copy(m.Token, data[4:4+tokenLen])
	b := data[4+tokenLen:]
	prev := 0

	parseExtOpt := func(opt int) (int, error) {
		switch opt {
		case extoptByteCode:
			if len(b) < 1 {
				return -1, errors.New("truncated")
			}
			opt = int(b[0]) + extoptByteAddend
			b = b[1:]
		case extoptWordCode:
			if len(b) < 2 {
				return -1, errors.New("truncated")
			}
			opt = int(binary.BigEndian.Uint16(b[:2])) + extoptWordAddend
			b = b[2:]
		}
		return opt, nil
	}

	for len(b) > 0 {
		if b[0] == 0xff {
			b = b[1:]
			break
		}

		delta := int(b[0] >> 4)
		length := int(b[0] & 0x0f)

		if delta == extoptError || length == extoptError {
			return errors.New("unexpected extended option marker")
		}

		b = b[1:]

		delta, err := parseExtOpt(delta)
		if err != nil {
			return err
		}
		length, err = parseExtOpt(length)
		if err != nil {
			return err
		}

		if len(b) < length {
			return errors.New("truncated")
		}

		oid := OptionID(prev + delta)
		opval := parseOptionValue(oid, b[:length])
		b = b[length:]
		prev = int(oid)

		if opval != nil {
			m.opts = append(m.opts, option{ID: oid, Value: opval})
		}
	}
	m.Payload = b
	return nil
}

func (v Value) MarshalJSON() ([]byte, error) {
	switch v.t {
	case reflect.String:
		return json.Marshal(v.s)
	case reflect.Int:
		return json.Marshal(v.i)
	case reflect.Bool:
		return json.Marshal(v.b)
	}

	return nil, fmt.Errorf("unknown value kind %v", v.t)
}

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


Question:
set panel as selected
@param {KISSY.Tabs.Panel} panel
@chainable

function (panel) {
                var self = this, bar = self.get('bar'), body = self.get('body'), selectedPanelIndex = util.indexOf(panel, body.get('children'));
                body.set('selectedPanelIndex', selectedPanelIndex);
                bar.set('selectedTab', self.getTabAt(selectedPanelIndex));
                return this;
            }

public function openGroup($name, $label = null, $options = [])
    {
        $options = $this->appendClassToOptions('form-group', $options);
        // Append the name of the group to the groupStack.
        $this->groupStack[] = $name;
        if ($this->hasErrors($name)) {
            // If the form element with the given name has any errors,
            // apply the 'has-error' class to the group.
            $options = $this->appendClassToOptions('has-error', $options);
        }
        // If a label is given, we set it up here. Otherwise, we will just
        // set it to an empty string.
        $label = $label ? $this->label($name, $label, ['class' => 'control-label']) : '';

        return '<div' . $this->html->attributes($options) . '>' . $label;
    }

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


Question:
Removes multiple models from all indices. The given searchable models must be of the same class.

@param array $searchableModels

@return array
@throws \InvalidArgumentException

public function removeMultipleFromIndices(array $searchableModels)
    {
        $algoliaRecords = $this->getAlgoliaRecordsFromSearchableModelArray($searchableModels);
        $indices = $this->initIndices($searchableModels[0]);
        $objectIds = \array_map(function ($algoliaRecord) {
            return $algoliaRecord['objectID'];
        }, $algoliaRecords);

        return $this->processIndices($indices, function (Index $index) use ($objectIds) {
            return $index->deleteObjects($objectIds);
        });
    }

public function renderNotFound($layout, $title, $type)
    {
        return ArrayData::create([
            'Type' => $type,
            'Title' => $title,
            'Layout' => $layout
        ])->renderWith('Error\Includes\NotFound');
    }

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


Question: // UnmarshalJSON deserializes into a FeatureValue instance

func (u *FeatureValue) UnmarshalJSON(body []byte) error {
	type wrap struct {
		dropbox.Tagged
		// UploadApiRateLimit : has no documentation (yet)
		UploadApiRateLimit json.RawMessage `json:"upload_api_rate_limit,omitempty"`
		// HasTeamSharedDropbox : has no documentation (yet)
		HasTeamSharedDropbox json.RawMessage `json:"has_team_shared_dropbox,omitempty"`
		// HasTeamFileEvents : has no documentation (yet)
		HasTeamFileEvents json.RawMessage `json:"has_team_file_events,omitempty"`
		// HasTeamSelectiveSync : has no documentation (yet)
		HasTeamSelectiveSync json.RawMessage `json:"has_team_selective_sync,omitempty"`
	}
	var w wrap
	var err error
	if err = json.Unmarshal(body, &w); err != nil {
		return err
	}
	u.Tag = w.Tag
	switch u.Tag {
	case "upload_api_rate_limit":
		err = json.Unmarshal(w.UploadApiRateLimit, &u.UploadApiRateLimit)

		if err != nil {
			return err
		}
	case "has_team_shared_dropbox":
		err = json.Unmarshal(w.HasTeamSharedDropbox, &u.HasTeamSharedDropbox)

		if err != nil {
			return err
		}
	case "has_team_file_events":
		err = json.Unmarshal(w.HasTeamFileEvents, &u.HasTeamFileEvents)

		if err != nil {
			return err
		}
	case "has_team_selective_sync":
		err = json.Unmarshal(w.HasTeamSelectiveSync, &u.HasTeamSelectiveSync)

		if err != nil {
			return err
		}
	}
	return nil
}

public JsonPropertyCoder<T, P> fix() {
		JsonPropertyCoder<T, P> coder = null;
		try {
			coder = coderClass.newInstance();
		} catch (InstantiationException e) {
			throw new IllegalArgumentException(e);
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException(e);
		}
		coder.name = this.name;
		coder.coder = this.coder;
		coder.router = this.router;

		return coder;
	}

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


Question: // Transform implements the Transformer interface.

func (t removeF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
	for r, sz := rune(0), 0; len(src) > 0; src = src[sz:] {

		if r = rune(src[0]); r < utf8.RuneSelf {
			sz = 1
		} else {
			r, sz = utf8.DecodeRune(src)

			if sz == 1 {
				// Invalid rune.
				if !atEOF && !utf8.FullRune(src) {
					err = ErrShortSrc
					break
				}
				// We replace illegal bytes with RuneError. Not doing so might
				// otherwise turn a sequence of invalid UTF-8 into valid UTF-8.
				// The resulting byte sequence may subsequently contain runes
				// for which t(r) is true that were passed unnoticed.
				if !t(r) {
					if nDst+3 > len(dst) {
						err = ErrShortDst
						break
					}
					nDst += copy(dst[nDst:], "\uFFFD")
				}
				nSrc++
				continue
			}
		}

		if !t(r) {
			if nDst+sz > len(dst) {
				err = ErrShortDst
				break
			}
			nDst += copy(dst[nDst:], src[:sz])
		}
		nSrc += sz
	}
	return
}

public void addSubstitutionFont(BaseFont font) {
        if (substitutionFonts == null)
            substitutionFonts = new ArrayList();
        substitutionFonts.add(font);
    }

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


Question:
Create an instance of {@link JAXBElement }{@code <}{@link GeneralConversionRefType }{@code >}

@param value
Java instance representing xml element's value.
@return
the new instance of {@link JAXBElement }{@code <}{@link GeneralConversionRefType }{@code >}

@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "definedByConversion")
    public JAXBElement<GeneralConversionRefType> createDefinedByConversion(GeneralConversionRefType value) {
        return new JAXBElement<GeneralConversionRefType>(_DefinedByConversion_QNAME, GeneralConversionRefType.class, null, value);
    }

@Nullable
    public static ResourceValue readResValue(ByteBuffer buffer, StringPool stringPool) {
//        ResValue resValue = new ResValue();
        int size = Buffers.readUShort(buffer);
        short res0 = Buffers.readUByte(buffer);
        short dataType = Buffers.readUByte(buffer);

        switch (dataType) {
            case ResValue.ResType.INT_DEC:
                return ResourceValue.decimal(buffer.getInt());
            case ResValue.ResType.INT_HEX:
                return ResourceValue.hexadecimal(buffer.getInt());
            case ResValue.ResType.STRING:
                int strRef = buffer.getInt();
                if (strRef >= 0) {
                    return ResourceValue.string(strRef, stringPool);
                } else {
                    return null;
                }
            case ResValue.ResType.REFERENCE:
                return ResourceValue.reference(buffer.getInt());
            case ResValue.ResType.INT_BOOLEAN:
                return ResourceValue.bool(buffer.getInt());
            case ResValue.ResType.NULL:
                return ResourceValue.nullValue();
            case ResValue.ResType.INT_COLOR_RGB8:
            case ResValue.ResType.INT_COLOR_RGB4:
                return ResourceValue.rgb(buffer.getInt(), 6);
            case ResValue.ResType.INT_COLOR_ARGB8:
            case ResValue.ResType.INT_COLOR_ARGB4:
                return ResourceValue.rgb(buffer.getInt(), 8);
            case ResValue.ResType.DIMENSION:
                return ResourceValue.dimension(buffer.getInt());
            case ResValue.ResType.FRACTION:
                return ResourceValue.fraction(buffer.getInt());
            default:
                return ResourceValue.raw(buffer.getInt(), dataType);
        }
    }

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


Question:
Performs synchronization from source to destination. Performs the three
        steps:

        1. Calculate signature of destination.
        2. Generate delta from source.
        3. Apply delta to destination.

def sync(self, src, dst):

        return dst.patch(src.delta(dst.signature(block_size=self.block_size)))

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


Question: Backslash escape line.value.

def encode(cls, line):
        """"""
        if not line.encoded:
            encoding = getattr(line, 'encoding_param', None)
            if encoding and encoding.upper() == cls.base64string:
                line.value = b64encode(line.value).decode('utf-8')
            else:
                line.value = backslashEscape(str_(line.value))
            line.encoded = True

func (v *VerbalExpression) EndOfLine() *VerbalExpression {
	if !strings.HasSuffix(v.suffixes, "$") {
		v.suffixes += "$"
	}
	return v
}

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


Question:
Register Menu Adapter.

@return void

protected function registerMenuAdapter()
    {
        $this->app->bind('adapter.menu', function ($app) {
            return new Menu($app['config']);
        });

        $this->app->alias('adapter.menu', Menu::class);
    }

def SetPackageView(self, directoryView):
        """"""
        self.directoryView = not self.directoryView
        self.packageMenuItem.Check(self.directoryView)
        self.packageViewTool.SetValue(self.directoryView)
        if self.loader:
            self.SetModel(self.loader)
        self.RecordHistory()

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


Question:
@param Closure|TabInterface[] $tabs

@return $this

public function setTabs($tabs)
    {
        if (is_callable($tabs)) {
            $tabs = call_user_func($tabs, $this);
        }

        return $this->setElements($tabs);
    }

function( event, eventData ) {
		var that = this,
			toShow = eventData.newPanel,
			toHide = eventData.oldPanel;

		this.running = true;

		function complete() {
			that.running = false;
			that._trigger( "activate", event, eventData );
		}

		function show() {
			eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );

			if ( toShow.length && that.options.show ) {
				that._show( toShow, that.options.show, complete );
			} else {
				toShow.show();
				complete();
			}
		}

		// start out by hiding, then showing, then completing
		if ( toHide.length && this.options.hide ) {
			this._hide( toHide, this.options.hide, function() {
				eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
				show();
			});
		} else {
			eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
			toHide.hide();
			show();
		}

		toHide.attr({
			"aria-expanded": "false",
			"aria-hidden": "true"
		});
		eventData.oldTab.attr( "aria-selected", "false" );
		// If we're switching tabs, remove the old tab from the tab order.
		// If we're opening from collapsed state, remove the previous tab from the tab order.
		// If we're collapsing, then keep the collapsing tab in the tab order.
		if ( toShow.length && toHide.length ) {
			eventData.oldTab.attr( "tabIndex", -1 );
		} else if ( toShow.length ) {
			this.tabs.filter(function() {
				return $( this ).attr( "tabIndex" ) === 0;
			})
			.attr( "tabIndex", -1 );
		}

		toShow.attr({
			"aria-expanded": "true",
			"aria-hidden": "false"
		});
		eventData.newTab.attr({
			"aria-selected": "true",
			tabIndex: 0
		});
	}

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


Question: // buildProjectionFieldNameFromExpressions builds the field name when field expression is a normal expression.

func (b *PlanBuilder) buildProjectionFieldNameFromExpressions(field *ast.SelectField) (model.CIStr, error) {
	if agg, ok := field.Expr.(*ast.AggregateFuncExpr); ok && agg.F == ast.AggFuncFirstRow {
		// When the query is select t.a from t group by a; The Column Name should be a but not t.a;
		return agg.Args[0].(*ast.ColumnNameExpr).Name.Name, nil
	}

	innerExpr := getInnerFromParenthesesAndUnaryPlus(field.Expr)
	funcCall, isFuncCall := innerExpr.(*ast.FuncCallExpr)
	// When used to produce a result set column, NAME_CONST() causes the column to have the given name.
	// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_name-const for details
	if isFuncCall && funcCall.FnName.L == ast.NameConst {
		if v, err := evalAstExpr(b.ctx, funcCall.Args[0]); err == nil {
			if s, err := v.ToString(); err == nil {
				return model.NewCIStr(s), nil
			}
		}
		return model.NewCIStr(""), ErrWrongArguments.GenWithStackByArgs("NAME_CONST")
	}
	valueExpr, isValueExpr := innerExpr.(*driver.ValueExpr)

	// Non-literal: Output as inputed, except that comments need to be removed.
	if !isValueExpr {
		return model.NewCIStr(parser.SpecFieldPattern.ReplaceAllStringFunc(field.Text(), parser.TrimComment)), nil
	}

	// Literal: Need special processing
	switch valueExpr.Kind() {
	case types.KindString:
		projName := valueExpr.GetString()
		projOffset := valueExpr.GetProjectionOffset()
		if projOffset >= 0 {
			projName = projName[:projOffset]
		}
		// See #3686, #3994:
		// For string literals, string content is used as column name. Non-graph initial characters are trimmed.
		fieldName := strings.TrimLeftFunc(projName, func(r rune) bool {
			return !unicode.IsOneOf(mysql.RangeGraph, r)
		})
		return model.NewCIStr(fieldName), nil
	case types.KindNull:
		// See #4053, #3685
		return model.NewCIStr("NULL"), nil
	case types.KindBinaryLiteral:
		// Don't rewrite BIT literal or HEX literals
		return model.NewCIStr(field.Text()), nil
	case types.KindInt64:
		// See #9683
		// TRUE or FALSE can be a int64
		if mysql.HasIsBooleanFlag(valueExpr.Type.Flag) {
			if i := valueExpr.GetValue().(int64); i == 0 {
				return model.NewCIStr("FALSE"), nil
			}
			return model.NewCIStr("TRUE"), nil
		}
		fallthrough

	default:
		fieldName := field.Text()
		fieldName = strings.TrimLeft(fieldName, "\t\n +(")
		fieldName = strings.TrimRight(fieldName, "\t\n )")
		return model.NewCIStr(fieldName), nil
	}
}

public function project(Operand\RootPath $path /*, $path2, ... */)
    {
        $this->projection->add(...func_get_args());

        return $this->qb;
    }

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


Question:
Generates the current page's URL.

Uses the provided GET parameters, page id and language id.

@return string URL of the current page.

protected function generatePageUrl()
    {
        if ($this->request->getParameter('overridePageUrl')) {
            return $this->request->getParameter('overridePageUrl');
        }

            /** @var $contentObject ContentObjectRenderer */
        $contentObject = GeneralUtility::makeInstance(ContentObjectRenderer::class);

        $typolinkConfiguration = [
            'parameter' => intval($this->page->id),
            'linkAccessRestrictedPages' => '1'
        ];

        $language = GeneralUtility::_GET('L');
        if (!empty($language)) {
            $typolinkConfiguration['additionalParams'] = '&L=' . $language;
        }

        $url = $contentObject->typoLink_URL($typolinkConfiguration);

        // clean up
        if ($url == '') {
            $url = '/';
        }

        return $url;
    }

protected static function _createUriString($scheme, $authority, $path, $query, $fragment)
    {
        $uri = '';

        if (! empty($scheme)) {
            $uri .= sprintf('%s://', $scheme);
        }

        if (! empty($authority)) {
            $uri .= $authority;
        }

        if ($path) {
            if (empty($path) || '/' !== substr($path, 0, 1)) {
                $path = '/' . $path;
            }

            $uri .= $path;
        }

        if ($query) {
            $uri .= sprintf('?%s', $query);
        }

        if ($fragment) {
            $uri .= sprintf('#%s', $fragment);
        }

        return $uri;
    }

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


Question:
Dynamically insert sections adjacent to a reference section.
{aria.templates.CfgBeans.InsertAdjacentSectionsCfg} args Adjacent sections configuration.

function (args) {
            var position = args.position;
            var validatorParam = {
                json : args,
                beanName : "aria.templates.CfgBeans.InsertAdjacentSectionsCfg"
            };
            ariaCoreJsonValidator.normalize(validatorParam);
            var topSection = this.createSection({
                fn : this.__dynamicSectionWriter,
                scope : this,
                args : args
            });
            // insert the new section items in the DOM and initialize them
            ariaUtilsDom.insertAdjacentHTML(args.refSection.domElt, position, topSection.html);
            ariaUtilsDom.refreshDomElt(this._cfg.tplDiv);
            var parentSection = args.refSection.object;
            if (position == "beforeBegin" || position == "afterEnd") {
                parentSection = parentSection.parent;
            }
            this.$assert(459, parentSection);
            // put the content at the right place inside the widget
            // and initialize it
            var differed = topSection.moveContentTo(parentSection);
            topSection.$dispose();
            this.$assert(466, differed);
            this.__processDifferedItems(differed);
            for (var i = 0; i < args.sections.length; i++) {
                this.afterRefresh({
                    section : args.sections[i].id
                });
            }
        }

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question:
Return a string describing the internal state of a task.  Useful for
 debugging.

def investigation
      result = "------------------------------\n"
      result << "Investigating #{name}\n"
      result << "class: #{self.class}\n"
      result <<  "task needed: #{needed?}\n"
      result <<  "timestamp: #{timestamp}\n"
      result << "pre-requisites: \n"
      prereqs = @prerequisites.collect {|name| application[name]}
      prereqs.sort! {|a,b| a.timestamp <=> b.timestamp}
      prereqs.each do |p|
        result << "--#{p.name} (#{p.timestamp})\n"
      end
      latest_prereq = @prerequisites.collect{|n| application[n].timestamp}.max
      result <<  "latest-prerequisite time: #{latest_prereq}\n"
      result << "................................\n\n"
      return result
    end

def handle_single_message(self, msg):

        job_id = msg.message['job_id']
        actual_msg = msg.message
        if msg.type == MessageType.JOB_UPDATED:
            progress = actual_msg['progress']
            total_progress = actual_msg['total_progress']
            self.storage_backend.update_job_progress(job_id, progress,
                                                     total_progress)
        elif msg.type == MessageType.JOB_COMPLETED:
            self.storage_backend.complete_job(job_id)
        elif msg.type == MessageType.JOB_FAILED:
            exc = actual_msg['exception']
            trace = actual_msg['traceback']
            self.storage_backend.mark_job_as_failed(job_id, exc, trace)
        elif msg.type == MessageType.JOB_CANCELED:
            self.storage_backend.mark_job_as_canceled(job_id)
        else:
            self.logger.error("Unknown message type: {}".format(msg.type))

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


Question:
removes child from the directory

@param   string  $name
@return  bool

public function removeChild(string $name): bool
    {
        foreach ($this->children as $key => $child) {
            if ($child->appliesTo($name)) {
                $child->removeParentPath();
                unset($this->children[$key]);
                $this->updateModifications();
                return true;
            }
        }

        return false;
    }

protected function setupDeleteReference($resource)
    {
        foreach ($resource->settings['actions']['DeleteReference']['uris'] as $property => $uri) {
            $this->setupDelete($resource, $uri, $property);
        }
    }

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


Question: // updateNFSNetworkStats collects statistics for network packets/connections.

func (c *nfsCollector) updateNFSNetworkStats(ch chan<- prometheus.Metric, s *nfs.Network) {
	ch <- prometheus.MustNewConstMetric(c.nfsNetReadsDesc, prometheus.CounterValue,
		float64(s.UDPCount), "udp")
	ch <- prometheus.MustNewConstMetric(c.nfsNetReadsDesc, prometheus.CounterValue,
		float64(s.TCPCount), "tcp")
	ch <- prometheus.MustNewConstMetric(c.nfsNetConnectionsDesc, prometheus.CounterValue,
		float64(s.TCPConnect))
}

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

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


Question:
// Log a message at LEVEL_ERR with 'format' populated with values from 'va'. The
// attributes from 'attrs' will be included with the message, overriding any that may
// be set at the Logger level

func (l *Logger) Errm(attrs map[string]interface{}, format string, va ...interface{}) error {
	return l.logMsg(attrs, LEVEL_ERR, format, va...)
}

def load_from_file(swag_path, swag_type='yml', root_path=None):

    if swag_type not in ('yaml', 'yml'):
        raise AttributeError("Currently only yaml or yml supported")
        # TODO: support JSON

    try:
        enc = detect_by_bom(swag_path)
        with codecs.open(swag_path, encoding=enc) as yaml_file:
            return yaml_file.read()
    except IOError:
        # not in the same dir, add dirname
        swag_path = os.path.join(
            root_path or os.path.dirname(__file__), swag_path
        )
        try:
            enc = detect_by_bom(swag_path)
            with codecs.open(swag_path, encoding=enc) as yaml_file:
                return yaml_file.read()
        except IOError:  # pragma: no cover
            # if package dir
            # see https://github.com/rochacbruno/flasgger/pull/104
            # Still not able to reproduce this case
            # test are in examples/package_example
            # need more detail on how to reproduce IOError here
            swag_path = swag_path.replace("/", os.sep).replace("\\", os.sep)
            path = swag_path.replace(
                (root_path or os.path.dirname(__file__)), ''
            ).split(os.sep)[1:]
            site_package = imp.find_module(path[0])[1]
            swag_path = os.path.join(site_package, os.sep.join(path[1:]))
            with open(swag_path) as yaml_file:
                return yaml_file.read()

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