Question:
Add expression to the evaluator

@param string $privilegeIdentifier MD5 hash that identifies a privilege
@param string $expression
@return void

public function addExpression(string $privilegeIdentifier, string $expression): void
    {
        $functionName = $this->generateExpressionFunctionName($privilegeIdentifier);
        $wrappedExpression = 'return ' . $expression . ';';
        $this->runtimeExpressionsCache->set($functionName, $wrappedExpression);
        $this->runtimeExpressions[$functionName] = eval($wrappedExpression);
    }

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

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


Question: Rules that apply to individual methods, and attributes

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

public void setInventoryRule(com.google.api.ads.admanager.axis.v201808.InventoryTargeting inventoryRule) {
        this.inventoryRule = inventoryRule;
    }

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


Question:
@param string $body

@return Objects\Voice\Leg
@throws \MessageBird\Exceptions\RequestException
@throws \MessageBird\Exceptions\ServerException

public function processRequest($body)
    {
        $body = @json_decode($body);

        if ($body === null or $body === false) {
            throw new Exceptions\ServerException('Got an invalid JSON response from the server.');
        }

        if (empty($body->errors)) {
            return $this->Object->loadFromArray($body->data[0]);
        }

        $ResponseError = new Common\ResponseError($body);
        throw new Exceptions\RequestException($ResponseError->getErrorString());
    }

public function add() {
		$this->err('Queue Email Task cannot be added via Console.');
		$this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.');
		$this->out('The Data Array should look something like this:');
		$this->out(var_export([
			'settings' => [
				'to' => 'email@example.com',
				'subject' => 'Email Subject',
				'from' => 'system@example.com',
				'template' => 'sometemplate',
			],
			'content' => 'hello world',
		], true));
		$this->out('Alternativly, you can pass the whole EmailLib to directly use it.');
	}

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


Question: Read the file manifest, or create a new one if there isn't one already

def read_local_manifest(self):

        manifest = file_or_default(self.get_full_file_path(self.manifest_file), {
            'format_version' : 2,
            'root'           : '/',
            'have_revision'  : 'root',
            'files'          : {}}, json.loads)

        if 'format_version' not in manifest or manifest['format_version'] < 2:
            raise SystemExit('Please update the client manifest format')
        return manifest

func (f *Flag) UnmarshalFlag(value string) error {
	tokens, err := shlex.Split(value, true /* posix */)
	if err != nil {
		return fmt.Errorf("invalid plugin %q: %v", value, err)
	}

	if len(tokens) < 1 {
		return fmt.Errorf("invalid plugin %q: please provide a name", value)
	}

	f.Name = tokens[0]
	exe := _pluginExecPrefix + f.Name
	path, err := exec.LookPath(exe)
	if err != nil {
		return fmt.Errorf("invalid plugin %q: could not find executable %q: %v", value, exe, err)
	}

	cmd := exec.Command(path, tokens[1:]...)
	cmd.Stderr = os.Stderr // connect stderr so that plugins can log

	f.Command = cmd
	return nil
}

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


Question:
把配置内容持久化成php文件
@param IConfiguration $config
@param string $file

private static function dump2PhpFile(IConfiguration $config,$file)
    {
        $values=$config->getAllValues();
        $values[self::$m_configFilesKey]=$config->getConfigFiles();
        $content=var_export($values, TRUE);
        $content="<?php\r\nreturn\r\n".$content.";";
        file_put_contents($file, $content);
    }

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question:
Create a SyncListItemUpdater to execute update.

@param pathServiceSid The service_sid
@param pathListSid The list_sid
@param pathIndex The index
@return SyncListItemUpdater capable of executing the update

public static SyncListItemUpdater updater(final String pathServiceSid,
                                              final String pathListSid,
                                              final Integer pathIndex) {
        return new SyncListItemUpdater(pathServiceSid, pathListSid, pathIndex);
    }

private function load_command_config_file($file, $prefix) {

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

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

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

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

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

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

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

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


Question:
Verify that no plugin files were modified, need to be deleted or were added.

Only checks JS and CSS files.

@param OutputInterface $output

@return int

public function validatePluginFiles(OutputInterface $output)
    {
        $code = 0;

        // Look for modified files or files that should be deleted.
        $files = Finder::create()->files()->in($this->backupDir)->name('*.js')->name('*.css')->getIterator();
        foreach ($files as $file) {
            $compareFile = $this->plugin->directory.'/'.$file->getRelativePathname();
            if (!file_exists($compareFile)) {
                $output->writeln(sprintf('<error>File no longer generated and likely should be deleted: %s</error>', $file->getRelativePathname()));
                $code = 1;
                continue;
            }

            if (sha1_file($file->getPathname()) !== sha1_file($compareFile)) {
                $output->writeln(sprintf('<error>File is stale and needs to be rebuilt: %s</error>', $file->getRelativePathname()));
                $code = 1;
            }
        }

        // Look for newly generated files.
        $files = Finder::create()->files()->in($this->plugin->directory)->name('*.js')->name('*.css')->getIterator();
        foreach ($files as $file) {
            if (!file_exists($this->backupDir.'/'.$file->getRelativePathname())) {
                $output->writeln(sprintf('<error>File is newly generated and needs to be added: %s</error>', $file->getRelativePathname()));
                $code = 1;
            }
        }

        return $code;
    }

public function hook(OutputInterface $output, array $response)
    {
        $this->printBoolean($output, 'OK', $response['success'], true === $response['success']);
    }

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


Question:
@param \Cake\Event\Event $event

@return void

public function beforeFilter(Event $event) {
		$actions = $this->getConfig('actions');
		if ($actions && !in_array($this->controller->request->param('action'), $actions)) {
			return;
		}

		$model = $this->controller->modelClass;
		if (!isset($this->controller->$model) || $this->controller->$model->hasBehavior('Captcha')) {
			return;
		}
		$this->controller->$model->addBehavior('Captcha.Captcha');
	}

public static <K, V> CacheEvent<K, V> creation(K newKey, V newValue, Cache<K, V> source) {
    return new CreationEvent<>(newKey, newValue, source);
  }

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


Question:
// monitorStreamPair waits for the pair to receive both its error and data
// streams, or for the timeout to expire (whichever happens first), and then
// removes the pair.

func (h *portForwardProxy) monitorStreamPair(p *httpStreamPair, timeout <-chan time.Time) {
	select {
	case <-timeout:
		err := fmt.Errorf("(conn=%v, request=%s) timed out waiting for streams", h.sourceConn, p.requestID)
		p.printError(err.Error())
	case <-p.complete:
		log.Infof("(conn=%v, request=%s) successfully received error and data streams", h.sourceConn, p.requestID)
	}
	h.removeStreamPair(p.requestID)
}

protected void gotoEOR(ArchiveRecord record) throws IOException {
        if (getIn().available() <= 0) {
            return;
        }

        // Remove any trailing LINE_SEPARATOR
        int c = -1;
        while (getIn().available() > 0) {
            if (getIn().markSupported()) {
                getIn().mark(1);
            }
            c = getIn().read();
            if (c != -1) {
                if (c == LINE_SEPARATOR) {
                    continue;
                }
                if (getIn().markSupported()) {
                    // We've overread.  We're probably in next record.  There is
                    // no way of telling for sure. It may be dross at end of
                    // current record. Backup.
                        getIn().reset();
                    break;
                }
                ArchiveRecordHeader h = (getCurrentRecord() != null)?
                    record.getHeader(): null;
                throw new IOException("Read " + (char)c +
                    " when only " + LINE_SEPARATOR + " expected. " +
                    getReaderIdentifier() + ((h != null)?
                        h.getHeaderFields().toString(): ""));
            }
        }
    }

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


Question:
根据包名扫描类，同时使用过滤器过滤

@param pack    包名
@param filters 过滤器组合，不能为null，filter返回true时扫描出的class将被过滤
@return 过滤后的所有Class

public List<Class<?>> scanByFilter(String pack, List<ClassFilter> filters) {
        LOGGER.debug("开始扫描包{}下的所有类的集合", pack);
        // 第一个class类的集合
        List<Class<?>> classes = new ArrayList<>();
        // 获取包的名字 并进行替换
        String packageDirName = pack.replace('.', '/');
        // 定义一个枚举的集合 并进行循环来处理这个目录下的things
        Enumeration<URL> dirs;
        try {
            dirs = ClassUtils.getDefaultClassLoader().getResources(packageDirName);
        } catch (IOException e) {
            LOGGER.error("扫描包{}资源出错", packageDirName);
            throw new RuntimeException(e);
        }
        // 循环迭代下去
        while (dirs.hasMoreElements()) {
            try {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    LOGGER.debug("file类型扫描");
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(),
                        Charset.defaultCharset().name());
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    classes.addAll(findAndAddClassesInPackageByFile(pack, filePath, true));
                } else if ("jar".equals(protocol)) {
                    JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    classes
                        .addAll(findAndAddClassesInPackageByFile(jar, packageDirName, pack, true));
                }
            } catch (Throwable e) {
                LOGGER.debug("扫描{}时出错", pack, e);
            }
        }

        if (!filters.isEmpty()) {
            LOGGER.debug("扫描完毕，扫描出来的Class集合为：{}，发现过滤器，使用过滤器过滤", classes);
            classes = classes.stream().filter(clazz -> filter(clazz, filters))
                .collect(Collectors.toList());
            LOGGER.debug("过滤后的Class为：{}", classes);
        }

        return classes;
    }

func NewREST(optsGetter generic.RESTOptionsGetter) *REST {
	store := &genericregistry.Store{
		NewFunc:                  func() runtime.Object { return &scheduling.PriorityClass{} },
		NewListFunc:              func() runtime.Object { return &scheduling.PriorityClassList{} },
		DefaultQualifiedResource: scheduling.Resource("priorityclasses"),

		CreateStrategy: priorityclass.Strategy,
		UpdateStrategy: priorityclass.Strategy,
		DeleteStrategy: priorityclass.Strategy,

		TableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},
	}
	options := &generic.StoreOptions{RESTOptions: optsGetter}
	if err := store.CompleteWithOptions(options); err != nil {
		panic(err) // TODO: Propagate error up
	}

	return &REST{store}
}

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


Question:
Return a full tsdoc for a type.

@param doc the doc string in the type's DataSchema.
@param deprecation the object listed under the schema's "deprecation" property

@return a fully formed tsdoc for the type.

private static String docComment(String doc, Object deprecation /* nullable */) {
    StringBuilder docStr = new StringBuilder();

    if (doc != null) {
      docStr.append(doc.trim());
    }

    if (deprecation != null) {
      docStr.append("\n\n").append("@deprecated");
      if (deprecation instanceof String) {
        docStr.append("  ").append(((String)deprecation).trim());
      }
    }
    return DocEscaping.stringToDocComment(docStr.toString(), DocCommentStyle.ASTRISK_MARGIN);
  }

function Time(name, ...rest) {
    let h = (methodDescriptor)=>{
        let {key, descriptor} = methodDescriptor;

        let fn = descriptor.value;
        let timer;

        let timeStart;
        let timeEnd;
        if (console != null && typeof console.time === 'function') {
            timeStart = console.time;
            timeEnd = console.timeEnd;
        } else {
            timeStart = ()=>{
                timer = Date.now();
            };

            timeEnd = (name)=>{
                let abstime = Date.now() - timer;

                console.log(name, '：', abstime);
            };
        }

        descriptor.value = function(...args) {
            timeStart(name || key);
            let r = fn.apply(this, args);

            if (r && typeof r.then === 'function') {
                return r.then((succ)=>{
                    timeEnd(name || key);
                    return Promise.resolve(succ);
                }, (fail)=>{
                    timeEnd(name || key);
                    return Promise.reject(fail);
                });
            } else {
                timeEnd(name || key);
                return r;
            }
        };

        return {
            ...methodDescriptor,
            descriptor,
        };
    };

    if (typeof name === 'string') {
        return h;
    } else {
        let args = [name, ...rest];
        name = void(0);
        h(...args);
    }
}

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


Question:
XHR call to url to retrieve JSON
@param {String} url - the url

function(url){
                var self = this;

                ajaGo._xhr.call(this, url, function processRes(res){
                    if(res){
                        try {
                            res = JSON.parse(res);
                        } catch(e){
                            self.trigger('error', e);
                            return null;
                        }
                    }
                    return res;
                });
            }

def get_item_api(self, resource):

        parameters = self.get_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            'operations': [
                {
                    'httpMethod': 'GET',
                    'nickname': 'get%s' % resource.model.__name__,
                    'summary': 'Get %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

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


Question:
/*
The function "openAllAvailableDevices" performs several OpenAll function calls to
build up a list of all the currently available LabJack devices.

function openAllAvailableDevices(bundle) {
        debugSS('in openAllAvailableDevices');
        var defered = q.defer();

        // Save the scan request list to a local variable w/ a shorter name.
        // If enabling extra T5 mock stanning...
        var scanMethods;
        if(LIVE_DEVICE_SCANNING_ENABLED) {
            scanMethods = OPEN_ALL_SCAN_REQUEST_LIST;
        } else {
            scanMethods = OPEN_ALL_SCAN_REQUEST_LIST;
            if(ENABLE_BETA_MOCK_T5_USB_SCAN) {
                scanMethods.push(EXTRA_T5_MOCK_SCAN);
            }
        }

        // Default... aka when the T5 has been added.
        // var scanMethods = OPEN_ALL_SCAN_REQUEST_LIST

        // Determine which scan options to enable given the input options.
        var scanOptions = bundle.options;
        var filteredScanMethods = scanMethods.filter(function(scanMethod) {
            var enableScan = false;
            var smct = scanMethod.connectionType;

            if(smct == driver_const.LJM_CT_USB) {
                if(scanOptions.scanUSB) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_ETHERNET_UDP) {
                if(scanOptions.scanEthernet) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_ETHERNET_TCP) {
                if(scanOptions.scanEthernetTCP) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_WIFI_UDP) {
                if(scanOptions.scanWiFi) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_WIFI_TCP) {
                if(scanOptions.scanWiFiTCP) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_UDP) {
                if(scanOptions.scanWiFi || scanOptions.scanEthernet) {
                    enableScan = true;
                }
            }
            if(smct == driver_const.LJM_CT_TCP) {
                if(scanOptions.scanWiFiTCP || scanOptions.scanEthernetTCP) {
                    enableScan = true;
                }
            }
            return enableScan;
        });

        // Save async vs sync option to a local variable w/ a shorter name.
        var performAsync = PERFORM_SCAN_REQUESTS_ASYNCHRONOUSLY;

        var startTime = new Date();
        function finishedScanning() {
            var stopTime = new Date();
            var duration = stopTime - startTime;
            duration = parseFloat((duration/1000).toFixed(3));

            // We are finished scanning...
            if(DEBUG_OPEN_ALL_SCAN) {
                console.log(
                    'Finished performing all openAll scans. Duration:',
                    duration
                );
            }
            defered.resolve(bundle);
        }

        if(performAsync) {
            async.each(
                filteredScanMethods,
                getPerformOpenAllScanMethod(bundle),
                finishedScanning
            );
        } else {
            async.eachSeries(
                filteredScanMethods,
                getPerformOpenAllScanMethod(bundle),
                finishedScanning
            );
        }
        return defered.promise;
    }

def get_map_location(target_device, fallback_device='cpu'):

    map_location = torch.device(target_device)

    # The user wants to use CUDA but there is no CUDA device
    # available, thus fall back to CPU.
    if map_location.type == 'cuda' and not torch.cuda.is_available():
        warnings.warn(
            'Requested to load data to CUDA but no CUDA devices '
            'are available. Loading on device "{}" instead.'.format(
                fallback_device,
            ), DeviceWarning)
        map_location = torch.device(fallback_device)
    return map_location

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


Question: Find or initialize Cms::Block object

def block
      page.blocks.detect{|b| b.identifier == self.identifier.to_s} ||
      page.blocks.build(:identifier => self.identifier.to_s)
    end

public static function add($cb, $timeout = null, $id = null, $priority = null)
    {
        $obj = new self($cb, $timeout, $id, $priority);
        return $obj->id;
    }

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


Question:
解析配置属性和构造函数

@param array $definition

@return array
<pre>
[$propertyInjections, $constructorInjection]
<pre>

private function resolverPropertiesAndConstructor(array $definition)
    {
        $propertyInjections = [];
        $constructorInjection = null;

        // 循环解析
        foreach ($definition as $name => $property) {
            // 构造函数
            if (is_array($property) && $name === 0) {
                $constructorInjection = $this->resolverConstructor($property);
                continue;
            }

            // 数组属性解析
            if (is_array($property)) {
                $injectProperty = $this->resolverArrayArgs($property);
                $propertyInjection = new PropertyInjection($name, $injectProperty, false);
                $propertyInjections[$name] = $propertyInjection;
                continue;
            }

            // 普通解析
            list($injectProperty, $isRef) = $this->getTransferProperty($property);
            $propertyInjection = new PropertyInjection($name, $injectProperty, (bool)$isRef);
            $propertyInjections[$name] = $propertyInjection;
        }

        return [$propertyInjections, $constructorInjection];
    }

public static <T> Builder<T> wrappedResultsArrayOf(TypeReference<T> type)
    {
        return builder(type).withHeader(StandardStreamCallbacks.RESULTS_HEADER).withFooter(StandardStreamCallbacks.RESULTS_FOOTER);
    }

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


Question:
Performs a validation of the current list of aliases in the widget.<p>

@param structureId the resource's structure id
@param sitePaths the map from ids to alias site paths

@param errorCallback the callback to invoke when the validation finishes

protected void validateFull(
        CmsUUID structureId,
        Map<String, String> sitePaths,
        final AsyncCallback<Map<String, String>> errorCallback) {

        validateAliases(structureId, sitePaths, errorCallback);
    }

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

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

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

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

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

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

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

            return new Rule($name, $validate);

        }

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

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

        }

        throw new InvalidRuleFormatException($definition);
    }

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


Question:
Adds to the encryption info with optional escape for json pointer syntax

@param path Name of the key
@param providerName Value encryption configuration

@InterfaceAudience.Private
    private void addValueEncryptionInfo(String path, String providerName, boolean escape) {
        if (escape) {
            path = path.replaceAll("~", "~0").replaceAll("/", "~1");
        }
        if (this.encryptionPathInfo == null) {
            this.encryptionPathInfo = new HashMap<String, String>();
        }
        this.encryptionPathInfo.put(path, providerName);
    }

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

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


Question:
Get the total mark for all questions in this usage.
@return number The sum of marks of all the question_attempts in this usage.

public function get_total_mark() {
        $mark = 0;
        foreach ($this->questionattempts as $qa) {
            if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) {
                return null;
            }
            $mark += $qa->get_mark();
        }
        return $mark;
    }

def new_select
      quant_list = [ :ALL, :DISTINCT ]
      select_list = [ :ASTERISK, :STRING ]

      select_tok = Tree::Select.new(basic_options)

      # handle an optional set quantifier (ALL or DISTINCT)
      if quant_list.include? peek_token.token
        select_tok.set_quantifier = read_token.token
      end

      # handle a select list (ASTERISK or search terms)
      if select_list.include? peek_token.token

        # read in all search terms from the query:
        while peek_token.token == :STRING
          select_tok.add_search_term(read_token.lexeme)
          read_token if peek_token.token == :COMMA
        end

      else
        raise SyntaxError "No valid select list given (#{error_location})"
      end

      select_tok
    end

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


Question:
registers a test as successful

        :param test: test to register

def addSuccess(self, test):

        super().addSuccess(test)
        self.test_info(test)
        self._call_test_results('addSuccess', test)

public function VerifyTracking($domain, $trackingType = \ElasticEmailEnums\TrackingType::Http) {
        return $this->sendRequest('domain/verifytracking', array(
                    'domain' => $domain,
                    'trackingType' => $trackingType
        ));
    }

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


Question:
// Rate creates a new ugen at a specific rate.
// If rate is an unsupported value this method will cause a runtime panic.
// If the input signal is nil this method will panic.

func (pan PanAz) Rate(rate int8) Input {
	CheckRate(rate)
	if pan.In == nil {
		panic("PanAz requires an input")
	}
	(&pan).defaults()
	return NewInput("PanAz", rate, 0, pan.NumChans, pan.In, pan.Pos, pan.Level, pan.Width, pan.Orientation)

}

def bed_writer(parser, keep, extract, args):
    """"""
    # The output bed and bim file
    bim_fn = args.output + ".bim"
    with open(bim_fn, "w") as bim, PyPlink(args.output, "w") as bed:
        # Getting the samples
        samples = np.array(parser.get_samples(), dtype=str)
        k = _get_sample_select(samples=samples, keep=keep)

        # Writing the FAM file
        with open(args.output + ".fam", "w") as fam:
            for sample in samples[k]:
                print(sample, sample, "0", "0", "0", "-1", sep=" ", file=fam)

        # Getting the data generator
        generator = _get_generator(parser=parser, extract=extract, keep=k,
                                   check_maf=args.maf)

        # The number of markers extracted
        nb_extracted = 0

        for data in generator:
            # Keeping only the required genotypes, changing NaN to -1 and
            # rounding to get a hard call
            genotypes = data.genotypes
            genotypes[np.isnan(genotypes)] = -1
            genotypes = np.round(genotypes, 0)

            # Writing the genotypes and the BIM file
            bed.write_genotypes(genotypes)
            print(
                _PLINK_CHROM_ENCODE.get(str(data.variant.chrom),
                                        data.variant.chrom),
                data.variant.name, "0", data.variant.pos, data.coded,
                data.reference, sep="\t", file=bim,
            )
            nb_extracted += 1

        if nb_extracted == 0:
            logger.warning("No markers matched the extract list")

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


Question:
Converts the first character of each word in the string to uppercase.

@return static Object with all characters of $str being title-cased

public function toTitleCase()
    {
        $str = \mb_convert_case($this->str, \MB_CASE_TITLE, $this->encoding);

        return static::create($str, $this->encoding);
    }

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

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


Question:
Static method to get an MD5Digest from a human-readable string representation
@param md5String
@return a filled out MD5Digest

public static MD5Digest fromString(String md5String) {
    byte[] bytes;
    try {
      bytes = Hex.decodeHex(md5String.toCharArray());
      return new MD5Digest(md5String, bytes);
    } catch (DecoderException e) {
      throw new IllegalArgumentException("Unable to convert md5string", e);
    }
  }

function (digest, iterationCount) {

        var derive = function (password, salt, len) {
            var key, i, tmpBuf;
            if (len > digest.digestLength()) {
                throw "Key length larger than digest length";
            }
            digest.reset();
            digest.update(password);
            digest.update(salt);
            tmpBuf = digest.finalize();
            for (i = 1; i < iterationCount; i++) {
                tmpBuf = digest.digest(tmpBuf);
            }
            return tmpBuf.slice(0, len);
        };

        return {
            deriveKey: function (password, salt, len) {
                return derive(convertToUint8Array(password), convertToUint8Array(salt), len);
            }
        };
    }

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


Question:
Создание анонса материала через модуль anonsCategory.
@param $event
@return bool|Feed|null
@throws \Exception

protected function attachAnonsModule($event)
    {
        if (! $event->request->has('_jsvalidation') && ($event->request->has('anons_merge') || ! empty($event->request->get('anons_description')))) {
            if (! config('larrock.feed.anonsCategory')) {
                MessageLarrock::danger('larrock.feed.anonsCategory не задан. Анонс создан не будет');

                return true;
            }
            /** @var Feed $anons */
            $anons = LarrockFeed::getModel();
            $anons->title = $event->request->get('title');
            $anons->url = 'anons_'.$event->model->id.''.random_int(1, 9999);
            $anons->category = LarrockFeed::getConfig()->settings['anons_category'];
            $anons->user_id = \Auth::id();
            $anons->active = 1;
            $anons->position = LarrockFeed::getModel()->whereCategory(LarrockFeed::getConfig()->settings['anons_category'])->max('position') + 1;

            if ($event->request->has('anons_merge')) {
                $original = LarrockFeed::getModel()->whereId($event->request->get('id_connect'))->first();
                $anons->short = 'full_url.'">'.$event->request->get('title').'';
            } else {
                $anons->short = $event->request->get('anons_description');
            }

            if ($anons->save()) {
                MessageLarrock::success('Анонс добавлен');

                return $anons;
            }
            MessageLarrock::danger('Анонс не добавлен');
        }

        return null;
    }

public function call($method, $parameters)
    {
        try {
            $ch = curl_init($this->base_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encode($method, $parameters));
            curl_setopt($ch, CURLOPT_TIMEOUT, 600);

            $response = curl_exec($ch);

            if ($response === false) {
                $e = new TransportException(curl_error($ch), curl_getinfo($ch, CURLINFO_HTTP_CODE));
                curl_close($ch);

                throw  $e;
            }

            curl_close($ch);

            return $this->decode($response);
        } catch (XmlrpcException $e) {
            throw new TransportException('XML parsing error', 0, $e);
        }
    }

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


Question: // getDiskTagsToDelete loops through the currently set tags and builds a list of tags to be deleted from the specified disk

func (l *LoadBalancer) getLoadBalancerTagsToDelete(currentTags map[string]string) map[string]string {
	tagsToDelete := map[string]string{}
	for k, v := range currentTags {
		if _, ok := l.Tags[k]; !ok {
			tagsToDelete[k] = v
		}
	}

	return tagsToDelete
}

def deleteReplicationMetadata(
        self, pid, nodeId, serialVersion, vendorSpecific=None
    ):

        response = self.deleteReplicationMetadataResponse(
            pid, nodeId, serialVersion, vendorSpecific
        )
        return self._read_boolean_response(response)

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


Question:
Detaches connection from URL
@param  ClientConnection $conn Connection
@param  string $url URL
@return void

public function detachConnFromUrl(ClientConnection $conn, $url)
    {
        if (isset($this->servConnFree[$url])) {
            $this->servConnFree[$url]->detach($conn);
        }
        if (isset($this->servConn[$url])) {
            $this->servConn[$url]->detach($conn);
        }
    }

protected function prepareCurl()
    {
        $this->curl = curl_init();
        $this->complete = Complete::factory(function() {
            if ($this->curl) {
                curl_close($this->curl);
            }
            $this->curl     = null;
            $this->complete = null;
        });

        foreach(self::$curlOptions as $option => $value) {
            curl_setopt($this->curl, $option, $value);
        }
        if ($this->method === HttpMethods::POST) {
            curl_setopt($this->curl, CURLOPT_POST, true);
        }
        if (!empty($this->auth)) {
            curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
                "%s:%s",
                $this->auth["user"],
                $this->auth["pass"]
            ));
        }
    }

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


Question: Procedurally draws the bank billet using FPDF methods

protected function drawBillet()
    {
        // Add document to assignor
        $assignor = $this->title->assignment->assignor;
        $this->fields['assignor']['value'] .= '     '
            . $assignor->person->getFormattedDocument(true);

        // Draw billet
        $dict = $this->dictionary;

        $this->AddPage();

        $this->drawPageHeader();

        $this->billetSetFont('cell_data');
        $this->drawDash($dict['client_receipt']);

        $this->drawBillhead();

        $this->drawTable('demonstrative');

        $this->Ln(4);

        $this->billetSetFont('cell_title');
        $this->drawDash($dict['compensation']);

        $this->SetY($this->GetY() - 3);

        $this->drawTable('instructions');

        $this->SetY($this->GetY() - 3);
        $this->drawBarCode();
    }

public function indexAction(Request $request)
    {
        $this->get('white_october_breadcrumbs')
            ->addItem('Home', $this->get('router')->generate('_homepage'))
        ;

        $chart = $this->get('phospr.account_handler')
            ->getChartOfAccounts()
        ;

        return array(
            'favourite_accounts' => $this->get('phospr.account_handler')
                ->getFavouriteAccountsForUser(
                    $this->get('security.context')
                        ->getToken()
                        ->getUser()
                )
        );
    }

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


Question:
// commitBlock should only ever be invoked with the bw.committingBlock held
// this ensures that the encoded config sequence numbers stay in sync

func (bw *BlockWriter) commitBlock(encodedMetadataValue []byte) {
	// Set the orderer-related metadata field
	if encodedMetadataValue != nil {
		bw.lastBlock.Metadata.Metadata[cb.BlockMetadataIndex_ORDERER] = utils.MarshalOrPanic(&cb.Metadata{Value: encodedMetadataValue})
	}

	bw.addLastConfigSignature(bw.lastBlock)
	bw.addBlockSignature(bw.lastBlock)

	err := bw.support.Append(bw.lastBlock)
	if err != nil {
		logger.Panicf("[channel: %s] Could not append block: %s", bw.support.ChainID(), err)
	}
	logger.Debugf("[channel: %s] Wrote block [%d]", bw.support.ChainID(), bw.lastBlock.GetHeader().Number)
}

def build_computation(self,
                          message: Message,
                          transaction: BaseOrSpoofTransaction) -> BaseComputation:
        """"""
        transaction_context = self.vm_state.get_transaction_context(transaction)
        if message.is_create:
            is_collision = self.vm_state.has_code_or_nonce(
                message.storage_address
            )

            if is_collision:
                # The address of the newly created contract has *somehow* collided
                # with an existing contract address.
                computation = self.vm_state.get_computation(message, transaction_context)
                computation._error = ContractCreationCollision(
                    "Address collision while creating contract: {0}".format(
                        encode_hex(message.storage_address),
                    )
                )
                self.vm_state.logger.debug2(
                    "Address collision while creating contract: %s",
                    encode_hex(message.storage_address),
                )
            else:
                computation = self.vm_state.get_computation(
                    message,
                    transaction_context,
                ).apply_create_message()
        else:
            computation = self.vm_state.get_computation(
                message,
                transaction_context).apply_message()

        return computation

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


Question: Return a list of supported cities in a country/state.

async def cities(self, country: str, state: str) -> list:
        """"""
        data = await self._request(
            'get', 'cities', params={
                'state': state,
                'country': country
            })
        return [d['city'] for d in data['data']]

protected function display_advanced_search_form() {
        print_collapsible_region_start('', 'advancedsearch', get_string('advancedsearchoptions', 'question'),
                                               'question_bank_advanced_search');
        foreach ($this->searchconditions as $searchcondition) {
            echo $searchcondition->display_options_adv($this);
        }
        print_collapsible_region_end();
    }

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


Question: // UnmarshalJSON implements conversion to JSON, supporting an alternate specification of the object as a string

func (o *LaunchTemplate) UnmarshalJSON(data []byte) error {
	var jsonName string
	if err := json.Unmarshal(data, &jsonName); err == nil {
		o.Name = &jsonName
		return nil
	}

	var r realLaunchTemplate
	if err := json.Unmarshal(data, &r); err != nil {
		return err
	}
	*o = LaunchTemplate(r)
	return nil
}

@Nullable
  public static Long parseUnsignedIntObj (@Nullable final String sStr)
  {
    return parseUnsignedIntObj (sStr, DEFAULT_RADIX, null);
  }

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


Question: Execute sql update

int update(Config config, Connection conn, String sql, Object... paras) throws SQLException {
		PreparedStatement pst = conn.prepareStatement(sql);
		config.dialect.fillStatement(pst, paras);
		int result = pst.executeUpdate();
		DbKit.close(pst);
		return result;
	}

public void checkSchemaUpdateOrGrantRights(String schemaName) {

        if (!hasSchemaUpdateOrGrantRights(schemaName)) {
            throw Error.error(ErrorCode.X_42501, schemaName);
        }
    }

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


Question:
// LoadPod loads a Pod Manifest (as prepared by stage0), the runtime data, and
// its associated Application Manifests, under $root/stage1/opt/stage1/$apphash

func LoadPod(root string, uuid *types.UUID, rp *RuntimePod) (*Pod, error) {
	p := &Pod{
		Root:     root,
		UUID:     *uuid,
		Images:   make(map[string]*schema.ImageManifest),
		UidRange: *user.NewBlankUidRange(),
	}

	// Unserialize runtime parameters
	if rp != nil {
		p.RuntimePod = *rp
	} else {
		buf, err := ioutil.ReadFile(filepath.Join(p.Root, RuntimeConfigPath))
		if err != nil {
			return nil, errwrap.Wrap(errors.New("failed reading runtime params"), err)
		}
		if err := json.Unmarshal(buf, &p.RuntimePod); err != nil {
			return nil, errwrap.Wrap(errors.New("failed unmarshalling runtime params"), err)
		}
	}

	pm, err := LoadPodManifest(p.Root)
	if err != nil {
		return nil, err
	}
	p.Manifest = pm

	// ensure volumes names are unique
	volNames := make(map[types.ACName]bool, len(pm.Volumes))
	for _, vol := range pm.Volumes {
		if volNames[vol.Name] {
			return nil, fmt.Errorf("duplicate volume name %q", vol.Name)
		}
		volNames[vol.Name] = true
	}

	for i, app := range p.Manifest.Apps {
		impath := common.ImageManifestPath(p.Root, app.Name)
		buf, err := ioutil.ReadFile(impath)
		if err != nil {
			return nil, errwrap.Wrap(fmt.Errorf("failed reading image manifest %q", impath), err)
		}

		im := &schema.ImageManifest{}
		if err = json.Unmarshal(buf, im); err != nil {
			return nil, errwrap.Wrap(fmt.Errorf("failed unmarshalling image manifest %q", impath), err)
		}

		if _, ok := p.Images[app.Name.String()]; ok {
			return nil, fmt.Errorf("got multiple definitions for app: %v", app.Name)
		}
		if app.App == nil {
			p.Manifest.Apps[i].App = im.App
		}
		p.Images[app.Name.String()] = im
	}

	if err := p.UidRange.Deserialize([]byte(p.PrivateUsers)); err != nil {
		return nil, err
	}

	return p, nil
}

def _get_spark_app_ids(self, running_apps, requests_config, tags):

        spark_apps = {}
        for app_id, (app_name, tracking_url) in iteritems(running_apps):
            response = self._rest_request_to_json(
                tracking_url, SPARK_APPS_PATH, SPARK_SERVICE_CHECK, requests_config, tags
            )

            for app in response:
                app_id = app.get('id')
                app_name = app.get('name')

                if app_id and app_name:
                    spark_apps[app_id] = (app_name, tracking_url)

        return spark_apps

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


Question:
Checks if the class can connect to the Eventbrite API.

Checks if we can connect to the API by calling the user endpoint and
checking the response code. If the response code is 2xx it returns true,
otherwise false.

@return bool

public function canConnect()
    {
        $data = $this->get(self::CURRENT_USER_ENDPOINT);
        if (strpos($data['code'], '2') === 0) {
            return true;
        }
        return false;
    }

async def check_response(response, valid_response_codes):
    """"""
    if response.status == 204:
        return True
    if response.status in valid_response_codes:
        _js = await response.json()
        return _js
    else:
        raise PvApiResponseStatusError(response.status)

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


Question:
Determine if the cached file is up to date with the template.

@param string $cachedFile
@param string $templateFile
@return bool

private function isCacheUpToDate($cachedFile, $templateFile)
    {
        if (!file_exists($cachedFile)) {
            return false;
        }

        $cacheTime = filemtime($cachedFile);
        $templTime = filemtime($templateFile);

        return $cacheTime == $templTime;
    }

def modified?(doc)
      return true if metadata[doc.path]&.[](:forced)
      return true unless File.exist?(site.in_dest_dir(doc.path))
      modified, hash = file_mtime_of(doc.path), metadata[doc.path]
      return modified > hash[:last_modified] if hash && !hash[:dynamic] && hash[:seen_before]
      return hash[:seen_before] = true if hash && !hash[:seen_before]
      return dependencies_modified?(hash) if hash
      add(doc.path).update(seen_before: true)

      true
    end

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


Question: Internal method which process the results from the server.

def _get_setup(self, result):
        """"""
        self.__devices = {}

        if ('setup' not in result.keys() or
                'devices' not in result['setup'].keys()):
            raise Exception(
                "Did not find device definition.")

        for device_data in result['setup']['devices']:
            device = Device(self, device_data)
            self.__devices[device.url] = device

        self.__location = result['setup']['location']
        self.__gateway = result['setup']['gateways']

func statusCodeFromDistributionError(err error) int {
	switch errs := err.(type) {
	case errcode.Errors:
		if len(errs) < 1 {
			return http.StatusInternalServerError
		}
		if _, ok := errs[0].(errcode.ErrorCoder); ok {
			return statusCodeFromDistributionError(errs[0])
		}
	case errcode.ErrorCoder:
		return errs.ErrorCode().Descriptor().HTTPStatusCode
	default:
		if e, ok := err.(causer); ok {
			return statusCodeFromDistributionError(e.Cause())
		}
	}
	return http.StatusInternalServerError
}

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


Question:
Update a table by criteria.

updateTable ( $meta , array $values , $criteria... )
updateTable ( $meta , Query\Update $query , $criteria... )

@return void

public function updateTable($meta, ...$args)
    {
        $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta;
        if (!$meta->canUpdate) {
            throw new Exception("Meta {$meta->id} prohibits update");
        }

        $query = Query\Update::fromParamArgs($args);
        if (!$query->set) {
            throw new \InvalidArgumentException("Query missing 'set' values");
        }

        list ($sql, $params, $setProps, $whereProps) = $query->buildQuery($meta);
        if ($setProps) {
            $params = $this->mapper->formatParams($meta, $setProps, $params);
        }
        if ($whereProps) {
            $params = $this->mapper->formatParams($meta, $whereProps, $params);
        }

        return $this->getConnector()->exec($sql, $params);
    }

public function populateUpdateFields($data) {

        $data['id']                 = $this->request->input('id');
        $data['user_id']            = $this->request->input('user_id');
        $data['priority_id']        = $this->request->input('priority_id');

        if (isset($data['from_email_address'])) {
            $data['from_email_address'] = $this->request->input('from_email_address');
        }

        if (isset($data['from_name'])) {
            $data['from_name']          = $this->request->input('from_name');
        }

        if (isset($data['to_email_address'])) {
            $data['to_email_address']   = $this->request->input('to_email_address');
        }

        if (isset($data['to_name'] )) {
            $data['to_name']            = $this->request->input('to_name');
        }

        $data['priority_id']        = $this->request->input('priority_id');
        $data['archived']           = $this->request->input('archived');
        $data['updated_at']         = Carbon::now();
        $data['updated_by']         = Auth::user()->id;

        return $data;
    }

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


Question: // SetInstanceType sets the InstanceType field's value.

func (s *Server) SetInstanceType(v string) *Server {
	s.InstanceType = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
// AppendSelection appends the elements in the selection to the end of each element
// in the set of matched elements.
//
// This follows the same rules as Selection.Append.

func (s *Selection) AppendSelection(sel *Selection) *Selection {
	return s.AppendNodes(sel.Nodes...)
}

def new_select
      quant_list = [ :ALL, :DISTINCT ]
      select_list = [ :ASTERISK, :STRING ]

      select_tok = Tree::Select.new(basic_options)

      # handle an optional set quantifier (ALL or DISTINCT)
      if quant_list.include? peek_token.token
        select_tok.set_quantifier = read_token.token
      end

      # handle a select list (ASTERISK or search terms)
      if select_list.include? peek_token.token

        # read in all search terms from the query:
        while peek_token.token == :STRING
          select_tok.add_search_term(read_token.lexeme)
          read_token if peek_token.token == :COMMA
        end

      else
        raise SyntaxError "No valid select list given (#{error_location})"
      end

      select_tok
    end

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


Question: Lazily creates and returns the data source for a given root url.

public GenomicsDataSource<Read, ReadGroupSet, Reference> get(String rootUrl) {
    Data<Read, ReadGroupSet, Reference> data = dataSources.get(rootUrl);
    if (data == null) {
      data = new Data<Read, ReadGroupSet, Reference>(new Settings(), null);
      dataSources.put(rootUrl, data);
    }
    if (data.dataSource == null) {
      data.dataSource = makeDataSource(rootUrl, data.settings);
    }
    return data.dataSource;
  }

public function getIterator()
    {
        $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod();
        foreach ($this->getResponseObject()->$resourcesGetMethod() as $element) {
            yield $element;
        }
    }

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


Question: // WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided

func (mn *mn_MN) WeekdayAbbreviated(weekday time.Weekday) string {
	return mn.daysAbbreviated[weekday]
}

public function getLanguageId(string $shortCode): string
    {
        $query = $this->Languages->find('all', [
            'conditions' => ['Languages.code' => $shortCode]
        ]);
        $language = $query->first();

        if (empty($language->id)) {
            throw new InvalidArgumentException("Unsupported language code [$shortCode]");
        }

        return $language->id;
    }

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


Question:
Checks to see if a given index is the child of another index.

@param parentIndex The so-called parent index.
@param childIndex The so-called child index.
@return Is the second index really a child of the first index?

public boolean isChildOf(GeometryIndex parentIndex, GeometryIndex childIndex) {
		return delegate.isChildOf(toDelegate(parentIndex), toDelegate(childIndex));
	}

private static function traverseTree(
        Criterion $node,
        array $children,
        $level
    ) {
        $type = 'n/a';
        $value = 'n/a';

        if ($node->getCaseValue() !== null) {
            $type =
                (new ReflectionClass($node->getCaseValue()))->getShortName();
            if ($node->getCaseValue() instanceof ProductCanonicalCondition) {
                $value = $node->getCaseValue()->getCondition();
            } elseif ($node->getCaseValue() instanceof
                ProductBiddingCategory) {
                $value = sprintf(
                    '%s (%s)',
                    $node->getCaseValue()->getType(),
                    $node->getCaseValue()->getValue()
                );
            } else {
                $value = $node->getCaseValue()->getValue();
            }
        }

        $result = sprintf(
            "%sID: %d, type: %s, value: %s\n",
            str_repeat("  ", $level),
            $node->getId(),
            $type,
            $value
        );
        foreach ($children[$node->getId()] as $childNode) {
            $result .= self::traverseTree($childNode, $children, $level + 1);
        }

        return $result;
    }

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


Question:
Método REST, asociado al verbo http get, sin parametro requerido en la url.

@param  \Fundamentary\Http\Interactions\Request\Request  $request
@return  array

public function index($request) {
        $this->resolveModel();
        $model = Dir::apiModel($this->model);

        if(empty($request->relationalModel))
            return $model::all();
        else {
            $modelRelational = trim(strtolower($request->relationalModel), 's');
            return $model::where([
                $model::EQUALS(
                    $modelRelational.'Id',
                    $request->idRelational
                )
            ]);
        }
    }

private function prepare($request)
    {
        $request->prepare();

        $curlOptions = $this->composeCurlOptions($request->getOptions());

        $method = strtoupper($request->getMethod());
        switch ($method) {
            case 'POST':
                $curlOptions[CURLOPT_POST] = true;
                break;
            default:
                $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
        }

        $content = $request->getContent();

        if ($method === 'HEAD') {
            $curlOptions[CURLOPT_NOBODY] = true;
        } else {
            $curlOptions[CURLOPT_POSTFIELDS] = $content;
        }

        $curlOptions[CURLOPT_RETURNTRANSFER] = true;
        $curlOptions[CURLOPT_URL] = $request->getFullUrl();
        $curlOptions[CURLOPT_HTTPHEADER] = $request->composeHeaderLines();

        if ($request->getOutputFile()) {
            $curlOptions[CURLOPT_FILE] = $request->getOutputFile();
        }

        return $curlOptions;
    }

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


Question: wraps daturi in css class ~~~~~~~~~~~~~~~~~~~~~

function generateCss( filepath, data )
		{
			var filetype = filepath.split( '.' ).pop().toLowerCase();
			var className;
			var template;

      className = options.classPrefix + path.basename( data.path ).split( '.' )[0] + options.classSuffix;
      filetype = options.usePlaceholder ? filetype : filetype + '_no';

      if (options.variables)
      {
      	template = cssTemplates.variables;
      }
      else
      {
      	template = cssTemplates[ filetype ] || cssTemplates.default;
      }

			return template.replace( '{{class}}', className ).replace( '{{data}}', data.data );
		}

public function setCurrentStyle(string $s)
    {
        $this->currentStyle = $s;
        $style              = $this->wt_report->getStyle($s);
        $this->SetFont($style['font'], $style['style'], $style['size']);
    }

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


Question: the path converted to list (eg /foo/bar becomes [foo, bar])

def path_args(self):
        """"""
        self._path_args = []
        path = self.path
        path_args = list(filter(None, path.split('/')))
        return path_args

public function toFilePath(): string
    {
        if (!strlen((string)$this->partition)) {
            return str_replace(':', '/', $this->id);
        }

        $hash = md5($this->partition);
        return trim(sprintf(
            '%s/%s/%s/%s/%s',
            $this->topic,
            substr($hash, 0, 2),
            substr($hash, 2, 2),
            $this->partition,
            $this->subPartition
        ), '/');
    }

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


Question:
Export the page data for the mustache template.

@param renderer_base $output renderer to be used to render the page elements.
@return \stdClass

public function export_for_template(renderer_base $output) {
        global $USER;

        $myparams = [];
        if ($this->isexistinguser && !empty($this->behalfid) && $this->behalfid != $USER->id) {
            $myparams['userid'] = $this->behalfid;
        }
        $data = (object) [
            'pluginbaseurl' => (new moodle_url('/admin/tool/policy'))->out(false),
            'myurl' => (new moodle_url('/admin/tool/policy/index.php', $myparams))->out(false),
            'sesskey' => sesskey(),
        ];

        if (!empty($this->messages)) {
            foreach ($this->messages as $message) {
                switch ($message->type) {
                    case 'error':
                        $data->messages[] = $output->notification($message->text, notification::NOTIFY_ERROR);
                        break;

                    case 'success':
                        $data->messages[] = $output->notification($message->text, notification::NOTIFY_SUCCESS);
                        break;

                    default:
                        $data->messages[] = $output->notification($message->text, notification::NOTIFY_INFO);
                        break;
                }
            }
        }

        // Filter out policies already shown on their own page, keep just policies to be shown here on the consent page.
        $data->policies = array_values(array_filter($this->policies, function ($policy) {
            return $policy->agreementstyle == policy_version::AGREEMENTSTYLE_CONSENTPAGE;
        }));

        // If viewing docs in behalf of other user, get his/her full name and profile link.
        if (!empty($this->behalfuser)) {
            $userfullname = fullname($this->behalfuser, has_capability('moodle/site:viewfullnames', \context_system::instance()) ||
                        has_capability('moodle/site:viewfullnames', \context_user::instance($this->behalfid)));
            $data->behalfuser = html_writer::link(\context_user::instance($this->behalfid)->get_url(), $userfullname);
        }

        // User can cancel accepting policies only if it is a part of signup.
        $data->cancancel = !isloggedin() || isguestuser();

        return $data;
    }

public function display(Form $form) {
        if (!$this->visible){
            return "";
        }
        $this->form = $form;
        if (!isset($this->rowHtmlOptions['class'])) {
            $this->rowHtmlOptions['class'] = $this->rowClass;
        } else {
            $this->rowHtmlOptions['class'] .= ' ' . $this->rowClass;
        }
        if (!is_null($this->getError())){
            $this->rowHtmlOptions['class'] .= ' has-error';
        }
        return Html::get()->tag('div', $this->getContent(), $this->rowHtmlOptions);
    }

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


Question:
<p>
Array of license configuration objects.
</p>

@param licenseConfigurations
Array of license configuration objects.

public void setLicenseConfigurations(java.util.Collection<LicenseConfiguration> licenseConfigurations) {
        if (licenseConfigurations == null) {
            this.licenseConfigurations = null;
            return;
        }

        this.licenseConfigurations = new java.util.ArrayList<LicenseConfiguration>(licenseConfigurations);
    }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question:
Adds a new custom message to current fieldname
@param string $rule
@param array $params

private static function addMessage($rule, $params) {

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

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

		if(false === isset($params[0])) {
			return trigger_error(sprintf('Params passed to %s() are not well formed', __METHOD__), E_USER_ERROR);
		}

		foreach(static :: $fieldnames as $fieldname) {

			if(false === isset(static :: $messages[$fieldname][$rule])) {
				static :: $messages[$fieldname][$rule] = [];
			}

			static :: $messages[$fieldname][$rule] = $params[0];
		}
	}

private function getErrorMessage()
    {
        $directivesMessage = '';
        $domainsMessage = '';

        if (!empty($this->invalidValues['directives'])) {
            $directivesMessage = "The following directives are invalid:\n- ";
            $directivesMessage .= implode("\n- ", $this->invalidValues['directives']);
        }

        if (!empty($this->invalidValues['domain'])) {
            $domainsMessage = "The following domains are invalid:\n- ";
            $domainsMessage .= implode("\n- ", $this->invalidValues['domain']);
        }

        return $domainsMessage . "\n" . $directivesMessage;
    }

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


Question: Render an individual model, if we have one, as part of a composite view (branch / leaf). For example: a treeview.

function(){
    var data = {};
    data = this.serializeData();
    data = this.mixinTemplateHelpers(data);

    var template = this.getTemplate();
    return Marionette.Renderer.render(template, data);
  }

public function getRenderValue()
    {
        $name = $this->getName();
        $defaultValue = $this->getDefaultValue();
        $bean = $this->getBean();
        $value = "";

        if ($this->isCreate()) {

            // Create Page
            // Use Default Value if not null
            if ($this->value !== null) {
                $value = $this->value;
            } else if ($defaultValue !== null) {
                $value = $defaultValue;
            }

        } else {

            // Edit Page
            if ($this->getFieldRelation() == Field::MANY_TO_MANY) {
                // Many to many, Value list
                $keyName = "shared". ucfirst($name) . "List";

                $relatedBeans = $bean->{$keyName};
                $value = [];

                foreach ($relatedBeans as $relatedBean) {
                    $value[$relatedBean->id] = $relatedBean->id;
                }

            } else {

                // Single Value
                if ($this->isOverwriteValue() && $this->value !== null) {
                    // Use the value set by user.
                    $value = $this->value;
                } else {
                    // Use the value from Database
                    $value = $this->getFieldType()->beforeRenderValue($bean->{$name});

                    // Escape the html
                    $value = htmlspecialchars($value);
                }
            }

        }

        return $value;
    }

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


Question:
Get an item from an array using "dot" notation.
If key dont exist, you get a default value back.

@param array           $array
@param string|int|null $key
@param mixed           $default

@return mixed

public static function get(array $array, $key = null, $default = null)
    {
        if ($key === null) {
            return $array;
        }

        if (isset($array[$key])) {
            return static::value($array[$key]);
        }

        foreach (explode('.', (string) $key) as $segment) {
            if (! array_key_exists($segment, $array)) {
                return static::value($default);
            }

            $array = $array[$segment];
        }

        return $array;
    }

public function getParams($include): ParamBag
    {
        $params = isset($this->params[$include]) ? $this->params[$include] : [];
        return new ParamBag($params);
    }

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


Question:
Process fields.

@param array $fields
An array of fields.
@param array $results
The results array on which to append inputs too.

@return array
An array of the field results.

protected function processFields(array $fields, array $results = [])
    {
        $input = $this->input;
        $output = $this->output;
        $helper = $this->helperSet->get('question');

        foreach ($fields as $field) {
            if (!$field instanceof FieldDefinitionInterface) {
                continue;
            }
            $field_name = $field->getName();

            if (isset($results[$field_name])) {
                continue;
            }

            if (!$field instanceof FieldGroup) {
                if ($field->hasCondition()
                    && !$this->fieldConditionMet($field, $results)) {
                    continue;
                }

                if ($field->hasFieldCallback()) {
                    $field->onFieldCallback($results);
                }

                if ($input->isInteractive()) {
                    try {
                        $value = $helper->ask($input, $output, $field->asQuestion());

                        if ($field->hasSubform()) {
                            $subform = new static();
                            $field->onSubformProcess($subform, $value);

                            $results[$field_name] = $subform
                                ->setInput($input)
                                ->setOutput($output)
                                ->setHelperSet($this->helperSet)
                                ->process()
                                ->getResults();
                        } else {
                            $results[$field_name] = $field->formattedValue($value);
                        }
                    } catch (\Exception $e) {
                        throw new FormException(trim($e->getMessage()));
                    }
                }
            } else {
                $groups = [];

                do {
                    $result = $this->processFields(
                        $field->getGroupFields()
                    );
                    $continue = false;

                    if ($field->hasLoopUntil()) {
                        $continue = $field->loopUntil([$result]);
                        if ($continue) {
                            $groups[] = $result;
                        }
                    } else {
                        $groups[] = $result;
                    }
                } while ($continue);

                $results[$field_name] = $groups;
            }
        }

        return $results;
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question:
Creates a new attribute instance from the provided String.

@param str string representation of the attribute
@return attribute instance or {@code null} if provided string is
{@code null}
@throws BOSHException on parse or validation failure

static AttrPause createFromString(final String str)
    throws BOSHException {
        if (str == null) {
            return null;
        } else {
            return new AttrPause(str);
        }
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question:
Adds the having clauses.

@param havingExpression
the having expression
@param aggregationBuilder
the aggregation builder
@param entityMetadata
the entity metadata
@return the aggregation builder

private AggregationBuilder addHavingClause(Expression havingExpression, AggregationBuilder aggregationBuilder,
            EntityMetadata entityMetadata)
    {
        if (havingExpression instanceof ComparisonExpression)
        {
            Expression expression = ((ComparisonExpression) havingExpression).getLeftExpression();
            if (!isAggregationExpression(expression))
            {
                logger.error("Having clause conditions over non metric aggregated are not supported.");
                throw new UnsupportedOperationException(
                        "Currently, Having clause without Metric aggregations are not supported.");
            }

            return checkIfKeyExists(expression.toParsedText()) ? aggregationBuilder
                    .subAggregation(getMetricsAggregation(expression, entityMetadata)) : aggregationBuilder;
        }
        else if (havingExpression instanceof AndExpression)
        {
            AndExpression andExpression = (AndExpression) havingExpression;
            addHavingClause(andExpression.getLeftExpression(), aggregationBuilder, entityMetadata);
            addHavingClause(andExpression.getRightExpression(), aggregationBuilder, entityMetadata);

            return aggregationBuilder;
        }
        else if (havingExpression instanceof OrExpression)
        {
            OrExpression orExpression = (OrExpression) havingExpression;
            addHavingClause(orExpression.getLeftExpression(), aggregationBuilder, entityMetadata);
            addHavingClause(orExpression.getRightExpression(), aggregationBuilder, entityMetadata);

            return aggregationBuilder;
        }
        else
        {
            logger.error(havingExpression + "not supported in having clause.");
            throw new UnsupportedOperationException(havingExpression + "not supported in having clause.");
        }
    }

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question:
Utility method to deal with facade methods that accept
variable length arguments.
@param arguments Argument array.
@param handler handler.
@param callInfo Call info.
@param <T> Type of objects.

private static <T> void foreach(T[] arguments, CallHandler<T> handler, CallInfo callInfo) {
    if (arguments == null || arguments.length == 0) {
      throw new InvalidOperationException("Empty or null array!");
    }
    for (T argument : arguments) {
      handler.action(callInfo, argument);
    }
  }

public function add(string $signal, callable $handler): self
    {
        $this->handlers[$signal] = $handler;

        return $this;
    }

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


Question: Call an API with HTTP GET method and Service credentials.

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

func (s *MarginInfoService) All() ([]MarginInfo, error) {
	req, err := s.client.newAuthenticatedRequest("GET", "margin_infos", nil)
	if err != nil {
		return nil, err
	}

	var v []MarginInfo
	_, err = s.client.do(req, &v)

	return v, err
}

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


Question:
Returns rendered template output. According to debug configuration outputs
debug information.

@param string $templateName template file name
@param object $oObject      object, witch template we wish to output

@return string

public function getTemplateOutput($templateName, $oObject)
    {
        $smarty = $this->getSmarty();
        $debugMode = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('iDebug');

        // assign
        $viewData = $oObject->getViewData();
        if (is_array($viewData)) {
            foreach (array_keys($viewData) as $viewName) {
                // show debug information
                if ($debugMode == 4) {
                    echo("TemplateData[$viewName] : \n");
                    var_export($viewData[$viewName]);
                }
                $smarty->assign($viewName, $viewData[$viewName]);
            }
        }

        return $smarty->fetch($templateName);
    }

private function traceCLI(array $trace, $label) {
            foreach ($trace as $k => $v) {
                $func = $loc = $line = '';
                $argsPresent = isset($v['args']) && !empty($v['args']);

                self::formatTraceLine($v, $func, $loc, $line);

                $this->console->write('<' . $label . 'b>#' . $k . ': </>')
                              ->write('<' . $label . '>' . ($loc ? $loc : '<<unknown file>>') . '</> ')
                              ->write('<' . $label . '>(' . ($line ? 'line ' . $line : 'unknown line') . ')</>')
                              ->write('<' . $label . '> | </>')
                              ->write('<' . $label . '>' . $func . '</>', true);

                if ($argsPresent) {
                    $this->console->write('<' . $label . 'b>Arguments:</>', true);
                    VarDumper::dump($v['args']);
                }

                $this->console->writeln('');
            }
        }

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


Question:
Removes the specified entry point

@param controlPoint The entry point

public synchronized void removeControlPoint(ControlPoint controlPoint) {
        if (controlPoint.decreaseReferenceCount() == 0) {
            ControlPointIdentifier id = new ControlPointIdentifier(controlPoint.getDeployment(), controlPoint.getEntryPoint());
            entryPoints.remove(id);
        }
    }

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

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

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *StartSessionInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "StartSessionInput"}
	if s.Target == nil {
		invalidParams.Add(request.NewErrParamRequired("Target"))
	}
	if s.Target != nil && len(*s.Target) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("Target", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question: // SetCursor changes the cursor

func SetCursor(c Cursor) {
	switch c {
	case CursorNone:
		document.Get("body").Get("style").Set("cursor", "default")
	case CursorHand:
		document.Get("body").Get("style").Set("cursor", "hand")
	}
}

def buffer_prev
      buffer_update_info
      if @_buffer_ctr < 1
        buffer_last
        return
      end
      @_buffer_ctr -= 1 if @_buffer_ctr > 0
      x = @_buffer_ctr
      l = @_buffers[x]
      if l
        populate_buffer_from_filename x
        l = @_buffers[x]
        $log.debug "bp calling set_content with #{l.class} "
        set_content l, @_buffers_conf[x]
        buffer_update_position
      end
    end

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


Question:
Minify javascript prefixes on html event attributes.

@param \ArjanSchouten\HtmlMinifier\MinifyContext $context

@return \ArjanSchouten\HtmlMinifier\MinifyContext

public function process(MinifyContext $context)
    {
        $contents = preg_replace_callback(
            '/'.
                Constants::$htmlEventNamePrefix.Constants::ATTRIBUTE_NAME_REGEX.'   # Match an on{attribute}
                \s*=\s*             # Match equals sign with optional whitespaces around it
                ["\']?              # Match an optional quote
                \s*javascript:      # Match the text "javascript:" which should be removed
            /xis',
            function ($match) {
                return str_replace('javascript:', '', $match[0]);
            }, $context->getContents());

        return $context->setContents($contents);
    }

protected function _singleMeta($name, $content)
    {
        if( stripos($name, 'http:') === 0 )
        {
            $name = ' http-equiv="'.str_ireplace('http:', NULL, $name).'"';
        }
        elseif( stripos($name, 'property:') === 0 )
        {
            $name = ' property="'.str_ireplace('property:', NULL, $name).'"';
        }
        else
        {
            $name = ' name="'.str_ireplace('name:', NULL, $name).'"';
        }

        if( ! empty($content) )
        {
            $content = ' content="'.$content.'"';
        }
        else
        {
            $content = '';
        }

        return '<meta' . $name . $content . ' />' . EOL;
    }

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


Question: // SetHasProposalBlockPart sets the given block part index as known for the peer.

func (ps *PeerState) SetHasProposalBlockPart(height int64, round int, index int) {
	ps.mtx.Lock()
	defer ps.mtx.Unlock()

	if ps.PRS.Height != height || ps.PRS.Round != round {
		return
	}

	ps.PRS.ProposalBlockParts.SetIndex(index, true)
}

func (c *ClientsetSecretStore) createSecret(s *fi.Secret, name string, replace bool) (*kops.Keyset, error) {
	keyset := &kops.Keyset{}
	keyset.Name = NamePrefix + name
	keyset.Spec.Type = kops.SecretTypeSecret

	t := time.Now().UnixNano()
	id := pki.BuildPKISerial(t)

	keyset.Spec.Keys = append(keyset.Spec.Keys, kops.KeysetItem{
		Id:              id.String(),
		PrivateMaterial: s.Data,
	})

	if replace {
		return c.clientset.Keysets(c.namespace).Update(keyset)
	}
	return c.clientset.Keysets(c.namespace).Create(keyset)
}

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


Question:
Add one or more policies to a team

@param  {Object}   params { id, organizationId, policies }
@param  {Function} cb

function addTeamPolicies (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { id, organizationId } = params

      Joi.validate({ id, organizationId, policies: params.policies }, validationRules.addTeamPolicies, function (err) {
        if (err) return cb(Boom.badRequest(err))

        const policies = utils.preparePolicies(params.policies)

        utils.checkPoliciesOrg(db, policies, organizationId, (err) => {
          if (err) return cb(err)

          insertTeamPolicies({ client: db, teamId: id, policies }, (err, res) => {
            if (err) return cb(err)
            teamOps.readTeam({ id, organizationId }, cb)
          })
        })
      })

      return promise
    }

func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}

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


Question: Automatically resizes widget to display at most max_height_items items

def _checkSize(self):
        """"""
        if self._item_height is not None:
            sz = min(self._max_height_items, self.count()) * self._item_height + 5
            sz = max(sz, 20)
            self.setMinimumSize(0, sz)
            self.setMaximumSize(1000000, sz)
            self.resize(self.width(), sz)

def col_widths(self):
        # type: () -> defaultdict

        _widths = defaultdict(int)

        all_rows = [self.headers]
        all_rows.extend(self._rows)

        for row in all_rows:
            for idx, col in enumerate(row):
                _col_l = len(col)
                if _col_l > _widths[idx]:
                    _widths[idx] = _col_l

        return _widths

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


Question:
@param BytesWalker $walker

@return mixed

public function readSignedShort(BytesWalker $walker)
    {
        list(, $v) = unpack('s', $this->correctEndianness($walker->read(2)));

        return $v;
    }

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question: Actually execute the action list.

def execute_action_list(obj, target, kw):
    """"""
    env = obj.get_build_env()
    kw = obj.get_kw(kw)
    status = 0
    for act in obj.get_action_list():
        args = ([], [], env)
        status = act(*args, **kw)
        if isinstance(status, SCons.Errors.BuildError):
            status.executor = obj
            raise status
        elif status:
            msg = "Error %s" % status
            raise SCons.Errors.BuildError(
                errstr=msg,
                node=obj.batches[0].targets,
                executor=obj,
                action=act)
    return status

@Override
    public boolean applyAction(Model m) {
        Mapping map = m.getMapping();
        return map.isRunning(vm) &&
                map.getVMLocation(vm).equals(src) &&
                map.addSleepingVM(vm, dst);
    }

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


Question:
Generates a new UUID

@param DocumentManager $dm       Not used.
@param object          $document Not used.

@return string UUID

@throws Exception

public function generate(DocumentManager $dm, object $document)
    {
        $uuid = $this->generateV4();
        return $this->generateV5($uuid, $this->salt ?: php_uname('n'));
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question:
Check if Access-Control-Request-Headers is valid
Section 5.9

@param array $accessControlRequestHeaders
@return bool

protected function checkAccessControlRequestHeaders(array $accessControlRequestHeaders)
    {
        // Make sure all array elements are strings and not blank
        foreach ($accessControlRequestHeaders as $h) {
            if (!is_string($h) || $h === '') {
                return false;
            }
        }

        return true;
    }

public static function UrlExsist ($url, $timeout = 30, $protocol_version = self::VERSION_1_1) {
		$result = static::HeadRequest($url, $timeout, $protocol_version);
		return isset($result['http']['status']['code']) && $result['http']['status']['code'] !== '404';
	}

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