Question:
Return a new {@link Client} instance

@param clientClass the runtime instance class of {@link Client} instance that is returned
@return a new {@link Client} instance

public <T extends Client<? extends Options, ? extends OptionsBuilder, ? extends RequestBuilder>> T newClient(Class<? extends Client> clientClass) {
        Client client;
        try {
            client = clientClass.newInstance();
            return (T) client;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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:
Set the MessagingAuthenticationService

@param messagingAuthenticationService

public void setMessagingAuthenticationService(
			MessagingAuthenticationService messagingAuthenticationService) {
		if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
			SibTr.entry(tc, CLASS_NAME + "setMessagingAuthenticationService",
					messagingAuthenticationService);
		}
		this.messagingAuthenticationService = messagingAuthenticationService;
		if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
			SibTr.exit(tc, CLASS_NAME + "setMessagingAuthenticationService");
		}
	}

protected function getParameter(string $name)
    {
        if (!$this->container->has('parameter_bag')) {
            throw new ServiceNotFoundException('parameter_bag', null, null, [], sprintf('The "%s::getParameter()" method is missing a parameter bag to work properly. Did you forget to register your controller as a service subscriber? This can be fixed either by using autoconfiguration or by manually wiring a "parameter_bag" in the service locator passed to the controller.', \get_class($this)));
        }

        return $this->container->get('parameter_bag')->get($name);
    }

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


Question:
Compose queue

@param {string} [name]
@returns {Use}
@example
usecase('name').use([f1, f2])(param)
usecase('name').use(f1).use(f2)(param)

function usecase(name) {
        let $queue = [];
        let $run;
        return { use };
        function use(arg) {
            let q = [].concat(arg);
            q = $enhancer ? q.map((t) => $enhancer(name, t)) : q;
            q.forEach(t => $queue.push(t));
            return $run || (() => {
                $run = run;
                $run.use = use;
                return $run;
            })();
        }
        function run() {
            next($queue[Symbol.iterator](), arguments[0]);
        }
        ;
    }

def parse_temperature_response(
        temperature_string: str) -> Mapping[str, Optional[float]]:
    '''

    '''
    err_msg = 'Unexpected argument to parse_temperature_response: {}'.format(
        temperature_string)
    if not temperature_string or \
            not isinstance(temperature_string, str):
        raise ParseError(err_msg)
    parsed_values = temperature_string.strip().split(' ')
    if len(parsed_values) < 2:
        log.error(err_msg)
        raise ParseError(err_msg)

    data = {
        parse_key_from_substring(s): parse_number_from_substring(s)
        for s in parsed_values[:2]
    }
    if 'C' not in data or 'T' not in data:
        raise ParseError(err_msg)
    data = {
        'current': data['C'],
        'target': data['T']
    }
    return data

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


Question:
Switches the format of the outputted QrCode or defaults to SVG.

@param string $format The desired format.

@throws \InvalidArgumentException

@return $this

public function format($format)
    {
        switch ($format) {
            case 'png':
                $this->writer->setRenderer(new Png());
                break;
            case 'eps':
                $this->writer->setRenderer(new Eps());
                break;
            case 'svg':
                $this->writer->setRenderer(new Svg());
                break;
            default:
                throw new \InvalidArgumentException('Invalid format provided.');
        }

        return $this;
    }

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question: // Runs cfg.Queries bootstrap queries every cfg.Period.

func (dht *IpfsDHT) BootstrapWithConfig(ctx context.Context, cfg BootstrapConfig) error {
	// Because this method is not synchronous, we have to duplicate sanity
	// checks on the config so that callers aren't oblivious.
	if cfg.Queries <= 0 {
		return fmt.Errorf("invalid number of queries: %d", cfg.Queries)
	}
	go func() {
		for {
			err := dht.runBootstrap(ctx, cfg)
			if err != nil {
				logger.Warningf("error bootstrapping: %s", err)
			}
			select {
			case <-time.After(cfg.Period):
			case <-ctx.Done():
				return
			}
		}
	}()
	return nil
}

function () {
    console.log( package.title );
    console.log( package.description );
    console.log( "Version " + package.version );
    console.log();
    console.log( "Commands:" );
    console.log( "sqs buster       Delete local site cache" );
    console.log( "sqs server       Start the local server" );
    console.log();
    console.log( "Options:" );
    console.log( "sqs --version    Print package version" );
    console.log( "sqs --forever    Start server using forever" );
    console.log( "sqs --fornever   Stop server started with forever" );
    console.log( "sqs --port=XXXX  Use the specified port" );
    console.log( "sqs --quiet      Silence the logger" );
    console.log( "sqs --open       Open a new tab for the server when it starts" );
    console.log();
    console.log( "Examples:" );
    console.log( "sqs server --port=8000" );
    process.exit();
}

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


Question:
/*
Merge changes submitted with MR.

    PUT /projects/:id/merge_request/:merge_request_id/merge

Parameters:

    id               The ID of a project
    merge_request_id The ID of a merge request

*/

func (g *Gitlab) ProjectMergeRequestAccept(id, merge_request_id string, req *AcceptMergeRequestRequest) (*MergeRequest, error) {
	u := g.ResourceUrl(ProjectMergeRequestMergeApiPath, map[string]string{
		":id":               id,
		":merge_request_id": merge_request_id,
	})

	encodedRequest, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}

	data, _, err := g.buildAndExecRequest("PUT", u.String(), encodedRequest)
	if err != nil {
		return nil, err
	}

	mr := new(MergeRequest)
	err = json.Unmarshal(data, mr)
	if err != nil {
		panic(err)
	}
	return mr, nil
}

public void marshall(AbortMultipartUploadRequest abortMultipartUploadRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(abortMultipartUploadRequest.getAccountId(), ACCOUNTID_BINDING);
            protocolMarshaller.marshall(abortMultipartUploadRequest.getVaultName(), VAULTNAME_BINDING);
            protocolMarshaller.marshall(abortMultipartUploadRequest.getUploadId(), UPLOADID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Swaps width with height if rotated 90° clock-wise or counter clock-wise
@param width Rendition width
@param height Rendition height
@return Width

private long rotateMapWidth(long width, long height) {
    if (rotation != null && (rotation == ROTATE_90 || rotation == ROTATE_270)) {
      return height;
    }
    else {
      return width;
    }
  }

protected function getDimensions()
    {
        // Default result
        $result = [0, 0];

        // If we have a resource already loaded, this means we have modified the resource since the
        // original image was loaded. This means the "Variant" tuple key is out of date, and we don't
        // have a reliable cache key to load from, or save to. If we use the original tuple as a key,
        // we would run the risk of overwriting the original dimensions in the cache, with the values
        // of the resized instead.
        // Instead, we use the immediately available dimensions attached to this resource, and we will
        // rely on cache warming in writeToStore to save these values, where the "Variant" becomes available,
        // before the next time this variant is loaded into memory.
        $resource = $this->image;
        if ($resource) {
            return $this->getResourceDimensions($resource);
        }

        // Check if we have a container
        $container = $this->getAssetContainer();
        if (!$container) {
            return $result;
        }

        // Check cache for unloaded image
        $cache = $this->getCache();
        $key = $this->getDimensionCacheKey($container->getHash(), $container->getVariant());
        if ($cache->has($key)) {
            return $cache->get($key);
        }

        // Cache-miss
        $resource = $this->getImageResource();
        if ($resource) {
            $result = $this->getResourceDimensions($resource);
            $cache->set($key, $result);
        }
        return $result;
    }

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


Question: // Format returns the formatted string of UUID.

func (u UUID) Format(style Style) string {
	switch style {
	case StyleWithoutDash:
		return fmt.Sprintf("%x", u[:])
	//case StyleStandard:
	default:
		return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", u[:4], u[4:6], u[6:8], u[8:10], u[10:])
	}
}

public static void setWorkUnitGuid(State state, Guid guid) {
    state.setProp(WORK_UNIT_GUID, guid.toString());
  }

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


Question: // SetBudgetName sets the BudgetName field's value.

func (s *DescribeNotificationsForBudgetInput) SetBudgetName(v string) *DescribeNotificationsForBudgetInput {
	s.BudgetName = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
Internal method. Returns a characteristic path of the
        pattern tree. This method must be run for all leaves until the
        linear subpatterns are merged into a single

def leaf_to_root(self):
        """"""
        node = self
        subp = []
        while node:
            if node.type == TYPE_ALTERNATIVES:
                node.alternatives.append(subp)
                if len(node.alternatives) == len(node.children):
                    #last alternative
                    subp = [tuple(node.alternatives)]
                    node.alternatives = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == TYPE_GROUP:
                node.group.append(subp)
                #probably should check the number of leaves
                if len(node.group) == len(node.children):
                    subp = get_characteristic_subpattern(node.group)
                    node.group = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == token_labels.NAME and node.name:
                #in case of type=name, use the name instead
                subp.append(node.name)
            else:
                subp.append(node.type)

            node = node.parent
        return subp

@Inline(value = "translate($1, null, $2, $3)")
	public void translate(List<? extends S> thePath, double curvilineCoord, double shiftCoord) {
		translate(thePath, null, curvilineCoord, shiftCoord);
	}

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


Question:
Returns the set of all strong link references from the files to publish.<p>

@return the set of all strong link references

protected Set<String> getStrongLinkReferences() {

        Set<String> includingFiles = new HashSet<String>();
        CmsDbContext dbc = m_publishEngine.getDbContext(getCms().getRequestContext());
        try {
            // use the online project
            CmsObject jspCms = OpenCms.initCmsObject(m_publishJob.getCmsObject());
            jspCms.getRequestContext().setCurrentProject(jspCms.readProject(CmsProject.ONLINE_PROJECT_ID));
            // collect jsp referencing information
            m_report.println(
                Messages.get().container(Messages.RPT_JSPLOADER_UPDATE_CACHE_BEGIN_0),
                I_CmsReport.FORMAT_HEADLINE);
            int plainId = OpenCms.getResourceManager().getResourceType(
                CmsResourceTypePlain.getStaticTypeName()).getTypeId();
            Iterator<CmsResource> it = m_publishJob.getPublishList().getFileList().iterator();
            while (it.hasNext()) {
                CmsResource resource = it.next();
                if ((CmsResourceTypeJsp.isJsp(resource)) || (resource.getTypeId() == plainId)) {
                    m_report.print(
                        Messages.get().container(Messages.RPT_JSPLOADER_UPDATE_CACHE_0),
                        I_CmsReport.FORMAT_NOTE);
                    m_report.print(
                        org.opencms.report.Messages.get().container(
                            org.opencms.report.Messages.RPT_ARGUMENT_1,
                            dbc.removeSiteRoot(resource.getRootPath())));
                    m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
                    m_jspLoader.getReferencingStrongLinks(jspCms, resource, includingFiles);
                    m_report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                        I_CmsReport.FORMAT_OK);
                }
            }
        } catch (Throwable e) {
            // catch every thing including runtime exceptions
            m_report.println(e);
        } finally {
            dbc.clear();
            dbc = null;
            m_report.println(
                Messages.get().container(Messages.RPT_JSPLOADER_UPDATE_CACHE_END_0),
                I_CmsReport.FORMAT_HEADLINE);
        }
        return includingFiles;
    }

def update_docs(readme=True, makefiles=True):

    if readme:
        _pandoc = get_external_executable("pandoc")
        rst2markdown_github(os.path.join(_HERE, "README.rst"),
                            os.path.join(_HERE, "README.md"),
                            pandoc=_pandoc)

    if makefiles:
        _make = get_external_executable("make")
        project_makefile_dir = os.path.abspath(_HERE)
        project_makefile_rst = os.path.join(
            _HERE,
            'docs',
            'src',
            'project_makefile.rst')
        docs_makefile_dir = os.path.join(_HERE, 'docs', 'src')
        docs_makefile_rst = os.path.join(
            _HERE,
            'docs',
            'src',
            'docs_makefile.rst')

        #: ``help2rst_queue`` stores tuples of
        #: ``(cwd, help_cmd, path_to_rst_file, rst_title_of_new_file)``
        help2rst_queue = [
            (project_makefile_dir, [_make, "help"], project_makefile_rst,
             "Project ``Makefile``"),

            (docs_makefile_dir, [_make, "help"], docs_makefile_rst,
             "Documentation ``Makefile``")]

        for cwd, help_cmd, outfile, title in help2rst_queue:
            console_help2rst(
                cwd,
                help_cmd,
                outfile,
                title,
                format_as_code=True)

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


Question:
Creates a new compiling class loader

@param classDir generated class directory root
@param sourceDir Java source directory root
@param args Javac arguments
@param encoding javac encoding

public static DynamicClassLoader create(ClassLoader parent,
                                          PathImpl classDir, PathImpl sourceDir,
                                          String args, String encoding)
  {
    DynamicClassLoader loader = new DynamicClassLoader(parent);
    loader.addLoader(new CompilingLoader(loader, classDir, sourceDir, args, encoding));

    loader.init();

    return loader;
  }

def tar(self, appname, appversion):

        name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2'
        time = utc.now()
        name = name_tmpl % {'app': appname,
                            'version': appversion,
                            'time': time.strftime('%Y-%m-%dT%H-%M')}

        if not os.path.exists(TARBALL_HOME):
            os.mkdir(TARBALL_HOME)
        tarball = os.path.join(TARBALL_HOME, name)
        tar_params = {'filename': tarball, 'folder': self.folder}
        tar_result = run('tar -C %(folder)s -cjf %(filename)s .' % tar_params)
        tar_result.raise_for_status()
        return Build(appname, appversion, time, tarball)

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


Question:
(non-Javadoc)

@see com.sematext.ag.source.FiniteEventSource#init(com.sematext.ag.PlayerConfig)

@Override
  public synchronized void init(PlayerConfig config) {
    super.init(config);
    searchFieldName = config.get(SEARCH_FIELD_NAME_KEY);
    if (searchFieldName == null || "".equals(searchFieldName.trim())) {
      throw new IllegalArgumentException(this.getClass().getName() + " expects configuration property "
          + SEARCH_FIELD_NAME_KEY);
    }
  }

private void storeEntityInformation(List<Chain> allChains, List<EntityInfo> entityInfos) {
		for (EntityInfo entityInfo : entityInfos) {
			String description = entityInfo.getDescription();
			String type;
			if (entityInfo.getType()==null){
				type = null;
			}
			else{
				type = entityInfo.getType().getEntityType();
			}
			List<Chain> entityChains = entityInfo.getChains();
			if (entityChains.isEmpty()){
				// Error mapping chain to entity
				System.err.println("ERROR MAPPING CHAIN TO ENTITY: "+description);
				mmtfDecoderInterface.setEntityInfo(new int[0], "", description, type);
				continue;
			}
			else{
				int[] chainIndices = new int[entityChains.size()];
				for (int i=0; i<entityChains.size(); i++) {
					chainIndices[i] = allChains.indexOf(entityChains.get(i));
				}
				Chain chain = entityChains.get(0);
				ChainImpl chainImpl;
				if (chain instanceof ChainImpl){
					chainImpl = (ChainImpl) entityChains.get(0);
				}
				else{
					throw new RuntimeException();
				}
				String sequence = chainImpl.getSeqResOneLetterSeq();
				mmtfDecoderInterface.setEntityInfo(chainIndices, sequence, description, type);
			}
		}
	}

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


Question:
Function that generates population.

        Called by ``__init__`` if ``M`` is passed.

def generate(self, M, age=9.6, feh=0.0,
                 ichrone='mist', n=1e4, bands=None, **kwargs):

        ichrone = get_ichrone(ichrone, bands=bands)
        if np.size(M) > 1:
            n = np.size(M)
        else:
            n = int(n)
        M2 = M * self.q_fn(n, qmin=np.maximum(self.qmin,self.minmass/M))

        P = self.P_fn(n)
        ecc = self.ecc_fn(n,P)

        mass = np.ascontiguousarray(np.ones(n)*M)
        mass2 = np.ascontiguousarray(M2)
        age = np.ascontiguousarray(age)
        feh = np.ascontiguousarray(feh)
        pri = ichrone(mass, age, feh, return_df=True, bands=bands)
        sec = ichrone(mass2, age, feh, return_df=True, bands=bands)

        BinaryPopulation.__init__(self, primary=pri, secondary=sec,
                                  period=P, ecc=ecc, **kwargs)
        return self

func (pin Pin) DutyCycle(dutyLen, cycleLen uint32) {
	SetDutyCycle(pin, dutyLen, cycleLen)
}

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


Question:
Sets JDBC Connection Properties to be used when physical
connections are obtained for the pool.

public Object setConnectionProperty(String name, String value) {
        return connProperties.setProperty(name, value);
    }

public Location load(Serializable id) {
		String sql = "select * from Location where id = ?";
		return getSimpleJdbcTemplate().queryForObject(sql, new LocationMapper(), id);
	}

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


Question:
Called on callback.
@since 1.0.0

@param Order $order Order.
@param mixed $data  Request input from callback.

@return bool

public function onCallbackSuccess($order, $data = null)
    {
        try {

            $response = $this->omnipay->completePurchase([
                'transactionId'    => $order->transactionId,
            ])->send();

            if ($response->isSuccessful()) {

                $this->statusCode = 'completed';

                $this->transactionId = $this->omnipay->getTransactionId();

                $this->detail = 'Success';

            } else {

                throw new GatewayException($response->getMessage(), 1);

            }

        } catch (\Exception $e) {

            throw new GatewayException(
                $e->getMessage(),
                1000,
                $e
            );

        }
    }

private function parseOptions(array $options): array
    {
        $child = $options['child'] ?? [];

        if (isset($options['header'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['header' => $options['header']]);
        }

        if (isset($options['divider'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['divider' => true]);
        }

        if (isset($options['icon'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['icon' => $options['icon']]);
        }

        if (isset($options['route']) && is_array($options['route'])) {
            $options['routeParameters'] = $options['route']['[parameters'] ?? [];
            $options['route'] = $options['route']['name'];
        }

        foreach ($this->parsers as $parser) {
            if ($result = $parser($options)) {
                $options = $result;
            }
        }

        unset($options['child']);

        return [
            'options' => $options,
            'child' => $child,
        ];
    }

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


Question:
Get the evaluated contents of the view.

@param  string $path
@param  array  $data
@return string

public function get($path, array $data = array())
    {
        $this->lastCompiled[] = $path;

        // If this given view has expired, which means it has simply been edited since
        // it was last compiled, we will re-compile the views so we can evaluate a
        // fresh copy of the view. We'll pass the compiler the path of the view.
        if ($this->compiler->isExpired($path)) {
            $this->compiler->compile($path);
        }

        $raw = (isset($data['raw']) && $data['raw']) ? true : false;
        $compiled = $this->compiler->getCompiledPath($path, $raw);

        // convert objects to arrays
        $data = array_map('self::convertObjectToArray', $data);

        // Once we have the path to the compiled file, we will evaluate the paths with
        // typical PHP just like any other templates. We also keep a stack of views
        // which have been rendered for right exception messages to be generated.
        $results = $this->evaluatePath($compiled, $data);

        array_pop($this->lastCompiled);

        return $results;
    }

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

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

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

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

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

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

        return $info;
    }

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


Question:
Get a namespace entry from a regular expression.

        Need to commit after!

        :param namespace: The name of the namespace
        :param pattern: The regular expression pattern for the namespace
        :param name: The entry to get

def get_or_create_regex_namespace_entry(self, namespace: str, pattern: str, name: str) -> NamespaceEntry:

        namespace = self.ensure_regex_namespace(namespace, pattern)

        n_filter = and_(Namespace.pattern == pattern, NamespaceEntry.name == name)

        name_model = self.session.query(NamespaceEntry).join(Namespace).filter(n_filter).one_or_none()

        if name_model is None:
            name_model = NamespaceEntry(
                namespace=namespace,
                name=name
            )
            self.session.add(name_model)

        return name_model

public final QueryParser.regex_match_return regex_match() throws RecognitionException {
        QueryParser.regex_match_return retval = new QueryParser.regex_match_return();
        retval.start = input.LT(1);

        CommonTree root_0 = null;

        Token WS41=null;
        Token REGEX_MATCH42=null;
        Token WS43=null;
        QueryParser.field_return field40 = null;

        QueryParser.value_return value44 = null;

        CommonTree WS41_tree=null;
        CommonTree REGEX_MATCH42_tree=null;
        CommonTree WS43_tree=null;

        try {
            // src/riemann/Query.g:56:2: ( field ( WS )* REGEX_MATCH ( WS )* value )
            // src/riemann/Query.g:56:4: field ( WS )* REGEX_MATCH ( WS )* value
            {
            root_0 = (CommonTree)adaptor.nil();

            pushFollow(FOLLOW_field_in_regex_match376);
            field40=field();

            state._fsp--;

            adaptor.addChild(root_0, field40.getTree());
            // src/riemann/Query.g:56:10: ( WS )*
            loop15:
            do {
                int alt15=2;
                int LA15_0 = input.LA(1);

                if ( (LA15_0==WS) ) {
                    alt15=1;
                }

                switch (alt15) {
            	case 1 :
            	    // src/riemann/Query.g:56:10: WS
            	    {
            	    WS41=(Token)match(input,WS,FOLLOW_WS_in_regex_match378);
            	    WS41_tree = (CommonTree)adaptor.create(WS41);
            	    adaptor.addChild(root_0, WS41_tree);

            	    }
            	    break;

            	default :
            	    break loop15;
                }
            } while (true);

            REGEX_MATCH42=(Token)match(input,REGEX_MATCH,FOLLOW_REGEX_MATCH_in_regex_match381);
            REGEX_MATCH42_tree = (CommonTree)adaptor.create(REGEX_MATCH42);
            root_0 = (CommonTree)adaptor.becomeRoot(REGEX_MATCH42_tree, root_0);

            // src/riemann/Query.g:56:27: ( WS )*
            loop16:
            do {
                int alt16=2;
                int LA16_0 = input.LA(1);

                if ( (LA16_0==WS) ) {
                    alt16=1;
                }

                switch (alt16) {
            	case 1 :
            	    // src/riemann/Query.g:56:27: WS
            	    {
            	    WS43=(Token)match(input,WS,FOLLOW_WS_in_regex_match384);
            	    WS43_tree = (CommonTree)adaptor.create(WS43);
            	    adaptor.addChild(root_0, WS43_tree);

            	    }
            	    break;

            	default :
            	    break loop16;
                }
            } while (true);

            pushFollow(FOLLOW_value_in_regex_match387);
            value44=value();

            state._fsp--;

            adaptor.addChild(root_0, value44.getTree());

            }

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

            retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
            adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);

        }
        catch (RecognitionException re) {
            reportError(re);
            recover(input,re);
    	retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);

        }
        finally {
        }
        return retval;
    }

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


Question:
Adds an element at the end of the list.

@param element
the element to add.

@return a reference to the newly added element.

public ElementReference pushBack(E element) {
        T entry = makeEntry(element);
        pushBackEntry(entry);
        return entry;
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question:
Set value

@param boolean $value

@return ValueInterface

public function setValue($value)
    {
        $this->value = ($value) ? self::TRUE : self::FALSE;

        return $this;
    }

public ApiResponse<GetInboundResponse> getInboundSettingsWithHttpInfo() throws ApiException {
        com.squareup.okhttp.Call call = getInboundSettingsValidateBeforeCall(null, null);
        Type localVarReturnType = new TypeToken<GetInboundResponse>(){}.getType();
        return apiClient.execute(call, localVarReturnType);
    }

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


Question:
Apply the specified {@link Layout}.

@param layout
The {@code Layout} to apply
@return {@code True} if the layout has been applied successfully, {@code false} otherwise.

public boolean applyLayout(Layout layout) {
        boolean applied = false;
        if (layout != null && isValidLayout(layout)) {
            Layout defaultLayout  = getDefaultLayout();
            if (layout != defaultLayout) {
                mLayouts.remove(defaultLayout);
            }
            if(mLayouts.add(layout)) {
                layout.onLayoutApplied(this, mViewPort);
                applied = true;
            }
        }
        return applied;
    }

private function configureFormatter(OutputFormatter $formatter)
    {
        $style = new OutputFormatterStyle('yellow', null, ['bold']);
        $formatter->setStyle('pathbold', $style);

        $style = new OutputFormatterStyle('green');
        $formatter->setStyle('localname', $style);

        $style = new OutputFormatterStyle(null, null, ['bold']);
        $formatter->setStyle('node', $style);

        $style = new OutputFormatterStyle('blue', null, ['bold']);
        $formatter->setStyle('templatenode', $style);

        $style = new OutputFormatterStyle('blue', null, []);
        $formatter->setStyle('templateproperty', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property', $style);

        $style = new OutputFormatterStyle('magenta', null, ['bold']);
        $formatter->setStyle('node-type', $style);

        $style = new OutputFormatterStyle('magenta', null, []);
        $formatter->setStyle('property-type', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property-value', $style);

        $style = new OutputFormatterStyle(null, 'red', []);
        $formatter->setStyle('exception', $style);
    }

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


Question:
Save error message

@param  array  error
@return false
@author Dmitry(dio) Levashov

protected function setError($error) {

		$this->error = array();

		foreach (func_get_args() as $err) {
			if (is_array($err)) {
				$this->error = array_merge($this->error, $err);
			} else {
				$this->error[] = $err;
			}
		}

		// $this->error = is_array($error) ? $error : func_get_args();
		return false;
	}

private function invalidType($name, $provided)
    {
        $expected = implode('|', $this->argDefinitions[$name]['valid']);
        $msg = "Invalid configuration value "
            . "provided for \"{$name}\". Expected {$expected}, but got "
            . describe_type($provided) . "\n\n"
            . $this->getArgMessage($name);
        throw new IAE($msg);
    }

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


Question:
Selects the Database Dialect based on the JDBC connection URL.

@param url the JDBC Connection URL
@return the dialect that maps to a specific JDBC URL.

public static Dialect getDialect(String url){
        if(url.startsWith("jdbc:mysql:")){
            return new MySQLDialect();
        } else if(url.startsWith("jdbc:postgresql:")){
            return new PostgreSQLDialect();
        } else if(url.startsWith("jdbc:oracle:")){
            return new OracleDialect();
        } else if(url.startsWith("jdbc:hsqldb:")){
            return new HyperSQLDialect();
        } else if(url.startsWith("jdbc:h2:")){
            return new H2Dialect();
        } else if(url.startsWith("jdbc:derby:")){
            return new DerbyDialect();
        } else if(url.startsWith("jdbc:sqlite:")){
            return new SQLiteDialect();
        } else if(url.startsWith("jdbc:sqlserver:") || url.startsWith("jdbc:jtds:sqlserver:")){
            return new SQLServerDialect();
        } else if(url.startsWith("jdbc:db2:") || url.startsWith("jdbc:db2j:")
                || url.startsWith("jdbc:db2:ids") || url.startsWith("jdbc:informix-sqli:")
                || url.startsWith("jdbc:as400:")){
            return new DB2Dialect();
        }
        return new StandardDialect();
    }

public void marshall(CustomerConnectorInfo customerConnectorInfo, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(customerConnectorInfo.getActiveConnectors(), ACTIVECONNECTORS_BINDING);
            protocolMarshaller.marshall(customerConnectorInfo.getHealthyConnectors(), HEALTHYCONNECTORS_BINDING);
            protocolMarshaller.marshall(customerConnectorInfo.getBlackListedConnectors(), BLACKLISTEDCONNECTORS_BINDING);
            protocolMarshaller.marshall(customerConnectorInfo.getShutdownConnectors(), SHUTDOWNCONNECTORS_BINDING);
            protocolMarshaller.marshall(customerConnectorInfo.getUnhealthyConnectors(), UNHEALTHYCONNECTORS_BINDING);
            protocolMarshaller.marshall(customerConnectorInfo.getTotalConnectors(), TOTALCONNECTORS_BINDING);
            protocolMarshaller.marshall(customerConnectorInfo.getUnknownConnectors(), UNKNOWNCONNECTORS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
.. deprecated:: 2.5.3
        Gets configuration out of environment.

        Returns list of dicts - list of namenode representations

def get_config_from_env(cls):

        core_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'core-site.xml')
        core_configs = cls.read_core_config(core_path)

        hdfs_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'hdfs-site.xml')
        hdfs_configs = cls.read_hdfs_config(hdfs_path)

        if (not core_configs) and (not hdfs_configs):
            raise Exception("No config found in %s nor in %s" % (core_path, hdfs_path))

        configs = {
            'use_trash': hdfs_configs.get('use_trash', core_configs.get('use_trash', False)),
            'use_sasl': core_configs.get('use_sasl', False),
            'hdfs_namenode_principal': hdfs_configs.get('hdfs_namenode_principal', None),
            'namenodes': hdfs_configs.get('namenodes', []) or core_configs.get('namenodes', [])
        }

        return configs

def dad_status_output_dad_status_entries_message(self, **kwargs):

        config = ET.Element("config")
        dad_status = ET.Element("dad_status")
        config = dad_status
        output = ET.SubElement(dad_status, "output")
        dad_status_entries = ET.SubElement(output, "dad-status-entries")
        message = ET.SubElement(dad_status_entries, "message")
        message.text = kwargs.pop('message')

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

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


Question:
Set route and optionally additional parameters for specific DataSource.

@param DataSourceViewInterface $dataSource
@param $route
@param array $additional_parameters

public function setRoute(DataSourceViewInterface $dataSource, $route, array $additional_parameters = [])
    {
        $this->routes[$dataSource->getName()] = $route;
        $this->additional_parameters[$dataSource->getName()] = $additional_parameters;
    }

public function generateRemotingApi() {
        $list = array();
        foreach($this->remotingBundles as $bundle) {
            $bundleRef = new \ReflectionClass($bundle);
            $controllerDir = new Finder();
            $controllerDir->files()->in(dirname($bundleRef->getFileName()).'/Controller/')->name('/.*Controller\.php$/');
            foreach($controllerDir as $controllerFile) {
                $controller = $bundleRef->getNamespaceName() . "\\Controller\\" . substr($controllerFile->getFilename(), 0, -4);
                $controllerRef = new \ReflectionClass($controller);
                foreach ($controllerRef->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
                    /** @var $methodDirectAnnotation Direct */
                    $methodDirectAnnotation = $this->annoReader->getMethodAnnotation($method, 'Tpg\ExtjsBundle\Annotation\Direct');
                    if ($methodDirectAnnotation !== null) {
                        $nameSpace = str_replace("\\", ".", $bundleRef->getNamespaceName());
                        $className = str_replace("Controller", "", $controllerRef->getShortName());
                        $methodName = str_replace("Action", "", $method->getName());
                        $list[$nameSpace][$className][] = array(
                            'name'=>$methodName,
                            'len' => count($method->getParameters())
                        );
                    }
                }
            }
        }
        return $list;
    }

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


Question: Make an edge between two vertices

def make_connection(v1, v2)
      raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex)
      raise "already connected" if is_connected?(v1, v2)
      # Make new edge
      edge = Edge.new(v1, v2)
      # Connect the two using the vertex method "connect"
      v1.connect(v2, edge)
      v2.connect(v1, edge)

      # Add to edge catalog
      @edges << edge
      edge
    end

function getRightEdge(index, cell) {
        return {
          index: index,
          x: editor.dom.getPos(cell).x + cell.offsetWidth
        };
      }

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


Question: Specify order for attributes.

def sort_func(self, key):
        """"""
        if key == self._KEYS.TIME:
            return 'aaa'
        if key == self._KEYS.MODEL:
            return 'zzy'
        if key == self._KEYS.SOURCE:
            return 'zzz'
        return key

public void init(final String name,
			final boolean[] value, final int dim_x, final int dim_y) {
		buildAttributeValueObject(name);
		insert(value, dim_x, dim_y);
    }

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


Question:
@DI\Observe("generate_resource_user_evaluation_file")

@param GenericDataEvent $event

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

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

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

public DriverRestarted getDriverRestarted() {
    final Set<String> expectedEvaluatorIds = new HashSet<>();
    for (final MockAllocatedEvaluator allocatedEvaluator : this.allocatedEvaluators) {
      expectedEvaluatorIds.add(allocatedEvaluator.getId());
    }
    return new DriverRestarted() {
      @Override
      public int getResubmissionAttempts() {
        return restartAttemps;
      }

      @Override
      public StartTime getStartTime() {
        return startTime;
      }

      @Override
      public Set<String> getExpectedEvaluatorIds() {
        return expectedEvaluatorIds;
      }
    };
  }

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


Question:
验证
@param array $fields 需要验证的字段，默认全部
@return bool

public function validate($fields = [])
    {
        if (empty($this->rules())) return true;
        foreach ($this->rules() as $rules) {
            if (is_array($rules[0])) {
                foreach ($rules[0] as $v){
                    if(!empty($fields) && !in_array($v,$fields)) continue;
                    $this->_validate($rules,$v);
                }
            } else {
                if(!empty($fields) && !in_array($rules[0],$fields)) continue;
                $this->_validate($rules,$rules[0]);
            }
        }
        $attributes = $this->attributes();
        if(!empty($this->_validateError) && !empty($attributes)){
            foreach ($this->_validateError as $k=> &$v){
                if(strpos($v,':attribute')!==false){
                    $v = isset($attributes[$k])? str_replace(':attribute',$attributes[$k],$v) : $v;
                }
            }
        }
        return empty($this->_validateError);
    }

public function submit($options = [])
    {
        if (is_string($options)) {
            $options = ['value' => $options];
        }

        if (!Arr::has($options, 'type')) {
            Arr::set($options, 'type', 'submit');
        }

        $input = new Input($this->expression('input'), $options);

        return $input;
    }

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


Question:
Called on every step of the animation

@param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only!

function(render) {
    var self = this;

    //
    // COMPUTE NEXT SCROLL POSITION
    //

    // Add deceleration to scroll position
    var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX;// * self.options.deceleration);
    var scrollTop = self.__scrollTop + self.__decelerationVelocityY;// * self.options.deceleration);

    //
    // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE
    //

    if (!self.options.bouncing) {

      var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft);
      if (scrollLeftFixed !== scrollLeft) {
        scrollLeft = scrollLeftFixed;
        self.__decelerationVelocityX = 0;
      }

      var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop);
      if (scrollTopFixed !== scrollTop) {
        scrollTop = scrollTopFixed;
        self.__decelerationVelocityY = 0;
      }

    }

    //
    // UPDATE SCROLL POSITION
    //

    if (render) {

      self.__publish(scrollLeft, scrollTop, self.__zoomLevel);

    } else {

      self.__scrollLeft = scrollLeft;
      self.__scrollTop = scrollTop;

    }

    //
    // SLOW DOWN
    //

    // Slow down velocity on every iteration
    if (!self.options.paging) {

      // This is the factor applied to every iteration of the animation
      // to slow down the process. This should emulate natural behavior where
      // objects slow down when the initiator of the movement is removed
      var frictionFactor = self.options.deceleration;

      self.__decelerationVelocityX *= frictionFactor;
      self.__decelerationVelocityY *= frictionFactor;

    }

    //
    // BOUNCING SUPPORT
    //

    if (self.options.bouncing) {

      var scrollOutsideX = 0;
      var scrollOutsideY = 0;

      // This configures the amount of change applied to deceleration/acceleration when reaching boundaries
      var penetrationDeceleration = self.options.penetrationDeceleration;
      var penetrationAcceleration = self.options.penetrationAcceleration;

      // Check limits
      if (scrollLeft < self.__minDecelerationScrollLeft) {
        scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft;
      } else if (scrollLeft > self.__maxDecelerationScrollLeft) {
        scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft;
      }

      if (scrollTop < self.__minDecelerationScrollTop) {
        scrollOutsideY = self.__minDecelerationScrollTop - scrollTop;
      } else if (scrollTop > self.__maxDecelerationScrollTop) {
        scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop;
      }

      // Slow down until slow enough, then flip back to snap position
      if (scrollOutsideX !== 0) {
        var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft;
        if (isHeadingOutwardsX) {
          self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration;
        }
        var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating;
        //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds
        if (!isHeadingOutwardsX || isStoppedX) {
          self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration;
        }
      }

      if (scrollOutsideY !== 0) {
        var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop;
        if (isHeadingOutwardsY) {
          self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration;
        }
        var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating;
        //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds
        if (!isHeadingOutwardsY || isStoppedY) {
          self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration;
        }
      }
    }
  }

def transformer_moe_8k():
  """"""
  hparams = transformer_moe_base()

  hparams.batch_size = 8192
  hparams.max_length = 0  # max_length == batch_size
  hparams.eval_drop_long_sequences = True
  hparams.min_length_bucket = 256  # Avoid cyclic problems for big batches

  hparams.default_ff = "sep"
  hparams.hidden_size = 1024

  return hparams

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


Question: // FetchUser will go to Facebook and access basic information about the user.

func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
	sess := session.(*Session)
	user := goth.User{
		AccessToken: sess.AccessToken,
		Provider:    p.Name(),
		ExpiresAt:   sess.ExpiresAt,
	}

	if user.AccessToken == "" {
		// data is not yet retrieved since accessToken is still empty
		return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName)
	}

	// always add appsecretProof to make calls more protected
	// https://github.com/markbates/goth/issues/96
	// https://developers.facebook.com/docs/graph-api/securing-requests
	hash := hmac.New(sha256.New, []byte(p.Secret))
	hash.Write([]byte(sess.AccessToken))
	appsecretProof := hex.EncodeToString(hash.Sum(nil))

	reqUrl := fmt.Sprint(
		endpointProfile,
		p.Fields,
		"&access_token=",
		url.QueryEscape(sess.AccessToken),
		"&appsecret_proof=",
		appsecretProof,
	)
	response, err := p.Client().Get(reqUrl)
	if err != nil {
		return user, err
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode)
	}

	bits, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return user, err
	}

	err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData)
	if err != nil {
		return user, err
	}

	err = userFromReader(bytes.NewReader(bits), &user)
	return user, err
}

func (p *PullRequest) GetHTMLURL() string {
	if p == nil || p.HTMLURL == nil {
		return ""
	}
	return *p.HTMLURL
}

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


Question:
Конфигурирование объекта запроса поиска по элементам.

@param \yii\db\ActiveQuery $activeQuery
@param null $modelClassName
@return $this

public function buildElementsQuery(\yii\db\ActiveQuery $activeQuery)
    {
        $where = [];

        //Нужно учитывать связанные дополнительные данные
        if ($this->enabledElementProperties == Cms::BOOL_Y) {
            $activeQuery->joinWith('cmsContentElementProperties');

            //Нужно учитывать настройки связанные дополнительные данных
            if ($this->enabledElementPropertiesSearchable == Cms::BOOL_Y) {
                $activeQuery->joinWith('cmsContentElementProperties.property');

                $where[] = [
                    'and',
                    ['like', CmsContentElementProperty::tableName() . ".value", '%' . $this->searchQuery . '%', false],
                    //[CmsContentProperty::tableName() . ".searchable" => Cms::BOOL_Y]
                ];
            } else {
                $where[] = [
                    'like',
                    CmsContentElementProperty::tableName() . ".value",
                    '%' . $this->searchQuery . '%',
                    false
                ];
            }
        }

        //Поиск по основному набору полей
        if ($this->searchElementFields) {
            foreach ($this->searchElementFields as $fieldName) {
                $where[] = [
                    'like',
                    CmsContentElement::tableName() . "." . $fieldName,
                    '%' . $this->searchQuery . '%',
                    false
                ];
            }
        }

        if ($where) {
            $where = array_merge(['or'], $where);
            $activeQuery->andWhere($where);
        }

        //Отфильтровать только конкретный тип
        if ($this->searchElementContentIds) {
            $activeQuery->andWhere([
                CmsContentElement::tableName() . ".content_id" => (array)$this->searchElementContentIds
            ]);
        }

        return $this;
    }

protected function process(array $config, ContainerBuilder $container)
    {
        $container->setParameter('qcm_core.website_name', $config['website_name']);
        $container->setParameter('qcm.model.user.class', $config['user_class']);
        $container->setParameter('qcm.configuration', $config['configuration']);
        $container->setParameter('qcm_core.statistics.class', $config['service']['statistics']['class']);
        $container->setParameter('qcm_core.template.class', $config['service']['statistics']['template']);

        $container->setAlias('qcm.configuration', $config['service']['configuration']);
        $container->setAlias('qcm.user_session_configuration', $config['service']['user_session_configuration']);

        return $config;
    }

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


Question:
Registers this relation as a Field in the Model.

@return void

protected function _addRelationFieldInLocalModel() {
        if (!$this->isSingular()) {
            return;
        }

        $column = Garp_Spawn_Relation_Set::getRelationColumn($this->name);
        $fieldParams = array(
            'model' => $this->model,
            'type' => 'numeric',
            'editable' => true,
            'visible' => true,
            'primary' => $this->primary,
            'required' => $this->required,
            'relationAlias' => $this->name,
            'relationType' => $this->type
        );
        if ($this->multilingual && $this->_localModel->isMultilingual()) {
            // The relation is added to the i18n model by Garp_Spawn_Config_Model_I18n
            return;
        }
        $this->_localModel->fields->add('relation', $column, $fieldParams);
    }

public function hydrateSet($key, $element)
    {
        $this->collection->set($key, $element);

        // If _backRefFieldName is set, then the association is bidirectional
        // and we need to set the back reference.
        if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) {
            // Set back reference to owner
            $this->typeClass->reflFields[$this->backRefFieldName]->setValue(
                $element, $this->owner
            );
        }
    }

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


Question:
Save Model

@param string $modelName
@param null   $id
@return string

public function save($modelName, $id = null)
    {
        // Custom page_type
        $this->request->merge([
            'pagetype' => ".blade.php",
        ]);

        return parent::save($modelName, $id);
    }

public function createMarkAction(Request $request, Result $result, User $user)
    {
        $this->assertCanEdit($result);
        $mark = $request->request->get('mark', false);
        $response = new JsonResponse();

        if ($mark !== false) {
            if (!$this->manager->isValidMark($result, $mark)) {
                $response->setData('Mark is not valid');
                $response->setStatusCode(422);
            } else {
                $mark = $this->manager->createMark($result, $user, $mark);
                $response->setData($mark->getId());
            }
        } else {
            $response->setData('Field "mark" is missing');
            $response->setStatusCode(422);
        }

        return $response;
    }

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


Question: // NewSet returns a new Set containing t.

func NewSet(t ...*Term) Set {
	s := newset(len(t))
	for i := range t {
		s.Add(t[i])
	}
	return s
}

public void add(Face vtx) {
        if (head == null) {
            head = vtx;
        } else {
            tail.next = vtx;
        }
        vtx.next = null;
        tail = vtx;
    }

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


Question:
/*
(non-Javadoc)
@see
org.fcrepo.server.security.xacml.pep.rest.filters.RESTFilter#handleRequest(javax.servlet
.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

@Override
    public RequestCtx handleRequest(HttpServletRequest request,
                                    HttpServletResponse response)
            throws IOException, ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("{}/handleRequest!", this.getClass().getName());
        }

        String dsState = request.getParameter("dsState");

        RequestCtx req = null;
        Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>();
        Map<URI, AttributeValue> resAttr;
        try {
            String[] parts = getPathParts(request);
            resAttr = ResourceAttributes.getResources(parts);
            if (dsState != null && !dsState.isEmpty()) {
                resAttr.put(Constants.DATASTREAM.NEW_STATE.getURI(),
                            new StringAttribute(dsState));
            }

            actions
                    .put(Constants.ACTION.ID.getURI(),
                         Constants.ACTION.SET_DATASTREAM_STATE
                                 .getStringAttribute());
            actions.put(Constants.ACTION.API.getURI(),
                        Constants.ACTION.APIM.getStringAttribute());

            // modifying the FeSL policy datastream requires policy management permissions
            String dsID = parts[3];
            if (dsID != null && dsID.equals(FedoraPolicyStore.FESL_POLICY_DATASTREAM)) {
                actions.put(Constants.ACTION.ID.getURI(),
                            Constants.ACTION.MANAGE_POLICIES.getStringAttribute());
            }

            req =
                    getContextHandler().buildRequest(getSubjects(request),
                                                     actions,
                                                     resAttr,
                                                     getEnvironment(request));

            LogUtil.statLog(request.getRemoteUser(),
                            Constants.ACTION.SET_DATASTREAM_STATE.uri,
                            parts[1],
                            dsID);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServletException(e.getMessage(), e);
        }

        return req;
    }

def ajax(cls, url, param={}, method='get'):

        param = urllib.parse.urlencode(param)
        if method.lower() == 'get':
            req = urllib.request.Request(url + '?' + param)
        elif method.lower() == 'post':
            param = param.encode('utf-8')
            req = urllib.request.Request(url, data=param)
        else:
            raise Exception("invalid method '{}' (GET/POST)".format(method))
        rsp = urllib.request.urlopen(req)
        if rsp:
            rsp_json = rsp.read().decode('utf-8')
            rsp_dict = json.loads(rsp_json)
            return rsp_dict
        return None

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


Question:
The combined values from :attr:`forms` and :attr:`files`. Values are
            either strings (form values) or instances of
            :class:`cgi.FieldStorage` (file uploads).

def POST(self):

        post = MultiDict()
        safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
        for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
            if key in self.environ: safe_env[key] = self.environ[key]
        if NCTextIOWrapper:
            fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n')
        else:
            fb = self.body
        data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True)
        for item in data.list or []:
            post[item.name] = item if item.filename else item.value
        return post

public static function GetFileUploadIniNameList () {
		return [
			static::FILE_UPLOADS						=> static::FILE_UPLOADS,
			static::UPLOAD_TMP_DIR						=> static::UPLOAD_TMP_DIR,
			static::UPLOAD_MAX_FILESIZE					=> static::UPLOAD_MAX_FILESIZE,
			static::MAX_FILE_UPLOADS					=> static::MAX_FILE_UPLOADS,
			static::POST_MAX_SIZE						=> static::POST_MAX_SIZE,
			static::MAX_INPUT_NESTING_LEVEL				=> static::MAX_INPUT_NESTING_LEVEL,
			static::MAX_INPUT_TIME						=> static::MAX_INPUT_TIME,
			static::MAX_INPUT_VARS						=> static::MAX_INPUT_VARS,
			static::SESSION_UPLOAD_PROGRESS_ENABLED		=> static::SESSION_UPLOAD_PROGRESS_ENABLED,
			static::SESSION_UPLOAD_PROGRESS_CLEANUP		=> static::SESSION_UPLOAD_PROGRESS_CLEANUP,
			static::SESSION_UPLOAD_PROGRESS_PREFIX		=> static::SESSION_UPLOAD_PROGRESS_PREFIX,
			static::SESSION_UPLOAD_PROGRESS_NAME		=> static::SESSION_UPLOAD_PROGRESS_NAME,
			static::SESSION_UPLOAD_PROGRESS_FREQ		=> static::SESSION_UPLOAD_PROGRESS_FREQ,
			static::SESSION_UPLOAD_PROGRESS_MIN_FREQ	=> static::SESSION_UPLOAD_PROGRESS_MIN_FREQ,
		];
	}

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


Question:
Validate if expression is bool/boolean value

@param string $str

@return bool

@throws CompileErrorException

private function validateBool(string $str) : bool
    {
        $ret = filter_var($str,FILTER_VALIDATE_BOOLEAN);
        if ($ret === null){
            throw new CompileErrorException('invalid boolean value', $this->state);
        }
        return $ret;
    }

def check_data(yaml_data, errors_array)
      valid = check_not_empty?(yaml_data, errors_array)
      valid &&= check_syntax_valid?(yaml_data, errors_array)
      valid &&= check_overlapping_keys?(yaml_data, errors_array)

      valid
    end

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


Question: aggregates a set of functions/objects into a constant part + a dynamic part

function mergeObjArr(arr) {
  var base = _assign3.default.apply(_assign3.default.apply.placeholder, [{}].concat(_toConsumableArray(arr)));
  var styles = (0, _flatten3.default)((0, _compact3.default)((0, _map3.default)(arr, 'styles')));
  if (styles.length > 1) {
    base.styles = styles;
  }
  return base;
}

def _apply_section(self, section, hosts):

        # Add the current group name to each host that this section covers.
        if section['name'] is not None:
            for hostname in self._group_get_hostnames(section['name']):
                hosts[hostname]['groups'].add(section['name'])

        # Apply variables
        func_map = {
            "hosts": self._apply_section_hosts,
            "children": self._apply_section_children,
            "vars": self._apply_section_vars,
        }
        func = func_map[section['type']]
        func(section, hosts)

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


Question:
Returns the distance in bytes between the current position inside of the
edits log and the length of the edits log

public long getLagBytes() {
    try {
      if (inputEditStream != null && inputEditStream.isInProgress()) {
        // for file journals it may happen that we read a segment finalized
        // by primary, but not refreshed by the standby, so length() returns 0
        // hence we take max(-1,lag)
        return Math.max(-1,
            inputEditStream.length() - this.inputEditStream.getPosition());
      }
      return -1;
    } catch (IOException ex) {
      LOG.error("Error getting the lag", ex);
      return -1;
    }
  }

private static function resolveLogLocation(array &$context) {
        if (!key_exists('trace', $context))
            self::generateStackTrace($context);
        $trace = $context['trace'];

        foreach ($trace as $i => $frame) {                  // find the first frame with "file"
            if (isset($frame['file'])) {                    // skip internal PHP functions
                $context['file'] = $frame['file'];
                $context['line'] = $frame['line'];
                break;
            }
        }

        if (!key_exists('file', $context)) {
            $context['file'] = '(unknown)';
            $context['line'] = '(?)';
        }
    }

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


@Override
	public boolean hasNext()
	{
		try
		{

			if(this.resultSet == null)
				return false;
			else if(!this.resultSet.next())
			{
				this.dispose();
				return false;
			}
			return true;
		}
		catch (SQLException e)
		{
			dispose();

			throw new CommunicationException(e.getMessage(),e);
		}

	}

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:
// isAllCaps checks if a string contains all capital letters only. Non-letters
// are not considered.

func isAllCaps(s string) bool {
	for _, r := range s {
		if unicode.IsLetter(r) && !unicode.IsUpper(r) {
			return false
		}
	}
	return true
}

protected function filterAlfanumeric($field, $details, $label, $message) {
        if (!$this->filterString($field, $details, $label, $message)) {
            return false;
        }
        if (ctype_alnum($this->getValue($field))) {
            return true;
        }

        throw new \Exception($message ? $message : $this->translate("$label must be alfanumeric!"));
    }

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


Question: // IsCRDConditionTrue indicates if the condition is present and strictly true.

func IsCRDConditionTrue(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) bool {
	return IsCRDConditionPresentAndEqual(crd, conditionType, ConditionTrue)
}

func (cd ConfigDetails) LookupEnv(key string) (string, bool) {
	v, ok := cd.Environment[key]
	return v, ok
}

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


Question: Utility function to add an event listener

function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,false); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}

func NewPlugin(name string, fn LogFunc) *Plugin {
	return &Plugin{name: name, logFn: fn}
}

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


Question:
Function taking a single name and computing its NYSIIS code.

@param  {string}  name - The name to process.
@return {string}       - The NYSIIS code.

@throws {Error} The function expects the name to be a string.

function nysiis(type, name) {
  if (typeof name !== 'string')
    throw Error('talisman/phonetics/nysiis: the given name is not a string.');

  // Preparing the string
  name = deburr(name)
    .toUpperCase()
    .trim()
    .replace(/[^A-Z]/g, '');

  // Getting the proper patterns
  const patterns = PATTERNS[type];

  // Applying the first substitutions
  for (let i = 0, l = patterns.first.length; i < l; i++) {
    const [match, replacement] = patterns.first[i];

    name = name.replace(match, replacement);
  }

  // Storing the first letter
  const firstLetter = name.charAt(0);

  // Eating the first letter if applying the original algorithm
  if (type === 'original')
    name = name.slice(1);

  // Applying the second substitutions
  for (let i = 0, l = patterns.second.length; i < l; i++) {
    const [match, replacement] = patterns.second[i];

    name = name.replace(match, replacement);
  }

  // Returning the squeezed code
  return firstLetter + squeeze(name);
}

func (c *Call) matches(args []interface{}) error {
	if !c.methodType.IsVariadic() {
		if len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}

		for i, m := range c.args {
			if !m.Matches(args[i]) {
				return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
					c.origin, strconv.Itoa(i), args[i], m)
			}
		}
	} else {
		if len(c.args) < c.methodType.NumIn()-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
				c.origin, len(c.args), c.methodType.NumIn()-1)
		}
		if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}
		if len(args) < len(c.args)-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
				c.origin, len(args), len(c.args)-1)
		}

		for i, m := range c.args {
			if i < c.methodType.NumIn()-1 {
				// Non-variadic args
				if !m.Matches(args[i]) {
					return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
						c.origin, strconv.Itoa(i), args[i], m)
				}
				continue
			}
			// The last arg has a possibility of a variadic argument, so let it branch

			// sample: Foo(a int, b int, c ...int)
			if i < len(c.args) && i < len(args) {
				if m.Matches(args[i]) {
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
					// Got Foo(a, b) want Foo(matcherA, matcherB)
					// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
					continue
				}
			}

			// The number of actual args don't match the number of matchers,
			// or the last matcher is a slice and the last arg is not.
			// If this function still matches it is because the last matcher
			// matches all the remaining arguments or the lack of any.
			// Convert the remaining arguments, if any, into a slice of the
			// expected type.
			vargsType := c.methodType.In(c.methodType.NumIn() - 1)
			vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
			for _, arg := range args[i:] {
				vargs = reflect.Append(vargs, reflect.ValueOf(arg))
			}
			if m.Matches(vargs.Interface()) {
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
				// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
				break
			}
			// Wrong number of matchers or not match. Fail.
			// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
			// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB)
			return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
				c.origin, strconv.Itoa(i), args[i:], c.args[i])

		}
	}

	// Check that all prerequisite calls have been satisfied.
	for _, preReqCall := range c.preReqs {
		if !preReqCall.satisfied() {
			return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
				c.origin, preReqCall, c)
		}
	}

	// Check that the call is not exhausted.
	if c.exhausted() {
		return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
	}

	return nil
}

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


Question:
Changes the Toggle's valueOn, updating facet refinements accordingly.

@param newValue valueOn's new value.
@param newName  an eventual new attribute name.

public void setValueOn(String newValue, @Nullable String newName) {
        if (isChecked()) { // refining on valueOn: facetRefinement needs an update
            searcher.updateFacetRefinement(attribute, valueOn, false)
                    .updateFacetRefinement(newName != null ? newName : attribute, newValue, true)
                    .search();
        }
        this.valueOn = newValue;
        applyEventualNewAttribute(newName);
    }

function (name, value) {
        var self = this, elm = self.getEl(self.ariaTarget);

        if (typeof value === "undefined") {
          return self._aria[name];
        }

        self._aria[name] = value;

        if (self.state.get('rendered')) {
          elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
        }

        return self;
      }

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


Question:
Perform the actual delete query on this model instance.

@return void

protected function runSoftDelete()
    {
        $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());

        $this->{$this->getDeletedAtColumn()} = $time = $this->freshTimestamp();

        $query->update([$this->getDeletedAtColumn() => $this->fromDateTime($time)]);
    }

public function hDel($key, $field) {
        return $this->getHandler($this->judge(__FUNCTION__))->hDel($key, $field);
    }

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


Question: // Set conforms to the TextMapWriter interface.

func (c HTTPHeadersCarrier) Set(key, val string) {
	h := http.Header(c)
	h.Set(key, val)
}

def write_layout(layout = nil, type = nil) # :nodoc:
      tag = 'c:layout'

      if layout
        @writer.tag_elements(tag)  { write_manual_layout(layout, type) }
      else
        @writer.empty_tag(tag)
      end
    end

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


Question:
设置查询字段
@param array $fields 推荐格式：array('id','name','pass')
@return $this

public function fields($fields) {

        if ( is_array($fields) ) {
            $this->fields = '`'.implode("`, `", $fields).'`';
        } else if ( is_string($fields) ) {
            $this->fields = $fields;
        } else {
            $this->fields = '*';
        }
        return $this;
    }

public function register($username, $password)
    {
        $userData = [
            'auth' => [
                'type' => 'm.login.dummy'
            ],
            'bind_email' => false,
            'bind_msisdn' => false,
            'password' => $password,
            'x_show_msisdn' => false
        ];

        if ($username) {
            $userData['username'] = $username;
        }

        $data = $this->matrix()->request('POST', $this->endpoint('register'), $userData, [
            'kind' => 'user'
        ]);
        $this->setData($data);
        return $this->data;
    }

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


Question:
Returns html for displaying a module selection box.<p>

@return html code

public String htmlModules() {

        StringBuffer html = new StringBuffer(1024);
        Iterator<String> itModules = sortModules(getAvailableModules().values()).iterator();
        for (int i = 0; itModules.hasNext(); i++) {
            String moduleName = itModules.next();
            CmsModule module = getAvailableModules().get(moduleName);
            html.append(htmlModule(module, i));
        }
        return html.toString();
    }

public function answerExportAction()
    {
        if ($this->answerExportSnippets) {
            $params = $this->_processParameters($this->answerExportParameters + $this->defaultTokenParameters);

            $this->addSnippets($this->answerExportSnippets, $params);
        }
    }

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


Question: Write a GATT Command without callback - not utf-8.

def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True):
        """"""
        try:
            with self:
                _LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response)
                self._conn.writeCharacteristic(handle, value, withResponse=with_response)
                if timeout:
                    _LOGGER.debug("Waiting for notifications for %s", timeout)
                    self._conn.waitForNotifications(timeout)
        except btle.BTLEException as ex:
            _LOGGER.debug("Got exception from bluepy while making a request: %s", ex)
            raise

public java.lang.String getResult() {
    java.lang.Object ref = result_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      if (bs.isValidUtf8()) {
        result_ = s;
      }
      return s;
    }
  }

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


Question: year=2005, month=11, day=16 => '2005-11-16 00:00:00

def get_datetext(year, month, day):
    """'"""
    input_format = "%Y-%m-%d"
    try:
        datestruct = time.strptime("%i-%i-%i" % (year, month, day),
                                   input_format)
        return strftime(datetext_format, datestruct)
    except:
        return datetext_default

public function render() {

		$ret = '<input ' . $this->getNameProperty();

		switch ($this->type) {

            default:
            case 'text':
            case 'email':
            case 'tel':
            case 'url':
            case 'color':
            case 'password':
                $ret .= ' type="' . htmlspecialchars($this->type) . '" value="' . htmlspecialchars($this->value) . '"';
                break;

            case 'number':
            	$curr = setlocale(LC_NUMERIC, 0);
            	setlocale(LC_NUMERIC, 'en_US');
            	$ret .= ' type="number" value="' . htmlspecialchars($this->value) . '"';
            	setlocale(LC_NUMERIC, $curr);
            	break;

            case 'bool':
                $ret .= ' type="checkbox" value="1"';
                if ($this->value) $ret .= ' checked="checked"';
                break;

            case 'date':
                $ret .= ' type="date" value="' . htmlspecialchars($this->value) . '"';
				break;

			case 'datetime':
				$type = Input::usingCustomDatetimepicker() ? 'datetime' : 'datetime-local';
				$ret .= ' type="' . $type . '" value="' . htmlspecialchars($this->value) . '"';
				break;

			case 'file':
				$ret .= ' type="file"';
				break;

			case 'address':
				$ret .= ' type="text" value="'. htmlspecialchars($this->value) .'" size="50" autocomplete="on" placeholder=""';
				$this->addClass('googlePlacesAutocomplete');
				break;

			case 'hidden':
				$ret .= ' type="hidden" value="' . htmlspecialchars($this->value) . '"';
				break;

		}

		// set min and max value attribute for date and number only
		if (in_array($this->type, ['number','date'])) {

			if ($this->min) {
				$ret .= ' min="' . htmlspecialchars($this->min) . '"';
			}

			if ($this->max) {
				$ret .= ' max="' . htmlspecialchars($this->max) . '"';
			}

		}

		// set minlength attribute
		if ($this->minLength) {
			$ret .= ' minlength="' . htmlspecialchars($this->minLength) . '"';
		}

		// set maxlength attribute
		if ($this->maxLength) {
			$ret .= ' maxlength="' . htmlspecialchars($this->maxLength) . '"';
		}

		// set accept attribute
		if ($this->accept) {
			$ret .= ' accept="' . $this->accept . '"';
		}

		// set step attribute
		if ($this->step) {
			$ret .= ' step="' . htmlspecialchars($this->step) . '"';
		}

		$ret .= $this->processProperties() . ' />';

		return $ret;

	}

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


Question:
Set a predefined template engine. If null then the default engine is used.

@param templateEngine the provided template engine or null to use the default engine

public void setEngineName(final TemplateRendererFactory.TemplateEngine templateEngine) {
		setEngineName(templateEngine == null ? null : templateEngine.getEngineName());
	}

public SQLTemplates.Builder getBuilder(DatabaseMetaData md) throws SQLException {
        String name = md.getDatabaseProductName().toLowerCase();
        if (name.equals("cubrid")) {
            return CUBRIDTemplates.builder();
        } else if (name.equals("apache derby")) {
            return DerbyTemplates.builder();
        } else if (name.startsWith("firebird")) {
            return FirebirdTemplates.builder();
        } else if (name.equals("h2")) {
            return H2Templates.builder();
        } else if (name.equals("hsql")) {
            return HSQLDBTemplates.builder();
        } else if (name.equals("mysql")) {
            return MySQLTemplates.builder();
        } else if (name.equals("oracle")) {
            return OracleTemplates.builder();
        } else if (name.equals("postgresql")) {
            return PostgreSQLTemplates.builder();
        } else if (name.equals("sqlite")) {
            return SQLiteTemplates.builder();
        } else if (name.startsWith("teradata")) {
            return TeradataTemplates.builder();
        } else if (name.equals("microsoft sql server")) {
            switch (md.getDatabaseMajorVersion()) {
                case 13:
                case 12:
                case 11: return SQLServer2012Templates.builder();
                case 10: return SQLServer2008Templates.builder();
                case 9:  return SQLServer2005Templates.builder();
                default: return SQLServerTemplates.builder();
            }
        } else {
            return new SQLTemplates.Builder() {
                @Override
                protected SQLTemplates build(char escape, boolean quote) {
                    return new SQLTemplates(Keywords.DEFAULT, "\"", escape, quote, false);
                }
            };
        }
    }

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


Question:
Get the transition type from one group to another.

@param groupIn The group in.
@param neighborGroups The neighbor groups.
@return The tile transition.

private static TransitionType getTransitionType(String groupIn, Collection<String> neighborGroups)
    {
        final boolean[] bits = new boolean[TransitionType.BITS];
        int i = 0;
        for (final String neighborGroup : neighborGroups)
        {
            bits[i] = !groupIn.equals(neighborGroup);
            i++;
        }
        return TransitionType.from(bits);
    }

public function path($name, array $parameters = [], $relative = false)
    {
        if ($name instanceof TreeNodeInterface) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ContentTreeContext) {
            return $this->router->generate($name->getNode(), $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ElementStructureValue) {
            if ($name->getType() === 'link') {
                $link = $name->getValue();
                if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                    $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                    if ($tree) {
                        $node = $tree->get($link['tid']);

                        return $this->router->generate(
                            $node,
                            $parameters,
                            $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                        );
                    }
                } elseif ($link['type'] === 'external') {
                    return $link['url'];
                } elseif ($link['type'] === 'mailto') {
                    return 'mailto:'.$link['recipient'];
                }
            }
        } elseif (is_array($name) && isset($name['type']) && in_array($name['type'], array('internal', 'intrasiteroot', 'external', 'mailto'))) {
            $link = $name;
            if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                if ($tree) {
                    $node = $tree->get($link['tid']);

                    return $this->router->generate(
                        $node,
                        $parameters,
                        $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                    );
                }
            } elseif ($link['type'] === 'external') {
                return $link['url'];
            } elseif ($link['type'] === 'mailto') {
                return 'mailto:'.$link['recipient'];
            }
        } elseif (strlen($name) && (is_int($name) || (int) $name)) {
            $tree = $this->contentTreeManager->findByTreeId((int) $name);
            if ($tree) {
                $node = $tree->get((int) $name);

                return $this->router->generate($node, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
            }
        } elseif (is_string($name)) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        }

        return '';
    }

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


Question: Get syslog facility from ENV var

def get_syslog_facility():
    """"""
    facil = os.getenv('WALE_SYSLOG_FACILITY', 'user')

    valid_facility = True
    try:
        facility = handlers.SysLogHandler.facility_names[facil.lower()]
    except KeyError:
        valid_facility = False
        facility = handlers.SysLogHandler.LOG_USER

    return facility, valid_facility

def _send(self, subname, value):
        '''
        '''
        name = self._get_name(self.name, subname)
        self.logger.info('%s: %s', name, value)
        return statsd.Client._send(self, {name: '%s|g' % value})

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


Question: Reduce text length for displaying / logging purposes.

def shorten(text):

    if len(text) >= MAX_DISPLAY_LEN:
        text = text[:MAX_DISPLAY_LEN//2]+"..."+text[-MAX_DISPLAY_LEN//2:]
    return text

public function getDescription()
    {
        return vsprintf(
            'The value is expected to be between %f and %f'
            . ' (%f <= x <= %f).',
            [$this->min, $this->max, $this->min, $this->max]
        );
    }

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


Question:
Stores result data inside cache.
@param array $result
@return void

protected function storeCachedInfo($result)
    {
        $cacheItem = $result;
        $cacheItem['mtime'] = $this->object->mtime;

        $cached = $this->getCachedInfo() ?: [];
        $cached[$this->filePath] = $cacheItem;

        Cache::put($this->dataCacheKey, base64_encode(serialize($cached)), 1440);

        self::$cache[$this->filePath] = $result;
    }

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: // WithContext adds the context to the get logout request params

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

def delete(name, remove=False, force=False):
    '''

    '''
    if salt.utils.data.is_true(force):
        log.warning(
            'userdel does not support force-deleting user while user is '
            'logged in'
        )
    cmd = ['userdel']
    if remove:
        cmd.append('-r')
    cmd.append(name)
    return __salt__['cmd.retcode'](cmd, python_shell=False) == 0

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


Question:
Single cont value
        :param elem:
        :param container_type:
        :param params:
        :param field_archiver:
        :return:

async def container_val(self, elem, container_type, params=None):

        if hasattr(container_type, 'boost_serialize'):
            raise ValueError('not supported')

        if self.writing:
            elem_type = params[0] if params else None
            if elem_type is None:
                elem_type = container_type.ELEM_TYPE

            await self.dump_field(elem, elem_type, params[1:] if params else None)

        else:
            raise ValueError('Not supported')

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question:
发送语音消息

@param array $toUsers
@param string $media_id
@param string $title
@param string $description
@return array

public function sendVoiceByOpenid(array $toUsers, $media_id, $title = "", $description = "")
    {
        $ret = array();
        $ret['touser'] = $toUsers;
        $ret['msgtype'] = 'voice';
        $ret['voice']['media_id'] = $media_id;
        $ret['voice']['title'] = $title;
        $ret['voice']['description'] = $description;
        return $this->send($ret);
    }

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

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