Question:
Sets the possible sources for submitted token.

Multiple sources can be added using an array. The handler will look for
the token from the sources in the order they appear in the array.

@param Source\TokenSource[] $sources List of token sources.

public function setSources(array $sources)
    {
        $this->sources = array_map(function (Source\TokenSource $source) {
            return $source;
        }, $sources);
    }

public function onKernelController(FilterControllerEvent $event)
    {
        $request = $event->getRequest();

        if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) {
            return;
        }

        $controller = $event->getController();

        if (is_callable($controller) && method_exists($controller, '__invoke')) {
            $controller = [$controller, '__invoke'];
        }

        $this->paramFetcher->setController($controller);
        $attributeName = $this->getAttributeName($controller);
        $request->attributes->set($attributeName, $this->paramFetcher);

        if ($this->setParamsAsAttributes) {
            $params = $this->paramFetcher->all();
            foreach ($params as $name => $param) {
                if ($request->attributes->has($name) && null !== $request->attributes->get($name)) {
                    $msg = sprintf("ParamFetcher parameter conflicts with a path parameter '$name' for route '%s'", $request->attributes->get('_route'));

                    throw new \InvalidArgumentException($msg);
                }

                $request->attributes->set($name, $param);
            }
        }
    }

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


Question:
Verifies not blank text as the utility function.
@param text The text to verify
@param errorMessage The error message
@throws IllegalArgumentException if the requirement fails

public static String checkNotBlank(String text, String errorMessage) {
    if (StringUtils.isBlank(text)) {
      throw new IllegalArgumentException(errorMessage);
    } else {
      return text;
    }
  }

public static String checkNonEmpty(String s, String msg) {
    checkArgument(!s.isEmpty(), msg);
    return s;
  }

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


Question:
Checks if filesInstalled includes scripts in a bin folder.

@param filesInstalled the list of files that are installed
@return true if at least one file is in the bin path

boolean containScript(List<File> filesInstalled) {
        for (File f : filesInstalled) {
            String path = f.getAbsolutePath().toLowerCase();
            if (path.contains("/bin/") || path.contains("\\bin\\")) {
                return true;
            }
        }
        return false;
    }

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

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

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

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

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

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


Question:
Create a new template.

        Args:
            `data`: json data required for creating a template
        Returns:
            Dictionary containing the details of the template with its ID.

def createTemplate(data):

        conn = Qubole.agent()
        return conn.post(Template.rest_entity_path, data)

def render(self, fn=None, prompt=False, **params):

        from getpass import getpass
        expected_keys = self.expected_param_keys()
        compiled_params = Dict(**params)
        for key in expected_keys:
            if key not in compiled_params.keys():
                if prompt==True:
                    if key=='password':
                        compiled_params[key] = getpass("%s: " % key)
                    else:
                        compiled_params[key] = input("%s: " % key)
                        if 'path' in key:
                            compiled_params[key] = compiled_params[key].replace('\\','')
                else:
                    compiled_params[key] = "%%(%s)s" % key

        config = ConfigTemplate(fn=fn, **self)
        config.__dict__['ordered_keys'] = self.__dict__.get('ordered_keys')
        for block in config.keys():
            for key in config[block].keys():
                if type(config[block][key])==str:
                    config[block][key] = config[block][key] % compiled_params
        return config

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


Question:
Plug in the plugins. Lazy plugins will be newed up when needed.

- {gui.LifePlugin} first
- {gui.ConfigPlugin} second
- bonus plugins galore

@TODO: To preserve order, refactor plugins stack from object to array

function() {
		var Plugin, plugins = this.constructor.$plugins;
		this.life = new gui.LifePlugin(this);
		this.config = new gui.ConfigPlugin(this);
		Object.keys(plugins).filter(function(prefix) {
			return prefix !== "life" && prefix !== "config";
		}).sort().forEach(function(prefix) {
			Plugin = plugins[prefix];
			if ((this.life.plugins[prefix] = !Plugin.lazy)) {
				gui.Plugin.$assign(this, prefix, new Plugin(this));
			} else {
				gui.Plugin.$prepare(this, prefix, Plugin);
			}
		}, this);
	}

def intuition(args):
    '''

    '''

    # Use the provided context builder to fill:
    #   - config: General behavior
    #   - strategy: Modules properties
    #   - market: The universe we will trade on
    with setup.Context(args['context']) as context:

        # Backtest or live engine.
        # Registers configuration and setups data client
        simulation = Simulation()

        # Intuition building blocks
        modules = context['config']['modules']

        # Prepare benchmark, timezone, trading calendar
        simulation.configure_environment(
            context['config']['index'][-1],
            context['market'].benchmark,
            context['market'].timezone)

        # Wire togetether modules and initialize them
        simulation.build(args['session'],
                         modules,
                         context['strategy'])

        # Build data generator
        # NOTE How can I use several sources ?
        data = {'universe': context['market'],
                'index': context['config']['index']}
        # Add user settings
        data.update(context['strategy']['data'])
        # Load backtest and / or live module(s)
        if 'backtest' in modules:
            data['backtest'] = utils.intuition_module(modules['backtest'])
        if 'live' in modules:
            data['live'] = utils.intuition_module(modules['live'])

        # Run the simulation and return an intuition.core.analyzes object
        return simulation(datafeed.HybridDataFactory(**data), args['bot'])

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


Question:
// ValidateFlags validates flags and logs a fatal message with all errors if found. Must be called
// after flag.Parse(). This is done by calling Get() on all flag values which implement the
// flag.Getter interface and collecting errors if returned.

func ValidateFlags(fs *flag.FlagSet) MultiFlagError {
	if fs == nil {
		fs = flag.CommandLine
	}
	var flagErrors []*FlagError
	checkGetError := func(f *flag.Flag) {
		if fv, ok := f.Value.(flag.Getter); ok {
			if err, ok := fv.Get().(error); ok && err != nil {
				flagErrors = append(flagErrors, &FlagError{f, err})
			}
		}
	}
	fs.VisitAll(checkGetError)
	if len(flagErrors) > 0 {
		return MultiFlagError(flagErrors)
	}
	return nil
}

public function getCode($file, $comments = true)
    {
        if (!is_string($file) || empty($file)) {
            throw new RuntimeException('Invalid filename provided.');
        }

        if (!is_readable($file)) {
            throw new RuntimeException("Cannot open $file for reading.");
        }

        if ($comments) {
            $content = file_get_contents($file);
        } else {
            $content = php_strip_whitespace($file);
        }

        $parsed = $this->parser->parse($content);
        $stmts = $this->traverser->traverseFile($parsed, $file);
        $pretty = $this->printer->prettyPrint($stmts);

        $pretty = preg_replace(
            '#^(<\?php)?[\s]*(/\*\*?.*?\*/)?[\s]*(declare[\s]*\([\s]*strict_types[\s]*=[\s]*1[\s]*\);)?#s',
            '',
            $pretty
        );

        return $this->getCodeWrappedIntoNamespace($parsed, $pretty);
    }

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


Question:
// MessageControlLoop provides a producer main loop that is sufficient for most
// use cases. ControlLoop will be called in a separate go routine.
// This function will block until a stop signal is received.

func (prod *BufferedProducer) MessageControlLoop(onMessage func(*Message)) {
	prod.setState(PluginStateActive)
	go prod.ControlLoop()
	prod.messageLoop(onMessage)
}

func (s BlockTrigger) Store(bd *BlockData, _ *wire.MsgBlock) error {
	s.Saver(bd.Header.Hash, bd.Header.Height)
	return nil
}

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


Question: Restrict visiblity of the admin bar

public function restrictAdminBarVisibility()
    {
        // Don't go further if not logged in or within admin panel
        if (is_admin() || !is_user_logged_in())
        {
            return;
        }

        $data = $this->getData();

        // Don't go further if no setting
        if ( !isset($data['admin_bar']) || empty($data['admin_bar']))
        {
            return;
        }

        $access = $data['admin_bar'];

        // Is current user's role within our access roles?
        $user = wp_get_current_user();
        $role = $user->roles;
        $role = (count($role) > 0) ? $role[0] : '';
        $isUserIncluded = in_array($role, $access['roles']);

        // Hide admin bar if required
        if (($access['mode'] == 'show' && !$isUserIncluded)
            || ($access['mode'] == 'hide' && $isUserIncluded)
        )
        {
            show_admin_bar(false);
        }
    }

def init_with_context(self, context):

        items = self._visible_models(context['request'])
        for model, perms in items:
            if not (perms['change'] or perms.get('view', False)):
                continue
            title = model._meta.verbose_name_plural
            url = self._get_admin_change_url(model, context)
            item = MenuItem(title=title, url=url)
            self.children.append(item)

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


Question: Idempotent non-blocking connection attempt to the given node id.

def _maybe_connect(self, node_id):
        """"""
        with self._lock:
            conn = self._conns.get(node_id)

            if conn is None:
                broker = self.cluster.broker_metadata(node_id)
                assert broker, 'Broker id %s not in current metadata' % (node_id,)

                log.debug("Initiating connection to node %s at %s:%s",
                          node_id, broker.host, broker.port)
                host, port, afi = get_ip_port_afi(broker.host)
                cb = WeakMethod(self._conn_state_change)
                conn = BrokerConnection(host, broker.port, afi,
                                        state_change_callback=cb,
                                        node_id=node_id,
                                        **self.config)
                self._conns[node_id] = conn

            # Check if existing connection should be recreated because host/port changed
            elif self._should_recycle_connection(conn):
                self._conns.pop(node_id)
                return False

            elif conn.connected():
                return True

            conn.connect()
            return conn.connected()

private Set<String> findReachableNodes(CmsAppCategoryNode rootNode, HashSet<String> reachableNodes) {

        reachableNodes.add(rootNode.getCategory().getId());
        for (CmsAppCategoryNode child : rootNode.getChildren()) {
            findReachableNodes(child, reachableNodes);
        }
        return reachableNodes;
    }

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


Question:
// NewDefaultKama creates a Kaufman Adaptive Moving Average Indicator (Kama) for online usage with default parameters
//	- timePeriod: 25

func NewDefaultKama() (indicator *Kama, err error) {
	timePeriod := 25
	return NewKama(timePeriod, gotrade.UseClosePrice)
}

def message(
    *tokens: Token,
    end: str = "\n",
    sep: str = " ",
    fileobj: FileObj = sys.stdout,
    update_title: bool = False
) -> None:

    if using_colorama():
        global _INITIALIZED
        if not _INITIALIZED:
            colorama.init()
            _INITIALIZED = True
    with_color, without_color = process_tokens(tokens, end=end, sep=sep)
    if CONFIG["record"]:
        _MESSAGES.append(without_color)
    if update_title and with_color:
        write_title_string(without_color, fileobj)
    to_write = with_color if config_color(fileobj) else without_color
    write_and_flush(fileobj, to_write)

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


Question:
二维码登陆验证

@return status:
>=400: invaild code; 408: not auth and wait, 400,401: not valid or expired
201: just scaned but not confirm
200: confirm then you can get user info

public function verify_code() {
		if (!$this->_logincode) return false;
		$t = time().strval(mt_rand(100,999));

			$url = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?uuid='.$this->_logincode.'&tip=0&_='.$t;
			$send_snoopy = new Snoopy;
			$send_snoopy->referer = "https://wx.qq.com/";
			$send_snoopy->fetch($url);
			$result = $send_snoopy->results;
			$this->log('step1:'.$result);
			if ($result) {
				preg_match("/window\.code=(\d+)/",$result,$matches);
				if(count($matches)>1) {
					$status = intval($matches[1]);
					if ($status==201) $_SESSION['login_step'] = 1;
					if ($status==200) {
						preg_match("/ticket=([0-9a-z-_]+)&lang=zh_CN&scan=(\d+)/",$result,$matches);
						preg_match("/window.redirect_uri=\"([^\"]+)\"/",$result,$matcheurl);
						$this->log('step2:'.print_r($matches,true));
						if (count($matcheurl)>1) {
							$ticket = $matches[1];
							$scan = $matches[2];
							//$loginurl = 'https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket='.$ticket.'&lang=zh_CN&scan='.$scan.'&fun=new';
							$loginurl = str_replace("wx.qq.com", "wx2.qq.com", $matcheurl[1]).'&fun=old';
							$urlpart = parse_url($loginurl);
							$send_snoopy = new Snoopy;
							$send_snoopy->referer = "https://{$urlpart['host']}/cgi-bin/mmwebwx-bin/webwxindex?t=chat";
							$send_snoopy->fetch($loginurl);
							$result = $send_snoopy->results;
							$xml = simplexml_load_string($result);
							if ($xml->ret=="0") $this->skey = $xml->skey;
							foreach ($send_snoopy->headers as $key => $value) {
								$value = trim($value);
								if(strpos($value,'Set-Cookie: ') !== false){
									$tmp = str_replace("Set-Cookie: ","",$value);
									$tmparray = explode(';', $tmp);
									$item = trim($tmparray[0]);
									$cookie.=$item.';';
								}
							}
							$cookie .="Domain=.qq.com;";
							$this->cookie = $cookie;
							$this->log('step3:'.$loginurl.';cookie:'.$cookie.';respond:'.$result);

							$this->saveCookie($this->_cookiename,$this->cookie);
						}
					}
					return $status;
				}
			}
		return false;
	}

private void parse(byte[] timestampTokenInfo) throws IOException {

        DerValue tstInfo = new DerValue(timestampTokenInfo);
        if (tstInfo.tag != DerValue.tag_Sequence) {
            throw new IOException("Bad encoding for timestamp token info");
        }
        // Parse version
        version = tstInfo.data.getInteger();

        // Parse policy
        policy = tstInfo.data.getOID();

        // Parse messageImprint
        DerValue messageImprint = tstInfo.data.getDerValue();
        hashAlgorithm = AlgorithmId.parse(messageImprint.data.getDerValue());
        hashedMessage = messageImprint.data.getOctetString();

        // Parse serialNumber
        serialNumber = tstInfo.data.getBigInteger();

        // Parse genTime
        genTime = tstInfo.data.getGeneralizedTime();

        // Parse optional elements, if present
        while (tstInfo.data.available() > 0) {
            DerValue d = tstInfo.data.getDerValue();
            if (d.tag == DerValue.tag_Integer) {    // must be the nonce
                nonce = d.getBigInteger();
                break;
            }

            // Additional fields:
            // Parse accuracy
            // Parse ordering
            // Parse tsa
            // Parse extensions
        }
    }

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


Question:
Twig initialization that sets the twig loader chain, then the environment, then extensions
and also the base set of twig vars

public function init()
    {
        if (null === $this->twig) {
            /** @var Config $config */
            $config = $this->grav['config'];
            /** @var UniformResourceLocator $locator */
            $locator = $this->grav['locator'];
            /** @var Language $language */
            $language = $this->grav['language'];

            $active_language = $language->getActive();

            // handle language templates if available
            if ($language->enabled()) {
                $lang_templates = $locator->findResource('theme://templates/' . ($active_language ? $active_language : $language->getDefault()));
                if ($lang_templates) {
                    $this->twig_paths[] = $lang_templates;
                }
            }

            $this->twig_paths = array_merge($this->twig_paths, $locator->findResources('theme://templates'));

            $this->grav->fireEvent('onTwigTemplatePaths');

            // Add Grav core templates location
            $core_templates = array_merge($locator->findResources('system://templates'), $locator->findResources('system://templates/testing'));
            $this->twig_paths = array_merge($this->twig_paths, $core_templates);

            $this->loader = new \Twig_Loader_Filesystem($this->twig_paths);

            // Register all other prefixes as namespaces in twig
            foreach ($locator->getPaths('theme') as $prefix => $_) {
                if ($prefix === '') {
                    continue;
                }

                $twig_paths = [];

                // handle language templates if available
                if ($language->enabled()) {
                    $lang_templates = $locator->findResource('theme://'.$prefix.'templates/' . ($active_language ? $active_language : $language->getDefault()));
                    if ($lang_templates) {
                        $twig_paths[] = $lang_templates;
                    }
                }

                $twig_paths = array_merge($twig_paths, $locator->findResources('theme://'.$prefix.'templates'));

                $namespace = trim($prefix, '/');
                $this->loader->setPaths($twig_paths, $namespace);
            }

            $this->grav->fireEvent('onTwigLoader');

            $this->loaderArray = new \Twig_Loader_Array([]);
            $loader_chain = new \Twig_Loader_Chain([$this->loaderArray, $this->loader]);

            $params = $config->get('system.twig');
            if (!empty($params['cache'])) {
                $cachePath = $locator->findResource('cache://twig', true, true);
                $params['cache'] = new \Twig_Cache_Filesystem($cachePath, \Twig_Cache_Filesystem::FORCE_BYTECODE_INVALIDATION);
            }

            if (!$config->get('system.strict_mode.twig_compat', true)) {
                // Force autoescape on for all files if in strict mode.
                $params['autoescape'] = 'html';
            } elseif (!empty($this->autoescape)) {
                $params['autoescape'] = $this->autoescape ? 'html' : false;
            }

            if (empty($params['autoescape'])) {
                user_error('Grav 2.0 will have Twig auto-escaping forced on (can be emulated by turning off \'system.strict_mode.twig_compat\' setting in your configuration)', E_USER_DEPRECATED);
            }

            $this->twig = new TwigEnvironment($loader_chain, $params);

            if ($config->get('system.twig.undefined_functions')) {
                $this->twig->registerUndefinedFunctionCallback(function ($name) {
                    if (function_exists($name)) {
                        return new \Twig_SimpleFunction($name, $name);
                    }

                    return new \Twig_SimpleFunction($name, function () {
                    });
                });
            }

            if ($config->get('system.twig.undefined_filters')) {
                $this->twig->registerUndefinedFilterCallback(function ($name) {
                    if (function_exists($name)) {
                        return new \Twig_SimpleFilter($name, $name);
                    }

                    return new \Twig_SimpleFilter($name, function () {
                    });
                });
            }

            $this->grav->fireEvent('onTwigInitialized');

            // set default date format if set in config
            if ($config->get('system.pages.dateformat.long')) {
                /** @var \Twig_Extension_Core $extension */
                $extension = $this->twig->getExtension('Twig_Extension_Core');
                $extension->setDateFormat($config->get('system.pages.dateformat.long'));
            }
            // enable the debug extension if required
            if ($config->get('system.twig.debug')) {
                $this->twig->addExtension(new \Twig_Extension_Debug());
            }
            $this->twig->addExtension(new TwigExtension());
            $this->twig->addExtension(new DeferredExtension());

            $this->grav->fireEvent('onTwigExtensions');

            /** @var Pages $pages */
            $pages = $this->grav['pages'];

            // Set some standard variables for twig
            $this->twig_vars += [
                    'config'            => $config,
                    'system'            => $config->get('system'),
                    'theme'             => $config->get('theme'),
                    'site'              => $config->get('site'),
                    'uri'               => $this->grav['uri'],
                    'assets'            => $this->grav['assets'],
                    'taxonomy'          => $this->grav['taxonomy'],
                    'browser'           => $this->grav['browser'],
                    'base_dir'          => rtrim(ROOT_DIR, '/'),
                    'home_url'          => $pages->homeUrl($active_language),
                    'base_url'          => $pages->baseUrl($active_language),
                    'base_url_absolute' => $pages->baseUrl($active_language, true),
                    'base_url_relative' => $pages->baseUrl($active_language, false),
                    'base_url_simple'   => $this->grav['base_url'],
                    'theme_dir'         => $locator->findResource('theme://'),
                    'theme_url'         => $this->grav['base_url'] . '/' . $locator->findResource('theme://', false),
                    'html_lang'         => $this->grav['language']->getActive() ?: $config->get('site.default_lang', 'en'),
                    'language_codes'    => new LanguageCodes,
                ];
        }

        return $this;
    }

protected function configuration($name)
	{
		$name = $name ?: $this->getDefaultConnection();

		// To get the database connection configuration, we will just pull each of the
		// connection configurations and get the configurations for the given name.
		// If the configuration doesn't exist, we'll throw an exception and bail.
		$connections = $this->prop['database.connections'];
		if (is_null($config = Arr::get($connections, $name)))
		{
			throw new InvalidArgumentException("Database [$name] not configured.");
		}

		return $config;
	}

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


Question: // SetChangeToken sets the ChangeToken field's value.

func (s *UpdateRuleInput) SetChangeToken(v string) *UpdateRuleInput {
	s.ChangeToken = &v
	return s
}

def _get_token_from_query_string(self, request, refresh_token):

        if refresh_token:
            query_string_token_name_key = "query_string_refresh_token_name"
        else:
            query_string_token_name_key = "query_string_access_token_name"
        query_string_token_name = getattr(
            self.config, query_string_token_name_key
        )
        return request.args.get(query_string_token_name(), None)

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


Question:
Returns the blocked word.

@param string $word

@return string

private function blockWord($word)
    {
        if ($this->strictClean) {
            return str_repeat($this->blocker[0], strlen($word));
        }

        return $this->blocker;
    }

function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

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


Question:
Generate serialize on jackson.

@param context
the context
@param entity
the entity

private static void generateSerializeOnJackson(BindTypeContext context, BindEntity entity) {
		// @formatter:off
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("serializeOnJackson").addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC)
				// .addParameter(typeName(AbstractJacksonContext.class),
				// "context")
				.addParameter(typeName(entity.getElement()), "object")
				.addParameter(typeName(JsonGenerator.class), "jacksonSerializer").returns(Integer.TYPE)
				.addException(Exception.class);
		// @formatter:on

		// methodBuilder.beginControlFlow("try");
		// methodBuilder.addStatement("$T jacksonSerializer =
		// wrapper.jacksonGenerator", className(JsonGenerator.class));
		methodBuilder.addStatement("jacksonSerializer.writeStartObject()");
		methodBuilder.addStatement("int fieldCount=0");

		BindTransform bindTransform;

		methodBuilder.addCode("\n");

		// fields
		methodBuilder.addCode("// Serialized Field:\n\n");
		for (BindProperty item : entity.getCollection()) {
			bindTransform = BindTransformer.lookup(item);

			methodBuilder.addCode("// field $L (mapped with $S)\n", item.getName(), item.label);
			bindTransform.generateSerializeOnJackson(context, methodBuilder, "jacksonSerializer",
					item.getPropertyType().getTypeName(), "object", item);
			methodBuilder.addCode("\n");
		}

		methodBuilder.addStatement("jacksonSerializer.writeEndObject()");
		methodBuilder.addStatement("return fieldCount");

		// methodBuilder.nextControlFlow("catch($T e)",
		// typeName(Exception.class));
		// methodBuilder.addStatement("e.printStackTrace()");
		// methodBuilder.addStatement("throw (new $T(e))",
		// typeName(KriptonRuntimeException.class));
		// methodBuilder.endControlFlow();

		context.builder.addMethod(methodBuilder.build());
	}

public function handleEncode(EncodeValueEvent $event)
    {
        $definition = $event->getValue();
        if (!$definition instanceof Definition) {
            return;
        }

        $type   = $definition->getType();
        $method = 'encode' . $this->convertTypeToMethod($type);

        if (method_exists($this, $method)) {
            $buffer = $this->$method($definition, $event->getEncoder(), $event->getJsonFlags());

            if ($buffer) {
                $event->addLine($buffer);
                $this->handleMethodCalls($definition, $event->getEncoder(), $event);
            }

            $event->setSuccessful();
        }
    }

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


Question: The function used to ran the schedule job, and setTimeout for next running job

function excuteJob(){
  let job = peekNextJob();
  let nextJob;

  while(!!job && (job.excuteTime()-Date.now())<accuracy){
    job.run();
    queue.pop();

    let nextTime = job.nextTime();

    if(nextTime === null){
      delete map[job.id];
    }else{
      queue.offer({id:job.id, time: nextTime});
    }
    job = peekNextJob();
  }

  //If all the job have been canceled
  if(!job)
    return;

  //Run next schedule
  setTimer(job);
}

func Report(reporters []metrics.Reporter, period time.Duration) {
	for {
		time.Sleep(period)

		workerStats := workers.GetStats()
		for _, r := range reporters {
			reportJobsRetry(r, workerStats.Retries)
			reportQueueSizes(r, workerStats.Enqueued)
			reportJobsTotal(r, workerStats.Failed, workerStats.Processed)
		}
	}
}

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


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

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

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

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

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


Question:
Retrieve an array of linkbase role types across all taxonomies

@return array

public function getAllLinkbaseRoleTypes()
	{
		// Gather all role types
		return array_reduce( $this->context->importedSchemas, function( $carry, /** @var XBRL $taxonomy */ &$taxonomy )
		{
			$lrts = $taxonomy->getLinkbaseRoleTypes();

			foreach ( $lrts as $linkbase => $definition )
			{
				if ( isset( $carry[ $linkbase ] ) )
				{
					$carry = array_merge( $carry[ $linkbase ], $definition );
				}
				else
				{
					$carry[ $linkbase ] = $definition;
				}
			}

			return $carry;

		}, array() );
	}

public function applyRelationSorts(string $relationName, string $alias, Builder $query)
    {
        foreach ($this->getRelationSorts($relationName) as $sorts) {
            $sorts->apply($query, $alias);
        }
    }

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


Question: Get the last SQL string for this statement type

public String getLastSQLStatement(int iType)
    {
        switch (iType)
        {
        case DBConstants.SQL_UPDATE_TYPE:
        case DBConstants.SQL_INSERT_TABLE_TYPE:
        case DBConstants.SQL_DELETE_TYPE:
            return m_strLastSQL;
        case DBConstants.SQL_AUTOSEQUENCE_TYPE:
        case DBConstants.SQL_SEEK_TYPE:
            if (!SHARE_STATEMENTS)
                return m_strStmtLastSeekSQL;
        case DBConstants.SQL_SELECT_TYPE:
        case DBConstants.SQL_CREATE_TYPE:
        default:
            return m_strStmtLastSQL;
        }
    }

def write_remaining(self):

        if not self.results:
            return
        with db.execution_context():
            with db.atomic():
                Result.insert_many(self.results).execute()
        del self.results[:]

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


Question:
Путь (хлебные крошки)

@param string $type  images|files
@param string $path
@return string  html

function DirPath($type, $path = '')
    {

        if (!empty($path))
        {
            $path = explode('[\\/]', str_replace($this->dir[$type], '', realpath($path)));
            $path = array_filter($path);
        }

        $ret = '

';
        $i = 0;
        $addPath = '';
        if (is_array($path))
        {
            foreach ($path as $v)
            {
                $i++;
                $addPath .= '/' . $v;
                if (sizeof($path) == $i)
                {
                    $ret .= '

' . $v . '

';
                }
                else
                {
                    $ret .= '

' . $v . '

';
                }
            }
        }

        return $ret;
    }

def htmlHelp(self, helpString=None, title=None, istask=False, tag=None):

        # Check the help string.  If it turns out to be a URL, launch that,
        # if not, dump it to a quick and dirty tmp html file to make it
        # presentable, and pass that file name as the URL.
        if not helpString:
            helpString = self.getHelpString(self.pkgName+'.'+self.taskName)
        if not title:
            title = self.taskName
        lwr = helpString.lower()
        if lwr.startswith("http:") or lwr.startswith("https:") or \
           lwr.startswith("file:"):
            url = helpString
            if tag and url.find('#') < 0:
                url += '#'+tag
#           print('LAUNCHING: '+url) # DBG
            irafutils.launchBrowser(url, subj=title)
        else:
            # Write it to a temp HTML file to display
            (fd, fname) = tempfile.mkstemp(suffix='.html', prefix='editpar_')
            os.close(fd)
            f = open(fname, 'w')
            if istask and self._knowTaskHelpIsHtml:
                f.write(helpString)
            else:
                f.write('<title>'+title+'</title>\n')
                f.write('
'+title+'
\n')
                f.write('
\n'+helpString+'\n
')
            f.close()
            irafutils.launchBrowser("file://"+fname, subj=title)

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


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

@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType)
	{
		switch (featureID)
		{
			case XAnnotationsPackage.XANNOTATION_ELEMENT_VALUE_PAIR__VALUE:
				return getValue();
			case XAnnotationsPackage.XANNOTATION_ELEMENT_VALUE_PAIR__ELEMENT:
				if (resolve) return getElement();
				return basicGetElement();
		}
		return super.eGet(featureID, resolve, coreType);
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question: Sets the global description if any

def _set_desc(self):
        """"""
        # TODO: manage different in/out styles
        if self.docs['in']['desc']:
            self.docs['out']['desc'] = self.docs['in']['desc']
        else:
            self.docs['out']['desc'] = ''

function (purpose) {
    const oThis = this;

    for (var chain in setupConfig.chains) {
      // Add comment to ENV
      fileManager.append(setupConfig.env_vars_file, "\n# "+chain+" chain");
      // Add content
      oThis._scanAndPopulateEnvVars(setupConfig.chains[chain],purpose);
    }
  }

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


Question:
Find the next Disposition

@return the next InterfaceHttpData if any
@throws ErrorDataDecoderException

private InterfaceHttpData findMultipartDisposition() {
        int readerIndex = undecodedChunk.readerIndex();
        if (currentStatus == MultiPartStatus.DISPOSITION) {
            currentFieldAttributes = new TreeMap<CharSequence, Attribute>(CaseIgnoringComparator.INSTANCE);
        }
        // read many lines until empty line with newline found! Store all data
        while (!skipOneLine()) {
            String newline;
            try {
                skipControlCharacters(undecodedChunk);
                newline = readLine(undecodedChunk, charset);
            } catch (NotEnoughDataDecoderException ignored) {
                undecodedChunk.readerIndex(readerIndex);
                return null;
            }
            String[] contents = splitMultipartHeader(newline);
            if (HttpHeaderNames.CONTENT_DISPOSITION.contentEqualsIgnoreCase(contents[0])) {
                boolean checkSecondArg;
                if (currentStatus == MultiPartStatus.DISPOSITION) {
                    checkSecondArg = HttpHeaderValues.FORM_DATA.contentEqualsIgnoreCase(contents[1]);
                } else {
                    checkSecondArg = HttpHeaderValues.ATTACHMENT.contentEqualsIgnoreCase(contents[1])
                            || HttpHeaderValues.FILE.contentEqualsIgnoreCase(contents[1]);
                }
                if (checkSecondArg) {
                    // read next values and store them in the map as Attribute
                    for (int i = 2; i < contents.length; i++) {
                        String[] values = contents[i].split("=", 2);
                        Attribute attribute;
                        try {
                            attribute = getContentDispositionAttribute(values);
                        } catch (NullPointerException e) {
                            throw new ErrorDataDecoderException(e);
                        } catch (IllegalArgumentException e) {
                            throw new ErrorDataDecoderException(e);
                        }
                        currentFieldAttributes.put(attribute.getName(), attribute);
                    }
                }
            } else if (HttpHeaderNames.CONTENT_TRANSFER_ENCODING.contentEqualsIgnoreCase(contents[0])) {
                Attribute attribute;
                try {
                    attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_TRANSFER_ENCODING.toString(),
                            cleanString(contents[1]));
                } catch (NullPointerException e) {
                    throw new ErrorDataDecoderException(e);
                } catch (IllegalArgumentException e) {
                    throw new ErrorDataDecoderException(e);
                }

                currentFieldAttributes.put(HttpHeaderNames.CONTENT_TRANSFER_ENCODING, attribute);
            } else if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(contents[0])) {
                Attribute attribute;
                try {
                    attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_LENGTH.toString(),
                            cleanString(contents[1]));
                } catch (NullPointerException e) {
                    throw new ErrorDataDecoderException(e);
                } catch (IllegalArgumentException e) {
                    throw new ErrorDataDecoderException(e);
                }

                currentFieldAttributes.put(HttpHeaderNames.CONTENT_LENGTH, attribute);
            } else if (HttpHeaderNames.CONTENT_TYPE.contentEqualsIgnoreCase(contents[0])) {
                // Take care of possible "multipart/mixed"
                if (HttpHeaderValues.MULTIPART_MIXED.contentEqualsIgnoreCase(contents[1])) {
                    if (currentStatus == MultiPartStatus.DISPOSITION) {
                        String values = StringUtil.substringAfter(contents[2], '=');
                        multipartMixedBoundary = "--" + values;
                        currentStatus = MultiPartStatus.MIXEDDELIMITER;
                        return decodeMultipart(MultiPartStatus.MIXEDDELIMITER);
                    } else {
                        throw new ErrorDataDecoderException("Mixed Multipart found in a previous Mixed Multipart");
                    }
                } else {
                    for (int i = 1; i < contents.length; i++) {
                        final String charsetHeader = HttpHeaderValues.CHARSET.toString();
                        if (contents[i].regionMatches(true, 0, charsetHeader, 0, charsetHeader.length())) {
                            String values = StringUtil.substringAfter(contents[i], '=');
                            Attribute attribute;
                            try {
                                attribute = factory.createAttribute(request, charsetHeader, cleanString(values));
                            } catch (NullPointerException e) {
                                throw new ErrorDataDecoderException(e);
                            } catch (IllegalArgumentException e) {
                                throw new ErrorDataDecoderException(e);
                            }
                            currentFieldAttributes.put(HttpHeaderValues.CHARSET, attribute);
                        } else {
                            Attribute attribute;
                            try {
                                attribute = factory.createAttribute(request,
                                        cleanString(contents[0]), contents[i]);
                            } catch (NullPointerException e) {
                                throw new ErrorDataDecoderException(e);
                            } catch (IllegalArgumentException e) {
                                throw new ErrorDataDecoderException(e);
                            }
                            currentFieldAttributes.put(attribute.getName(), attribute);
                        }
                    }
                }
            } else {
                throw new ErrorDataDecoderException("Unknown Params: " + newline);
            }
        }
        // Is it a FileUpload
        Attribute filenameAttribute = currentFieldAttributes.get(HttpHeaderValues.FILENAME);
        if (currentStatus == MultiPartStatus.DISPOSITION) {
            if (filenameAttribute != null) {
                // FileUpload
                currentStatus = MultiPartStatus.FILEUPLOAD;
                // do not change the buffer position
                return decodeMultipart(MultiPartStatus.FILEUPLOAD);
            } else {
                // Field
                currentStatus = MultiPartStatus.FIELD;
                // do not change the buffer position
                return decodeMultipart(MultiPartStatus.FIELD);
            }
        } else {
            if (filenameAttribute != null) {
                // FileUpload
                currentStatus = MultiPartStatus.MIXEDFILEUPLOAD;
                // do not change the buffer position
                return decodeMultipart(MultiPartStatus.MIXEDFILEUPLOAD);
            } else {
                // Field is not supported in MIXED mode
                throw new ErrorDataDecoderException("Filename not found");
            }
        }
    }

public function display( Exception $exception, $id, $code, array $headers )
	{
		$info = $this->info->generate( $exception, $id, $code );

		return new Response( $this->render( $info ), $code, array_merge( $headers, ['Content-Type' => $this->contentType()] ) );
	}

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


Question:
Returns the object bound with the specified name in this session, or null if no object is bound under the name.

@param name a string specifying the name of the object
@param <T>  The type parameter
@return the object with the specified name

@SuppressWarnings("unchecked")
    public <T> T attribute(String name) {
        return (T) session.getAttribute(name);
    }

public function render($type = 'html')
    {
        $row = $this->getTable()->getRow()->getActualRow();

        $value = '';

        if (is_array($row) || $row instanceof \ArrayAccess) {
            $value = (isset($row[$this->getHeader()->getName()])) ? $row[$this->getHeader()->getName()] : '';
        } elseif (is_object($row)) {
            $headerName = $this->getHeader()->getName();
            $methodName = 'get' . ucfirst($headerName);
            if (method_exists($row, $methodName)) {
                $value = $row->$methodName();
            } else {
                $value = (property_exists($row, $headerName)) ? $row->$headerName : '';
            }
        }

        foreach ($this->decorators as $decorator) {
            if ($decorator->validConditions()) {
                $value = $decorator->render($value);
            }
        }

        if ($type == 'html') {
            $ret = sprintf("<td %s>%s</td>", $this->getAttributes(), $value);
            $this->clearVar();
            return $ret;

        } else {
            return $value;
        }
    }

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


Question: Parses the given file-like object.

def _parse_file(self, file):

        case = Case()
        file.seek(0)

        line = file.readline().split()
        if line[0] != "function":
            logger.error("Invalid data file header.")
            return case
        if line[1] != "mpc":
            self._is_struct = False
            base = ""
        else:
            base = "mpc."
        case.name = line[-1]

        for line in file:
            if line.startswith("%sbaseMVA" % base):
                case_data = line.rstrip(";\n").split()
                case.base_mva = float(case_data[-1])
            elif line.startswith("%sbus" % base):
                self._parse_buses(case, file)
            elif line.startswith("%sgencost" % base):
                self._parse_gencost(case, file)
            elif line.startswith("%sgen" % base):
                self._parse_generators(case, file)
            elif line.startswith("%sbranch" % base):
                self._parse_branches(case, file)

        return case

public BufferedReader newBufferedReader(Path path, Charset cs)
    {
        try {
            return Files.newBufferedReader(path, cs);
        } catch (IOException e) {
            return null;
        }
    }

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


Question:
Reopens the stdout and stderr output files, as set by
    L{outputToFiles}.

def reopenOutputFiles():

    if not _stdout and not _stderr:
        debug('log', 'told to reopen log files, but log files not set')
        return

    def reopen(name, fileno, *args):
        oldmask = os.umask(0026)
        try:
            f = open(name, 'a+', *args)
        finally:
            os.umask(oldmask)

        os.dup2(f.fileno(), fileno)

    if _stdout:
        reopen(_stdout, sys.stdout.fileno())

    if _stderr:
        reopen(_stderr, sys.stderr.fileno(), 0)
        debug('log', 'opened log %r', _stderr)

def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):

    if all([utils.file_exists(x) for x in out_files]):
        return out_files
    cmd = _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data)
    if len(fastq_files) == 1:
        of = [out_files[0], log_file]
        message = "Trimming %s in single end mode with cutadapt." % (fastq_files[0])
        with file_transaction(data, of) as of_tx:
            of1_tx, log_tx = of_tx
            do.run(cmd.format(**locals()), message)
    else:
        of = out_files + [log_file]
        with file_transaction(data, of) as tx_out_files:
            of1_tx, of2_tx, log_tx = tx_out_files
            tmp_fq1 = utils.append_stem(of1_tx, ".tmp")
            tmp_fq2 = utils.append_stem(of2_tx, ".tmp")
            singles_file = of1_tx + ".single"
            message = "Trimming %s and %s in paired end mode with cutadapt." % (fastq_files[0],
                                                                                fastq_files[1])
            do.run(cmd.format(**locals()), message)
    return out_files

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


Question: Receives a value for the object and some context on its source.

def Set(self, value, context=None):
    """"""
    if self.has_error: return
    if self.value is None:
      self.value = value
      self._context["old_value"] = value
      self._context.update({"old_" + k: v for k, v in context.items()})
    elif self.value != value:
      self.has_error = True
      self._context["new_value"] = value
      self._context.update({"new_" + k: v for k, v in context.items()})

public void marshall(DeliveryChannelStatus deliveryChannelStatus, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(deliveryChannelStatus.getName(), NAME_BINDING);
            protocolMarshaller.marshall(deliveryChannelStatus.getConfigSnapshotDeliveryInfo(), CONFIGSNAPSHOTDELIVERYINFO_BINDING);
            protocolMarshaller.marshall(deliveryChannelStatus.getConfigHistoryDeliveryInfo(), CONFIGHISTORYDELIVERYINFO_BINDING);
            protocolMarshaller.marshall(deliveryChannelStatus.getConfigStreamDeliveryInfo(), CONFIGSTREAMDELIVERYINFO_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Returns the type of the meta data if meta data is available.

@return Meta type.

@Nullable
    public final EnhancedMimeType getMetaContentType() {
        if ((metaContentType == null) && (metaContentTypeStr != null)) {
            metaContentType = EnhancedMimeType.create(metaContentTypeStr);
        }
        return metaContentType;
    }

protected function setMediaMetadata()
    {
        $mediaMetadata = $this->getDataProperty('metadata');
        if (is_array($mediaMetadata)) {
            if ($mediaMetadata['.tag'] === 'photo') {
                //Media is Photo
                $this->mediaMetadata = new PhotoMetadata($mediaMetadata);
            } elseif ($mediaMetadata['.tag'] === 'video') {
                //Media is Video
                $this->mediaMetadata = new VideoMetadata($mediaMetadata);
            } else {
                //Unknown Media (Quite unlikely, though.)
                $this->mediaMetadata = new MediaMetadata($mediaMetadata);
            }
        }
    }

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


Question: Auto Generated Code

def event_handler_event_handler_list_action_action_choice_python_script_python_script(self, **kwargs):

        config = ET.Element("config")
        event_handler = ET.SubElement(config, "event-handler", xmlns="urn:brocade.com:mgmt:brocade-event-handler")
        event_handler_list = ET.SubElement(event_handler, "event-handler-list")
        name_key = ET.SubElement(event_handler_list, "name")
        name_key.text = kwargs.pop('name')
        action = ET.SubElement(event_handler_list, "action")
        action_choice = ET.SubElement(action, "action-choice")
        python_script = ET.SubElement(action_choice, "python-script")
        python_script = ET.SubElement(python_script, "python-script")
        python_script.text = kwargs.pop('python_script')

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

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question:
Function: WebFinger

WebFinger constructor

Returns:

return WebFinger object

function WebFinger(config) {
    if (typeof config !== 'object') {
      config = {};
    }

    this.config = {
      tls_only:         (typeof config.tls_only !== 'undefined') ? config.tls_only : true,
      webfist_fallback: (typeof config.webfist_fallback !== 'undefined') ? config.webfist_fallback : false,
      uri_fallback:     (typeof config.uri_fallback !== 'undefined') ? config.uri_fallback : false,
      request_timeout:  (typeof config.request_timeout !== 'undefined') ? config.request_timeout : 10000
    };
  }

func init() {
	DefaultCallback.Query().Register("gorm:query", queryCallback)
	DefaultCallback.Query().Register("gorm:preload", preloadCallback)
	DefaultCallback.Query().Register("gorm:after_query", afterQueryCallback)
}

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


Question: Load configuration for an example. Used for SystemJS

function loadExampleConfig(exampleFolder) {
  // Default config.
  let config = {build: 'build', run: 'serve:e2e'};

  try {
    const exampleConfig = fs.readJsonSync(`${exampleFolder}/${EXAMPLE_CONFIG_FILENAME}`);
    Object.assign(config, exampleConfig);
  } catch (e) {
  }

  return config;
}

function(configFilePath) {
  FileRegistry.super_.call(this);
  this._configFilePath = configFilePath || this._getDefaultConfigFilePath();
  try {
    var data = fs.readFileSync(this._configFilePath, 'utf-8');
    this._registryConfig = JSON.parse(data);
  } catch(e) {}
}

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


Question:
Write log record into log

@param LogRecord $record
@return string

public function write(LogRecord $record)
    {
        $logLine = array();

        if ($record->time) {
            $timestr = ($this->logLevel >= self::LEVEL_DEBUG) ?
                $this->udate('Y-m-d H:i:s.u T', $record->time) :
                date('Y/m/d h:i:s', $record->time);
            $logLine[] = "[ $timestr ]";
        }

        if ($record->level != null) {
            $logLine[] = self::LEVELS[$record->level];
        }

        $logLine[] = $record->message;

        $message = implode(' ', $logLine) . PHP_EOL;

        if ($this->fp) {
            fwrite($this->fp, $message);
        } else {
            if (isset($GLOBALS['useErrorLog'])) {
                error_log($message);
            } else {
                file_put_contents('php://stderr', $message, FILE_APPEND);
            }
        }

        return $message;
    }

def show_raslog_output_show_all_raslog_raslog_entries_severity(self, **kwargs):

        config = ET.Element("config")
        show_raslog = ET.Element("show_raslog")
        config = show_raslog
        output = ET.SubElement(show_raslog, "output")
        show_all_raslog = ET.SubElement(output, "show-all-raslog")
        raslog_entries = ET.SubElement(show_all_raslog, "raslog-entries")
        severity = ET.SubElement(raslog_entries, "severity")
        severity.text = kwargs.pop('severity')

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

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


Question:
Calculate percentage rank of a sequence expression.

    :param expr: expression for calculation
    :param sort: name of the sort column
    :param ascending: whether to sort in ascending order
    :return: calculated column

def percent_rank(expr, sort=None, ascending=True):

    return _rank_op(expr, PercentRank, types.float64, sort=sort, ascending=ascending)

public function orderByRaw(string $sql, array $bindings = []): BaseQueryRelateContract
    {
        $this->query->orderByRaw($sql, $bindings);

        return $this;
    }

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


Question:
// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
// it looks just like a function call.  The arg list, if non-nil, includes (in the manner of the shell), arg[0]
// as the function itself.

func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
	if args != nil {
		args = args[1:] // Zeroth arg is function name/node; not passed to function.
	}
	typ := fun.Type()
	numIn := len(args)
	if final.IsValid() {
		numIn++
	}
	numFixed := len(args)
	if typ.IsVariadic() {
		numFixed = typ.NumIn() - 1 // last arg is the variadic one.
		if numIn < numFixed {
			s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
		}
	} else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
		s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
	}
	if !goodFunc(typ) {
		// TODO: This could still be a confusing error; maybe goodFunc should provide info.
		s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
	}
	// Build the arg list.
	argv := make([]reflect.Value, numIn)
	// Args must be evaluated. Fixed args first.
	i := 0
	for ; i < numFixed && i < len(args); i++ {
		argv[i] = s.evalArg(dot, typ.In(i), args[i])
	}
	// Now the ... args.
	if typ.IsVariadic() {
		argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
		for ; i < len(args); i++ {
			argv[i] = s.evalArg(dot, argType, args[i])
		}
	}
	// Add final value if necessary.
	if final.IsValid() {
		t := typ.In(typ.NumIn() - 1)
		if typ.IsVariadic() {
			t = t.Elem()
		}
		argv[i] = s.validateType(final, t)
	}
	result := fun.Call(argv)
	// If we have an error that is not nil, stop execution and return that error to the caller.
	if len(result) == 2 && !result[1].IsNil() {
		s.at(node)
		s.errorf("error calling %s: %s", name, result[1].Interface().(error))
	}
	return result[0]
}

def _resolve_expression_block(self, expression, context, url_encode, strategy, errors):

        try:
            body = expression[1:]  # strip prefix

            # if expression doesn't start with ( then check it's an allowed top level context reference
            if not body.startswith('('):
                top_level = body.split('.')[0].lower()
                if top_level not in self._allowed_top_levels:
                    return expression

            evaluated = self.evaluate_expression(body, context, strategy)

            # convert result to string
            result = conversions.to_string(evaluated, context)

            return urlquote(result) if url_encode else result
        except EvaluationError as e:
            logger.debug("EvaluationError: %s" % str(e))

            # if we can't evaluate expression, include it as is in the output
            errors.append(str(e))
            return expression

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


Question: Restore row from BigQuery

def restore_row(self, row, schema):

        for index, field in enumerate(schema.fields):
            if field.type == 'datetime':
                row[index] = parse(row[index])
            if field.type == 'date':
                row[index] = parse(row[index]).date()
            if field.type == 'time':
                row[index] = parse(row[index]).time()
        return schema.cast_row(row)

func (col *Column) ResolveIndices(schema *Schema) (Expression, error) {
	newCol := col.Clone()
	err := newCol.resolveIndices(schema)
	return newCol, err
}

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


Question:
If you want to allow a page to be cached by shared proxies for one minute.

@param int $seconds Interval in seconds

@return $this

public function cacheNoValidate($seconds = 60)
    {
        self::preventMultipleCaching();
        self::$cached = true;
        Header::cacheNoValidate($seconds);

        return $this;
    }

def schedule_cycles(minutes,location_id,conditions = {})

			products = Auth.configuration.product_class.constantize.all if conditions.blank?

			products = Auth.configuration.product_class.constantize.where(conditions) if !conditions.blank?

			minutes.keys.each do |epoch|

				products.each do |product|

					all_cycles_valid = true
					product.cycles.each do |cycle|

						all_cycles_valid = cycle.requirements_satisfied(epoch + cycle.time_since_prev_cycle.minutes*60,location_id)

					end

					## just because the cycles are valid, it means we have workers, but how many?
					## that also has to be returned by the cycle validity statements

					if all_cycles_valid == true
						cycle_chain = []
						product.cycles.each do |cycle|
							epoch_at_which_to_add = epoch + cycle.time_since_prev_cycle.minutes*60
							cycle_to_add = cycle.dup
							cycle_to_add.start_time = epoch_at_which_to_add
							cycle_to_add.end_time = cycle_to_add.start_time + cycle_to_add.duration
							cycle_to_add.cycle_chain = cycle_chain
							if minutes[epoch_at_which_to_add]

								add_to_previous_rolling_n_minutes(minutes,epoch_at_which_to_add,cycle_to_add)

								minutes[epoch_at_which_to_add].cycles << cycle_to_add

								cycle_chain << cycle_to_add.id.to_s
							else
								#raise "necessary minute not in range."
							end
						end
					end
				end
			end
			minutes
		end

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


Question: //HTTPCode 返回HTTP状态码

func (s State) HTTPCode() int {
	if v, y := GetStatus(s); y {
		return v.Code
	}
	return http.StatusOK
}

protected function sendLockoutResponse(Request $request)
    {
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );

        return HCLog::info('AUTH-005', trans('auth.throttle', ['seconds' => $seconds]));
    }

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


Question:
Parse an ELF file and fill the class' properties.

        Arguments:
            f(file or str): The (path to) the ELF file to read.

def parse_file(self, f):

        if type(f) is str:
            self.f = open(f, 'rb')
        else:
            self.f = f
        self._parse_header(self.f.read(64))

static public List<String> convertLoadpathVariable(Element element) {

        // Create the list of strings. Always add the empty string as this will
        // force the lookup routine to always include the "current" directory.
        LinkedList<String> filelist = new LinkedList<String>();
        filelist.add("");

        // If the argument is null (the variable doesn't exist), then just
        // return the list with the current directory.
        if (element == null) {
            return filelist;
        }

        // Verify that the element is of the correct type (i.e. a list).
        if (!(element instanceof ListResource)) {
            throw new EvaluationException("LOADPATH variable must be a list");
        }

        // Loop over the values in the list.
        ListResource loadpath = (ListResource) element;
        for (int i = 0; i < loadpath.size(); i++) {
            try {
                Element child = loadpath.get(TermFactory.create(i));
                if (child instanceof StringProperty) {
                    String sfile = ((StringProperty) child).getValue();
                    if (sfile.startsWith("/")) {
                        throw new EvaluationException(
                                "LOADPATH can only contain relative paths");
                    }
                    filelist.add(sfile);
                } else {
                    throw new EvaluationException(
                            "LOADPATH contains non-string value");
                }
            } catch (InvalidTermException ite) {
                // This exception should never be encountered because the terms
                // are all indexes and the resource is a list.
                throw CompilerError.create(MSG_INVALID_KEY_OR_INDEX);
            }

        }

        return filelist;
    }

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


Question:
// Push appends a function to the Pipe.
// Note that you can add as many functions as you like at once or
// separatly. They will be processed in order.

func (p *Pipe) Push(procs ...Filter) *Pipe {
	for _, proc := range procs {
		if proc == nil {
			continue
		}

		err := make(chan error, 1)
		p.errors = append(p.errors, err)

		r, w := io.Pipe()

		go func(p Filter, r io.Reader, w *io.PipeWriter, err chan error) {
			err <- p(r, w)
			w.Close()
		}(proc, p.reader, w, err)

		p.reader = r
	}
	return p
}

func (f *FilterStore) PutFilter(hash *chainhash.Hash,
	filter *gcs.Filter, fType FilterType) error {

	return walletdb.Update(f.db, func(tx walletdb.ReadWriteTx) error {
		filters := tx.ReadWriteBucket(filterBucket)

		var targetBucket walletdb.ReadWriteBucket
		switch fType {
		case RegularFilter:
			targetBucket = filters.NestedReadWriteBucket(regBucket)
		default:
			return fmt.Errorf("unknown filter type: %v", fType)
		}

		if filter == nil {
			return targetBucket.Put(hash[:], nil)
		}

		bytes, err := filter.NBytes()
		if err != nil {
			return err
		}

		return targetBucket.Put(hash[:], bytes)
	})
}

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


Question:
Retrieve the dual-select's options.

@return array

public function dualSelectOptions()
    {
        if ($this->dualSelectOptions === null) {
            $this->dualSelectOptions = $this->defaultDualSelectOptions();
        }

        return $this->dualSelectOptions;
    }

function extractPalette(parts, theme) {
      // If the next section is one of the palettes we assume it's a two word palette
      // Two word palette can be also written in camelCase, forming camelCase to dash-case

      var isTwoWord = parts.length > 1 && colorPalettes.indexOf(parts[1]) !== -1;
      var palette = parts[0].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

      if (isTwoWord)  palette = parts[0] + '-' + parts.splice(1, 1);

      if (colorPalettes.indexOf(palette) === -1) {
        // If the palette is not in the palette list it's one of primary/accent/warn/background
        var scheme = $mdTheming.THEMES[theme].colors[palette];
        if (!scheme) {
          throw new Error($mdUtil.supplant(
            'mdColors: couldn\'t find \'{palette}\' in the palettes.',
            {palette: palette}));
        }
        palette = scheme.name;
      }

      return palette;
    }

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


Question:
Insert buttonbar resources

This method is abstracted because it is invoked by multiple controllers.

@param Gdn_Controller $Sender

protected function AttachButtonBarResources($Sender, $Formatter) {
      if (!in_array($Formatter, $this->Formats)) return;
      $Sender->AddJsFile('buttonbar.js', 'plugins/ButtonBar');
      $Sender->AddJsFile('jquery.hotkeys.js', 'plugins/ButtonBar');

      $Sender->AddDefinition('ButtonBarLinkUrl', T('ButtonBar.LinkUrlText', 'Enter your URL:'));
      $Sender->AddDefinition('ButtonBarImageUrl', T('ButtonBar.ImageUrlText', 'Enter image URL:'));
      $Sender->AddDefinition('ButtonBarBBCodeHelpText', T('ButtonBar.BBCodeHelp', 'You can use BBCode in your post.'));
      $Sender->AddDefinition('ButtonBarHtmlHelpText', T('ButtonBar.HtmlHelp', 'You can use Simple Html in your post.'));
      $Sender->AddDefinition('ButtonBarMarkdownHelpText', T('ButtonBar.MarkdownHelp', 'You can use Markdown in your post.'));

      $Sender->AddDefinition('InputFormat', $Formatter);
   }

public void marshall(DescribeDomainControllersRequest describeDomainControllersRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeDomainControllersRequest.getDirectoryId(), DIRECTORYID_BINDING);
            protocolMarshaller.marshall(describeDomainControllersRequest.getDomainControllerIds(), DOMAINCONTROLLERIDS_BINDING);
            protocolMarshaller.marshall(describeDomainControllersRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeDomainControllersRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Process the message with the modifiers.

@param {Mixed} message The message to be transformed by modifers.
@returns {String} Transformed message.
@public

function process(message) {
  for (var i = 0; i < modifiers.length; i++) {
    message = modifiers[i].apply(modifiers[i], arguments);
  }

  return message;
}

func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
	app := in.App

	flds := ""
	valid := true
	var logs []*pb.LogEntry
	var decoder PayloadDecoder
	switch application.PayloadFormat(app.PayloadFormat) {
	case "", application.PayloadFormatCustom:
		decoder = &CustomUplinkFunctions{
			Decoder:   app.Decoder,
			Converter: app.Converter,
			Validator: app.Validator,
			Logger:    functions.NewEntryLogger(),
		}
	case application.PayloadFormatCayenneLPP:
		decoder = &cayennelpp.Decoder{}
	default:
		return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
	}

	fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
	if err != nil {
		return nil, err
	}

	valid = val
	logs = decoder.Log()

	marshalled, err := json.Marshal(fields)
	if err != nil {
		return nil, err
	}

	flds = string(marshalled)

	return &pb.DryUplinkResult{
		Payload: in.Payload,
		Fields:  flds,
		Valid:   valid,
		Logs:    logs,
	}, nil
}

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


Question: Initialization common to Map and Reduce

void init(JobID jobId) {
    this.startTime = JobTracker.getClock().getTime();
    this.id = new TaskID(jobId, isMapTask(), partition);
    this.skipping = startSkipping();
    long speculativeDuration;
    if (isMapTask()) {
      this.speculativeLag = conf.getMapSpeculativeLag();
      speculativeDuration = conf.getMapSpeculativeDuration();
    } else {
      this.speculativeLag = conf.getReduceSpeculativeLag();
      speculativeDuration = conf.getReduceSpeculativeDuration();
    }

    // speculate only if 1/(1000 * progress_rate) > speculativeDuration
    // ie. :
    // speculate only if progress_rate < 1/(1000 * speculativeDuration)

    if (speculativeDuration > 0) {
      this.maxProgressRateForSpeculation = 1.0/(1000.0*speculativeDuration);
    } else {
      // disable this check for durations <= 0
      this.maxProgressRateForSpeculation = -1.0;
    }

    this.useProcessingRateForSpeculation =
        conf.getBoolean("mapreduce.job.speculative.using.processing.rate",
            false);
  }

def start(cls, cluster_id_label, api_version=None):

        conn = Qubole.agent(version=api_version)
        data = {"state": "start"}
        return conn.put(cls.element_path(cluster_id_label) + "/state", data)

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


Question: // SetClientRequestToken sets the ClientRequestToken field's value.

func (s *Cluster) SetClientRequestToken(v string) *Cluster {
	s.ClientRequestToken = &v
	return s
}

def _get_token_from_query_string(self, request, refresh_token):

        if refresh_token:
            query_string_token_name_key = "query_string_refresh_token_name"
        else:
            query_string_token_name_key = "query_string_access_token_name"
        query_string_token_name = getattr(
            self.config, query_string_token_name_key
        )
        return request.args.get(query_string_token_name(), None)

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


Question: can override for other style

def wo_resp(self, resp):

        if self._data is not None:
            resp['res'] = self.to_str(self._data)

        return self.wo_json(resp)

public void setTransform(Element element, String transform) {
		if (transform.contains("scale")) {
			try {
				String scaleValue = transform.substring(transform.indexOf("scale(") + 6);
				scaleValue = scaleValue.substring(0, scaleValue.indexOf(")"));
				Dom.setStyleAttribute(element, "zoom", scaleValue);
			} catch (Exception e) {
			}
		}
	}

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


Question:
Delete all the files from a directory.

@param string $directory

public static function clear_directory($directory)
    {
        foreach (scandir($directory) as $file) {
            if ($file !== '.' and $file !== '..') {
                unlink($directory.$file);
            }
        }
    }

public function setPathParameters(array $pathParameters)
    {
        foreach ($pathParameters as $name => $value) {
            $this->setPathParameter($name, $value);
        }
    }

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


Question: Removes all buckets and their content for specified hash.

def clean_buckets(self, hash_name):

        bucket_keys = self._iter_bucket_keys(hash_name)
        self.redis_object.delete(*bucket_keys)

def delete
      return if !verify_logged_in

      resp = Caboose::StdClass.new
      search = SavedSearch.find(params[:id])

      if search
        search.destroy
        resp.success = "The saved search has been deleted."
      else
        resp.error = "There was an error deleting your search."
      end

      render :json => resp
    end

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


Question:
make all pairwise genome comparisons to get rbhs
    rbh = {genome: {other_genome: {rbh_id: [rbh_match, pident, e, bit, norm_bit]]}}

def compare_genomes(fastas, id2desc, algorithm):

    hits = {}
    for pair in itertools.permutations(fastas, 2):
        if pair[0] not in hits:
            hits[pair[0]] = {}
        hits[pair[0]][pair[1]] = {}
    for pair in itertools.combinations(fastas, 2):
        A, B = pair
        blastF = open(search(A, B, method = algorithm, alignment = 'local'))
        blastR = open(search(B, A, method = algorithm, alignment = 'local'))
        for compare in [A, B, blastF], [B, A, blastR]:
            query, ref, blast = compare
            for hit in best_blast(blast, 1):
                a, b, pident, qstart, qend, e, bit = \
                        hit[0].split()[0], hit[1].split()[0], float(hit[2]), float(hit[6]), float(hit[7]), float(hit[-2]), float(hit[-1])
                alignment_length = abs(qstart - qend + 1)
                norm_bit = normalize_bit(a, b, bit, id2desc)
                length_fraction = float((alignment_length) / id2desc[a][2])
                hits[query][ref][a] = ['fbh', a, b, pident, length_fraction, e, bit, norm_bit]
    return hits

def define
      lib_path = @libs.join(File::PATH_SEPARATOR)
      actual_name = Hash === name ? name.keys.first : name
      unless Rake.application.last_comment
        desc "Analyze code coverage with tests" +
          (@name==:rcov ? "" : " for #{actual_name}")
      end
      task @name do
        run_code = ''
        RakeFileUtils.verbose(@verbose) do
          run_code =
          case rcov_path
          when nil, ''
            "-S rcov"
          else %!"#{rcov_path}"!
          end
          ruby_opts = @ruby_opts.clone
          ruby_opts.push( "-I#{lib_path}" )
          ruby_opts.push run_code
          ruby_opts.push( "-w" ) if @warning
          ruby ruby_opts.join(" ") + " " + option_list +
          %[ -o "#{@output_dir}" ] +
          file_list.collect { |fn| %["#{fn}"] }.join(' ')
        end
      end

      desc "Remove rcov products for #{actual_name}"
      task paste("clobber_", actual_name) do
        rm_r @output_dir rescue nil
      end

      clobber_task = paste("clobber_", actual_name)
      task :clobber => [clobber_task]

      task actual_name => clobber_task
      self
    end

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


Question: Get the generation key for any number of tables.

def get_generation(self, *tables, **kwargs):
        """"""
        db = kwargs.get('db', 'default')
        if len(tables) > 1:
            return self.get_multi_generation(tables, db)
        return self.get_single_generation(tables[0], db)

func (session *Session) CreateTable(bean interface{}) error {
	v := rValue(bean)
	session.Statement.setRefValue(v)

	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	return session.createOneTable()
}

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


Question: // SetVlan sets the Vlan field's value.

func (s *NewTransitVirtualInterfaceAllocation) SetVlan(v int64) *NewTransitVirtualInterfaceAllocation {
	s.Vlan = &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:
Handle the {@link PingPayload} by echoing the {@link PingPayload#getZen()}.

@param payload the incoming payload
@return the zen

@RequestMapping(method = POST)
    public String ping(@Valid @RequestBody PingPayload payload) {
        logger.info("received Ping event - {}", payload);
        return payload.getZen();
    }

func query(method, path string, values url.Values, v interface{}) error {
	// parse the stripe URL
	endpoint, err := url.Parse(_url)
	if err != nil {
		return err
	}

	// set the endpoint for the specific API
	endpoint.Path = path
	endpoint.User = url.User(_key)

	// if this is an http GET, add the url.Values to the endpoint
	if method == "GET" {
		endpoint.RawQuery = values.Encode()
	}

	// else if this is not a GET, encode the url.Values in the body.
	var reqBody io.Reader
	if method != "GET" && values != nil {
		reqBody = strings.NewReader(values.Encode())
	}

	// Log request if logging enabled
	if _log {
		fmt.Println("REQUEST: ", method, endpoint.String())
		fmt.Println(values.Encode())
	}

	// create the request
	req, err := http.NewRequest(method, endpoint.String(), reqBody)
	if err != nil {
		return err
	}

	req.Header.Set("Stripe-Version", apiVersion)

	// submit the http request
	r, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	// read the body of the http message into a byte array
	body, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		return err
	}

	// Log response if logging enabled
	if _log {
		fmt.Println("RESPONSE: ", r.StatusCode)
		fmt.Println(string(body))
	}

	// is this an error?
	if r.StatusCode != 200 {
		error := Error{}
		json.Unmarshal(body, &error)
		return &error
	}

	//parse the JSON response into the response object
	return json.Unmarshal(body, v)
}

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


Question:
Returns a list of all curencies (by code) that have a service defined that
    implements `get_block`.

def get_block_currencies():

    return ['btc', 'ltc', 'ppc', 'dash', 'doge', 'ric']
    currencies = []
    for currency, data in crypto_data.items():
        if type(data) is list:
            continue
        block_services = data.get('services', {}).get('get_block', [])
        if len(block_services) > 0 and not all([x.get_block.by_latest for x in block_services]):

            currencies.append(currency)

    return currencies

def currency
      # Mixing currency not allowed; this
      # library can't convert between
      # currencies.
      currencies = @contents.map { |item| item[:currency] }.uniq || "USD"

      case currencies.count
        when 0
          "USD"
        when 1
          currencies.first
        else
          raise RuntimeError.new("Mixing currency not allowed")
      end

    end

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


Question:
<p>
The tags to remove from the product.
</p>

@param removeTags
The tags to remove from the product.

public void setRemoveTags(java.util.Collection<String> removeTags) {
        if (removeTags == null) {
            this.removeTags = null;
            return;
        }

        this.removeTags = new java.util.ArrayList<String>(removeTags);
    }

private static MyNode compactForm(MyNode n) {
        if (n.node.getNodeType() == Node.TEXT_NODE) {
            n.out = n.node.getNodeValue().trim();
        } else {
            n.out = n.node.getNodeName();
            if (n.out.startsWith("m:")) {
                n.out = n.out.substring(2);
            }
            if ("annotation-xml".equals(n.out)) {
                n.out = "";
            }
            if ("pquery".equals(n.out) || "cquery".equals(n.out)) {
                n.out = "";
            }
            if ("mws:qvar".equals(n.out)) {
                final String qname = n.node.getAttributes().getNamedItem("name").toString();
                if (n.qVar == null) {
                    n.out = "\\qvar{x_0}";
                    n.qVar = new HashMap<>();
                    n.qVar.put(qname, 0);
                } else {
                    Integer qInt = n.qVar.get(qname);
                    if (qInt == null) {
                        n.out = "\\qvar{x_" + n.qVar.size() + "}";
                        n.qVar.put(qname, n.qVar.size());
                    } else {
                        n.out = "\\qqvar{x_" + qInt + "}";
                    }
                }
            }
            if (n.node.hasChildNodes()) {
                String sChild = "";
                for (Node childNode = n.node.getFirstChild();
                     childNode != null; childNode = childNode.getNextSibling()) {
                    MyNode ret = compactForm(new MyNode(childNode, n.qVar));
                    String cn = ret.out;
                    n.qVar = ret.qVar;
                    if (!cn.isEmpty()) {
                        sChild += cn + ";";
                    }
                }
                if (sChild.endsWith(";")) {
                    sChild = sChild.substring(0, sChild.length() - 1).trim();
                }
                if (!sChild.isEmpty() && sChild.codePointAt(0) != 8290 && sChild.codePointAt(0) != 8289) {
                    if ("m:annotation-xml".equals(n.node.getNodeName())) {
                        n.out += sChild;
                    } else {
                        n.out += '[' + sChild + ']';
                    }
                }
            }
        }
        if ("mo".equals(n.out)) {
            //Remove empty mo elements
            n.out = "";
        }
        return n;
    }

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


Question:
// deleteNodeCASTxn is used to try doing a node delete operation with a given
// raft index. If the CAS index specified is not equal to the last observed index for
// the given check, then the call is a noop, otherwise a normal check delete is invoked.

func (s *Store) deleteNodeCASTxn(tx *memdb.Txn, idx, cidx uint64, nodeName string) (bool, error) {
	// Look up the node.
	node, err := getNodeTxn(tx, nodeName)
	if err != nil {
		return false, err
	}
	if node == nil {
		return false, nil
	}

	// If the existing index does not match the provided CAS
	// index arg, then we shouldn't update anything and can safely
	// return early here.
	if node.ModifyIndex != cidx {
		return false, nil
	}

	// Call the actual deletion if the above passed.
	if err := s.deleteNodeTxn(tx, idx, nodeName); err != nil {
		return false, err
	}

	return true, nil
}

public function _cascadeDelete($parentTableClassname, array $primaryKey)
    {
        $this->_setupMetadata();
        $rowsAffected = 0;
        foreach ($this->_getReferenceMapNormalized() as $map) {
            if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_DELETE])) {
                switch ($map[self::ON_DELETE]) {
                    case self::CASCADE:
                        $where = array();
                        for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) {
                            $col = $this->_db->foldCase($map[self::COLUMNS][$i]);
                            $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
                            $type = $this->_metadata[$col]['DATA_TYPE'];
                            $where[] = $this->_db->quoteInto(
                                $this->_db->quoteIdentifier($col, true) . ' = ?',
                                $primaryKey[$refCol], $type);
                        }
                        $rowsAffected += $this->delete($where);
                        break;
                    default:
                        // no action
                        break;
                }
            }
        }
        return $rowsAffected;
    }

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


Question:
Adds a validation message to the result.

@param message a validation message to be added

private void addMessage(ValidationMessage<Origin> message) {
		if (message == null) {
			return;
		}

		if( null != defaultOrigin ) {
			message.addOrigin( defaultOrigin );
		}

		this.messages.add(message);
	}

public Value get(String name) {
        if (name.length() > 1) {
            int dot;
            if (name.charAt(0) == LPAREN) {
                int start = name.indexOf(RPAREN);
                dot = name.indexOf(DOT, start);
            } else {
                dot = name.indexOf(DOT);
            }
            if (dot > 0) {
                String fieldName = name.substring(0, dot);
                String rest = name.substring(dot + 1);
                Key key = createKey(fieldName);
                Value value = fields.get(key);
                if (!value.isMessageType()) {
                    throw new ParserException("Invalid option name: %s", name);
                }
                DynamicMessage msg = value.getMessage();
                return msg.get(rest);
            } else {
                Key key = createKey(name);
                return fields.get(key);
            }
        } else {
            Key key = Key.field(name);
            return fields.get(key);
        }
    }

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


Question:
Creates embedded message path composed of ancestor messages
separated by slash "/". If message has no ancestor returns empty string.

@param Descriptor|EnumDescriptor $descriptor

@return string

private function _createEmbeddedMessagePath($descriptor)
    {
        $containing = $descriptor->getContaining();
        $path = array();

        while ($containing && !$containing instanceof FileDescriptor) {
            /**
             * @var Descriptor $containing
             */
            $path[] = $containing->getFullName();
            $containing = $containing->getContaining();
        }

        array_reverse($path);

        return implode("/", $path);
    }

protected function findChatCommand($cmdAndArgs, $depth, $orig = null)
    {
        if ($depth == 0) {
            return [null, []];
        }

        if ($orig == null) {
            $orig = $cmdAndArgs;
        }

        $cmdAndArgs = array_splice($cmdAndArgs, 0, $depth);
        $parameters = array_diff($orig, $cmdAndArgs);
        $command = implode(' ', $cmdAndArgs);

        return isset($this->commands[$command])
            ? [$this->commands[$command], $parameters]
            : $this->findChatCommand($cmdAndArgs, $depth - 1, $orig);
    }

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


Question:
Gets the absolute file path as a string, normalized
to using front slashes for path separators.
@param {java.io.File||String} file

function (fileObj) {
            if (typeof fileObj === "string") {
                fileObj = new java.io.File(fileObj);
            }
            return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
        }

public static void copy(final File src, final File dest) throws IOException {
        if (src.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdir();
            }

            // Copy everything in directory
            String[] children = src.list();
            for (String child : children) {
                copy(new File(src, child), new File(dest, child));
            }
        } else {
            try (ReadableByteChannel in = Channels.newChannel(new FileInputStream(src))) {
                try (WritableByteChannel out = Channels.newChannel(new FileOutputStream(dest))) {
                    fastChannelCopy(in, out);
                }
            }
        }
    }

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


Question:
Parse provided value into new data

@param $value
@param $providers
@param array $references

@return mixed

public function parse($value, $providers = [], $references = [])
    {
        $referenceName = substr($value, 1);

        if (isset($references[$referenceName])) {
            return $references[$referenceName];
        }

        return $value;
    }

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

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


Question:
@since 0.1

{@inheritDoc}

public function doFilterResponseById( $oclcID ) {

		$text = $this->requestResponseFor( $oclcID );

		if ( $this->httpRequest->getLastError() !== '' ) {
			return $this->addMessage( array( 'onoi-remi-request-error', $this->httpRequest->getLastError(), $oclcID ) );
		}

		$jsonld = json_decode( $text, true );

		if ( $jsonld === null || $jsonld === '' ) {
			return $this->addMessage( array( 'onoi-remi-response-empty', $oclcID ) );
		}

		$this->doProcessJsonLd( $oclcID, $jsonld );

		$this->filteredRecord->set( 'retrieved-from', 'http://www.worldcat.org/' );
	}

def version_history(soup, html_flag=True):
    ""
    convert = lambda xml_string: xml_to_html(html_flag, xml_string)
    version_history = []
    related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))
    for tag in related_object_tags:
        article_version = OrderedDict()
        date_tag = first(raw_parser.date(tag))
        if date_tag:
            copy_attribute(date_tag.attrs, 'date-type', article_version, 'version')
            (day, month, year) = ymd(date_tag)
            article_version['day'] = day
            article_version['month'] = month
            article_version['year'] = year
            article_version['date'] = date_struct_nn(year, month, day)
        copy_attribute(tag.attrs, 'xlink:href', article_version, 'xlink_href')
        set_if_value(article_version, "comment",
                     convert(node_contents_str(first(raw_parser.comment(tag)))))
        version_history.append(article_version)
    return version_history

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


Question:
Auto-link mailto, ftp, and http strings in text

@param   array  $matches  Text to autolink
@return  string

protected function autolink($matches)
	{
		$href = $matches[0];

		if (substr($href, 0, 1) == '!')
		{
			return substr($href, 1);
		}

		$href = str_replace('"', '', $href);
		$href = str_replace("'", '', $href);
		$href = str_replace('&#8221', '', $href);

		$h = array('h', 'm', 'f', 'g', 'n');
		if (!in_array(substr($href, 0, 1), $h))
		{
			$href = substr($href, 1);
		}
		$name = trim($href);
		if (substr($name, 0, 7) == 'mailto:')
		{
			$name = substr($name, 7, strlen($name));
			$name = Str::obfuscate($name);

			$href = 'mailto:' . $name;
		}
		$l = sprintf(
			' %s', $href, $name
		);
		return $l;
	}

public function parse()
    {
        if (null === $this->html) {
            throw new HtmlPhpExcelException('You must provide html content first. Use setHtml() or setHtmlFile().');
        }

        $dom = new \DOMDocument();
        $dom->loadHTML($this->html);

        $xpath = new \DOMXPath($dom);
        $htmlTables = $xpath->query('.//table[contains(concat(" ", normalize-space(@class), " "), "'.$this->tableClass.'")]');

        $document = new Document();

        foreach ($htmlTables as $htmlTable) {

            $table = new Table();

            $htmlRows = $xpath->query('.//tr[contains(concat(" ", normalize-space(@class), " "), "'.$this->rowClass.'")]', $htmlTable);
            foreach($htmlRows as $htmlRow) {

                $row = new Row();
                $htmlCells = $xpath->query(
                     './/td[contains(concat(" ", normalize-space(@class), " "), "'.$this->cellClass.'")]
                    | .//th[contains(concat(" ", normalize-space(@class), " "), "'.$this->cellClass.'")]',
                    $htmlRow
                );

                foreach($htmlCells as $htmlCell) {
                    $cell = new Cell();
                    $cell->setValue($htmlCell->nodeValue);

                    foreach ($htmlCell->attributes as $attribute) {
                        $cell->addAttribute($attribute->name, $attribute->value);
                    }

                    if ('th' == $htmlCell->nodeName) {
                        $cell->setIsHeader(true);
                    }

                    $row->addCell($cell);
                }

                foreach ($htmlRow->attributes as $attribute) {
                    $row->addAttribute($attribute->name, $attribute->value);
                }

                $table->addRow($row);
            }

            foreach ($htmlTable->attributes as $attribute) {
                $table->addAttribute($attribute->name, $attribute->value);
            }

            $document->addTable($table);
        }

        return $document;
    }

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


Question: Extract a certain length fraction and place them in a new file.

def extract_length(self, lower_bound=None, upper_bound=None, new_path=None):
        """"""
        # Temporary path #
        if new_path is None: fraction = self.__class__(new_temp_path())
        elif isinstance(new_path, FASTA): fraction = new_path
        else:                fraction = self.__class__(new_path)
        # Generator #
        if lower_bound is None: lower_bound = 0
        if upper_bound is None: upper_bound = sys.maxint
        def fraction_iterator():
            for read in self:
                if lower_bound <= len(read) <= upper_bound:
                    yield read
        # Do it #
        fraction.write(fraction_iterator())
        fraction.close()
        return fraction

def save_hdf(self, filename, path='', overwrite=False):

        if os.path.exists(filename) and overwrite:
            os.remove(filename)

        for pop in self.poplist:
            name = pop.modelshort
            pop.save_hdf(filename, path='{}/{}'.format(path,name), append=True)

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