Question:
Alter this object properties

REST: PUT /ipLoadbalancing/{serviceName}/quota/{zone}
@param body [required] New object properties
@param serviceName [required] The internal name of your IP load balancing
@param zone [required] Zone of your quota

public void serviceName_quota_zone_PUT(String serviceName, String zone, OvhQuota body) throws IOException {
		String qPath = "/ipLoadbalancing/{serviceName}/quota/{zone}";
		StringBuilder sb = path(qPath, serviceName, zone);
		exec(qPath, "PUT", sb.toString(), body);
	}

protected function registerClassAliases()
    {
        $serviceAliases = [
            \Dingo\Api\Http\Request::class => \Dingo\Api\Contract\Http\Request::class,
            'api.dispatcher' => \Dingo\Api\Dispatcher::class,
            'api.http.validator' => \Dingo\Api\Http\RequestValidator::class,
            'api.http.response' => \Dingo\Api\Http\Response\Factory::class,
            'api.router' => \Dingo\Api\Routing\Router::class,
            'api.router.adapter' => \Dingo\Api\Contract\Routing\Adapter::class,
            'api.auth' => \Dingo\Api\Auth\Auth::class,
            'api.limiting' => \Dingo\Api\Http\RateLimit\Handler::class,
            'api.transformer' => \Dingo\Api\Transformer\Factory::class,
            'api.url' => \Dingo\Api\Routing\UrlGenerator::class,
            'api.exception' => [\Dingo\Api\Exception\Handler::class, \Dingo\Api\Contract\Debug\ExceptionHandler::class],
        ];

        foreach ($serviceAliases as $key => $aliases) {
            foreach ((array) $aliases as $alias) {
                $this->app->alias($key, $alias);
            }
        }
    }

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


Question: // IsInGOPATH checks whether the path is inside of any GOPATH or not

func IsInGOPATH(thePath string) bool {
	for _, gopath := range GetGOPATHs() {
		if strings.Contains(thePath, filepath.Join(gopath, "src")) {
			return true
		}
	}
	return false
}

public function isLinkAllowed(string $link): bool
	{
		if (isset($this->allowedLinks[$link])) {
			return true;
		} else {
			$pos = strrpos($link, ':');
			$link = substr($link, 0, ($pos + 1));
			return isset($this->allowedLinks[$link]);
		}
	}

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


Question:
sets a boolean value to a XML Element

@param el Element to set value on it
@param key key to set
@param value value to set

public void setBoolean(Element el, String key, boolean value) {
	el.setAttribute(key, String.valueOf(value));
    }

public function updateBlock(Block $block): void
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->update('ngbm_block')
            ->set('layout_id', ':layout_id')
            ->set('depth', ':depth')
            ->set('path', ':path')
            ->set('parent_id', ':parent_id')
            ->set('placeholder', ':placeholder')
            ->set('position', ':position')
            ->set('definition_identifier', ':definition_identifier')
            ->set('view_type', ':view_type')
            ->set('item_view_type', ':item_view_type')
            ->set('name', ':name')
            ->set('translatable', ':translatable')
            ->set('main_locale', ':main_locale')
            ->set('always_available', ':always_available')
            ->set('config', ':config')
            ->where(
                $query->expr()->eq('id', ':id')
            )
            ->setParameter('id', $block->id, Type::INTEGER)
            ->setParameter('layout_id', $block->layoutId, Type::INTEGER)
            ->setParameter('depth', $block->depth, Type::STRING)
            ->setParameter('path', $block->path, Type::STRING)
            ->setParameter('parent_id', $block->parentId, Type::INTEGER)
            ->setParameter('placeholder', $block->placeholder, Type::STRING)
            ->setParameter('position', $block->position, Type::INTEGER)
            ->setParameter('definition_identifier', $block->definitionIdentifier, Type::STRING)
            ->setParameter('view_type', $block->viewType, Type::STRING)
            ->setParameter('item_view_type', $block->itemViewType, Type::STRING)
            ->setParameter('name', $block->name, Type::STRING)
            ->setParameter('translatable', $block->isTranslatable, Type::BOOLEAN)
            ->setParameter('main_locale', $block->mainLocale, Type::STRING)
            ->setParameter('always_available', $block->alwaysAvailable, Type::BOOLEAN)
            ->setParameter('config', $block->config, Type::JSON_ARRAY);

        $this->applyStatusCondition($query, $block->status);

        $query->execute();
    }

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


Question: Ownership of module is returned

def remove_module(self, module):

        with ffi.OutputString() as outerr:
            if ffi.lib.LLVMPY_RemoveModule(self, module, outerr):
                raise RuntimeError(str(outerr))
        self._modules.remove(module)
        module._owned = False

def handle(self, *args, **options):

        self.options = options
        delete = False

        try:
            # blank line
            self.stdout.write('\r\n')
            # store verbosity level in instance attribute for later use
            self.verbosity = int(self.options.get('verbosity'))

            self.verbose('disabling signals (notififcations, websocket alerts)')
            pause_disconnectable_signals()

            self.check_status_mapping()
            self.retrieve_nodes()
            self.extract_users()
            self.import_admins()
            self.import_users()
            self.import_nodes()
            self.check_deleted_nodes()
            self.import_devices()
            self.import_interfaces()
            self.import_links()
            self.check_deleted_links()
            self.import_contacts()

            self.confirm_operation_completed()

            resume_disconnectable_signals()
            self.verbose('re-enabling signals (notififcations, websocket alerts)')

        except KeyboardInterrupt:
            self.message('\n\nOperation cancelled...')
            delete = True
        except Exception as e:
            tb = traceback.format_exc()
            delete = True
            # rollback database transaction
            transaction.rollback()
            self.message('Got exception:\n\n%s' % tb)
            error('import_old_nodeshot: %s' % e)

        if delete:
            self.delete_imported_data()

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


Question:
Requests path supplied as argument and returns true if the request was a success.
 For checking if the current authentication is valid.

 @param [String] token_verify_path a path that requires authentication
 @return [Boolean]

def authentication_ok?(token_verify_path)
      return false unless token
      return false unless token['access_token']
      return false unless token_verify_path

      final_path = token_verify_path.gsub(/\:access\_token/, token['access_token'])
      debug { "Requesting user info from #{final_path}" }
      request(path: final_path)
      true
    rescue => ex
      error { "Authentication verification exception" }
      error { ex }
      false
    end

def authenticate( username, password, hours = nil )

      @username, @password, @hours = username, password, hours

      if username and password

         @ticket = nil
         if @hours
            xmlRequestData = toXML( :hours, @hours )
            sendRequest( :authenticate, xmlRequestData )
         else
            sendRequest( :authenticate )
         end

         @userid = getResponseValue( :userid )
         return self if @chainAPIcalls
         return @ticket, @userid

      elsif username or password
         raise "authenticate: missing username or password"
      elsif @ticket
         raise "authenticate: #{username} is already authenticated"
      end
   end

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


Question: // NewSharedInformer creates a new instance for the listwatcher.

func NewSharedInformer(lw ListerWatcher, objType runtime.Object, resyncPeriod time.Duration) SharedInformer {
	return NewSharedIndexInformer(lw, objType, resyncPeriod, Indexers{})
}

public void add(Collection<NrqlAlertCondition> conditions)
    {
        for(NrqlAlertCondition condition : conditions)
            this.conditions.put(condition.getId(), condition);
    }

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


Question:
Set the time at which the resource was last modified.

@param lastModified the lastModified value to set
@return the CertificateListHeaders object itself.

public CertificateListHeaders withLastModified(DateTime lastModified) {
        if (lastModified == null) {
            this.lastModified = null;
        } else {
            this.lastModified = new DateTimeRfc1123(lastModified);
        }
        return this;
    }

public function httpOptions(RequestInterface $request, ResponseInterface $response)
    {
        $methods = $this->server->getAllowedMethods($request->getPath());

        $response->setHeader('Allow', strtoupper(implode(', ', $methods)));
        $features = ['1', '3', 'extended-mkcol'];

        foreach ($this->server->getPlugins() as $plugin) {
            $features = array_merge($features, $plugin->getFeatures());
        }

        $response->setHeader('DAV', implode(', ', $features));
        $response->setHeader('MS-Author-Via', 'DAV');
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', '0');
        $response->setStatus(200);

        // Sending back false will interrupt the event chain and tell the server
        // we've handled this method.
        return false;
    }

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


Question: Return string representation for VCF

def serialize(self):
        """"""
        if self.mate_chrom is None:
            remote_tag = "."
        else:
            if self.within_main_assembly:
                mate_chrom = self.mate_chrom
            else:
                mate_chrom = "<{}>".format(self.mate_chrom)
            tpl = {FORWARD: "[{}:{}[", REVERSE: "]{}:{}]"}[self.mate_orientation]
            remote_tag = tpl.format(mate_chrom, self.mate_pos)
        if self.orientation == FORWARD:
            return remote_tag + self.sequence
        else:
            return self.sequence + remote_tag

@Override
    public void setValueFromObject(Object anObject) {
        if ((anObject!=null) && (value==null)) {
            if(anObject instanceof QualifiedName) {
                setValue((QualifiedName)anObject);
            } else if (anObject instanceof org.openprovenance.prov.model.LangString) {
                setValue((org.openprovenance.prov.model.LangString)anObject);
            } else if (anObject instanceof byte[]) {
                setValueFromObject((byte[]) anObject);
            } else if (anObject instanceof org.w3c.dom.Node) {
                setValueFromObject((org.w3c.dom.Node)anObject);
            } else {
                setValue(anObject.toString());
            }
        }

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


Question: Reed-Solomon main decoding function

def rs_correct_msg(msg_in, nsym, fcr=0, generator=2, erase_pos=None, only_erasures=False):
    ''''''
    global field_charac
    if len(msg_in) > field_charac:
        # Note that it is in fact possible to encode/decode messages that are longer than field_charac, but because this will be above the field, this will generate more error positions during Chien Search than it should, because this will generate duplicate values, which should normally be prevented thank's to the prime polynomial reduction (eg, because it can't discriminate between error at position 1 or 256, both being exactly equal under galois field 2^8). So it's really not advised to do it, but it's possible (but then you're not guaranted to be able to correct any error/erasure on symbols with a position above the length of field_charac -- if you really need a bigger message without chunking, then you should better enlarge c_exp so that you get a bigger field).
        raise ValueError("Message is too long (%i when max is %i)" % (len(msg_in), field_charac))

    msg_out = bytearray(msg_in)     # copy of message
    # erasures: set them to null bytes for easier decoding (but this is not necessary, they will be corrected anyway, but debugging will be easier with null bytes because the error locator polynomial values will only depend on the errors locations, not their values)
    if erase_pos is None:
        erase_pos = []
    else:
        for e_pos in erase_pos:
            msg_out[e_pos] = 0
    # check if there are too many erasures to correct (beyond the Singleton bound)
    if len(erase_pos) > nsym: raise ReedSolomonError("Too many erasures to correct")
    # prepare the syndrome polynomial using only errors (ie: errors = characters that were either replaced by null byte or changed to another character, but we don't know their positions)
    synd = rs_calc_syndromes(msg_out, nsym, fcr, generator)
    # check if there's any error/erasure in the input codeword. If not (all syndromes coefficients are 0), then just return the codeword as-is.
    if max(synd) == 0:
        return msg_out[:-nsym], msg_out[-nsym:]  # no errors

    # Find errors locations
    if only_erasures:
        err_pos = []
    else:
        # compute the Forney syndromes, which hide the erasures from the original syndrome (so that BM will just have to deal with errors, not erasures)
        fsynd = rs_forney_syndromes(synd, erase_pos, len(msg_out), generator)
        # compute the error locator polynomial using Berlekamp-Massey
        err_loc = rs_find_error_locator(fsynd, nsym, erase_count=len(erase_pos))
        # locate the message errors using Chien search (or bruteforce search)
        err_pos = rs_find_errors(err_loc[::-1], len(msg_out), generator)
        if err_pos is None:
            raise ReedSolomonError("Could not locate error")

    # Find errors values and apply them to correct the message
    # compute errata evaluator and errata magnitude polynomials, then correct errors and erasures
    msg_out = rs_correct_errata(msg_out, synd, (erase_pos + err_pos), fcr, generator) # note that we here use the original syndrome, not the forney syndrome (because we will correct both errors and erasures, so we need the full syndrome)
    # check if the final message is fully repaired
    synd = rs_calc_syndromes(msg_out, nsym, fcr, generator)
    if max(synd) > 0:
        raise ReedSolomonError("Could not correct message")
    # return the successfully decoded message
    return msg_out[:-nsym], msg_out[-nsym:]

func (row Row) WriteTo(writer io.Writer) (err error) {
	encoded, err := encodeRow(row)
	if err != nil {
		return fmt.Errorf("WriteTo encoding error: %v", err)
	}
	return WriteMessage(writer, encoded)
}

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


Question:
Creates an extraction file (keeping only markers on autosomes).

    :param bim_filename: the name of the BIM file.
    :param out_prefix: the prefix for the output file.

    :type bim_filename: str
    :type out_prefix: str

def create_extraction_file(bim_filename, out_prefix):

    o_file = None
    try:
        o_file = open(out_prefix + ".to_extract", "w")
    except IOError:
        raise ProgramError("{}: cannot write file".format(
            out_prefix + ".to_extract"
        ))

    # Reading the BIM file and extracts only the markers on autosome
    autosomes = set(map(str, range(1, 23)))
    nb_markers = 0
    header = dict(zip(["chrom", "name", "cm", "pos", "a1", "a2"], range(6)))
    with open(bim_filename, "r") as i_file:
        for line in i_file:
            row = line.rstrip("\r\n").split()
            if row[header["chrom"]] in autosomes:
                print >>o_file, row[header["name"]]
                nb_markers += 1

    # Closing the file
    o_file.close()

    logger.info("  - {:,d} markers will be used for contamination "
                "estimation".format(nb_markers))

def bip32(self, s):

        s = parseable_str(s)
        return self.bip32_prv(s) or self.bip32_pub(s)

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


Question:
Returns a result set from the given search parameters.

@todo rearrange start and limit params to reflect DataObject

@param array $searchParams
@param array|bool|string $sort
@param array|bool|string $limit
@return DataList
@throws Exception

public function getResults($searchParams, $sort = false, $limit = false)
    {
        $searchParams = array_filter((array)$searchParams, array($this, 'clearEmptySearchFields'));

        // getQuery actually returns a DataList
        return $this->getQuery($searchParams, $sort, $limit);
    }

public function match($pathinfo)
    {
        $routes = array();
        $this->debug(sprintf('match: Matching %s', $pathinfo));

        foreach ($this->matchers as $matcher) {
            try {
                $routes = $matcher->match($pathinfo);
                break;
            } catch (ResourceNotFoundException $e) {
            } catch (MethodNotAllowedException $e) {
            }
        }

        if (!isset($routes['_route']) || !isset($routes['_controller'])) {
            $mesg = 'match: No Routes Found.';
            $this->alert($mesg);
            throw new RoutingException($mesg);
        }

        $this->debug(sprintf('match: Route matched %s', $routes['_route']));

        return($routes);
    }

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


Question:
Deletes a user API key associated with the current user.

@param id The id of the API key to delete.
@return A {@link Task} that completes when the API key is deleted.

@Override
  public Task<Void> deleteApiKey(@NonNull final ObjectId id) {
    return dispatcher.dispatchTask(new Callable<Void>() {
      @Override
      public Void call() {
        deleteApiKeyInternal(id);
        return null;
      }
    });
  }

func (u *Client) RevokeToken(accessToken string) error {
	segments := strings.Split(accessToken, ".")

	if len(segments) < 2 {
		return errors.New("access token missing segments")
	}

	jsonPayload, err := base64.RawURLEncoding.DecodeString(segments[1])

	if err != nil {
		return errors.New("could not base64 decode token payload")
	}

	payload := make(map[string]interface{})
	json.Unmarshal(jsonPayload, &payload)
	jti, ok := payload["jti"].(string)

	if !ok {
		return errors.New("could not parse jti from payload")
	}

	request, err := http.NewRequest(http.MethodDelete, u.AuthURL+"/oauth/token/revoke/"+jti, nil)
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+accessToken)
	resp, err := u.Client.Do(request)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= http.StatusBadRequest {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		return fmt.Errorf("Received HTTP %d error while revoking token from auth server: %q", resp.StatusCode, body)
	}

	return nil
}

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


Question:
Get url of user's avatar or null if it is not set

@return string|null

public function getAvatar(){
		$result = null;
		if (isset($this->userInfo[$this->socialFieldsMap['avatar']])) {
			$result = $this->userInfo[$this->socialFieldsMap['avatar']];
			}
		return $result;
		}

public function setOption($option, $value)
        {
            $option = strval($option);
            switch($option) {
                case self::OPTION_DEFAULT_IMAGE:
                    switch($value) {
                        case self::DEFAULT_404:
                        case self::DEFAULT_IDENTICON:
                        case self::DEFAULT_MM:
                        case self::DEFAULT_MONSTERID:
                        case self::DEFAULT_WAVATAR:
                        case self::DEFAULT_RETRO:
                            $this->options[$option] = $value;
                            break;
                        default:
                            throw new \Thin\Exception(get_class() . ": " . __METHOD__ . ": unknown default image type '{$value}'.");
                    }
                    break;
                case self::OPTION_EMAIL:
                    $this->options[$option] = strval($value);
                    break;
                case self::OPTION_RATING:
                    switch($value) {
                        case self::RATING_G:
                        case self::RATING_PG:
                        case self::RATING_R:
                        case self::RATING_X:
                            $this->options[$option] = $value;
                            break;
                        default:
                            throw new \Thin\Exception(get_class() . ": " . __METHOD__ . ": unknown rating '{$value}'.");
                    }
                    break;
                case self::OPTION_IMAGE_SIZE:
                    $this->options[$option] = intval($value);
                    break;
                case self::OPTION_HTTPS:
                    $this->options[$option] =(boolean) $value;
                    break;
                default:
                    throw new \Thin\Exception(get_class() . ": " . __METHOD__ . ": unknown option '{$option}'.");
            }

            return $this;
        }

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


Question: set the render window size

def window_size(self, window_size):

        BasePlotter.window_size.fset(self, window_size)
        self.app_window.setBaseSize(*window_size)

protected void bindNode(final Node node) {
        node.scaleXProperty().bind(bindWidth());
        node.scaleYProperty().bind(bindHeight());
    }

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


Question:
Uses the given serializer and transformer to transform $this into an array of the expected format.
@param ResourceInterface $resource
@param string $serializer
@return string

public static function toJson(ResourceAbstract $resource, $options = 0, $serializer = DataArraySerializer::class)
    {
        $manager = new Manager();
        $manager->setSerializer(new $serializer());
        return $manager->createData($resource)->toJson($options);
    }

@Override
    public boolean regiserService(NaviRpcExporter exporter) {
        Class<?> interf = exporter.getServiceInterface();
        Object bean = exporter.getServiceBean();
        List<AppIdToken> appIdTokens = getAuthIfPossible(bean);
        String interfSimpleName = interf.getSimpleName();
        try {
            exporters.put(exporter.getName(), exporter);
            if (interf.isAssignableFrom(bean.getClass())) {
                Method[] ms = ReflectionUtil.getAllInstanceMethods(bean.getClass());
                for (Method m : ms) {
                    if (methodResolver.isSupport(m)) {
                        MethodWrapper methodWrapper = new MethodWrapper(interf.getName(),
                                m.getName(), MethodUtil.getArgsTypeName(m));
                        MethodWrapper defaultMethodWrapper = new MethodWrapper(interf.getName(),
                                m.getName(), StringUtil.EMPTY);
                        String key = methodWrapper.toString();
                        MethodDescriptor<String> desc = new MethodDescriptor<String>();
                        desc.setServiceId(key).setMethod(m).setTarget(bean)
                                .setArgumentClass(m.getParameterTypes())
                                .setReturnClass(m.getReturnType()).setInterfClass(interf).setAppIdTokens(appIdTokens);
                        serviceRegistry.addServiceDescriptor(key, desc);
                        serviceRegistry.addServiceDescriptor(defaultMethodWrapper.toString(), desc);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(String.format(
                                    "Register service key=[%s], %s %s#%s(%s) successfully", key, m
                                            .getReturnType().getSimpleName(), interf.getName(), m
                                            .getName(), StringUtil.toString4Array(m
                                            .getParameterTypes())));
                        }
                    }
                }
                LOG.info("Find rpc service configured, interface is "
                        + interfSimpleName + " , implementation is "
                        + AopUtils.getTargetClass(bean).getName());
                return true;
            } else {
                LOG.error("The interface " + interfSimpleName + " is not compatible with the bean "
                        + bean.getClass().getName());
            }
        } catch (Exception e) {
            LOG.error(
                    "The interface " + interfSimpleName + " is configured wrongly."
                            + e.getMessage(), e);
        }
        return false;
    }

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


Question:
encodeParameter

@param string $type
@param mixed $param
@return string

public function encodeParameter($type, $param)
    {
        if (!is_string($type)) {
            throw new InvalidArgumentException('The type to encodeParameter must be string.');
        }
        return $this->encodeParameters([$type], [$param]);
    }

private KeyToken key(Token prev) {

    // Store keys as normal Strings; we don't want keys to contain spans.
    StringBuilder sb = new StringBuilder();

    // Consume the opening '{'.
    consume();
    while ((curChar >= 'a' && curChar <= 'z') || curChar == '_') {
      sb.append(curChar);
      consume();
    }

    // Consume the closing '}'.
    if (curChar != '}') {
      throw new IllegalArgumentException("Unexpected character '" + curChar
          + "'; expecting lower case a-z, '_', or '}'");
    }
    consume();

    // Disallow empty keys: {}.
    if (sb.length() == 0) {
      throw new IllegalArgumentException("Empty key: {}");
    }

    String key = sb.toString();
    keys.add(key);
    return new KeyToken(prev, key);
  }

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


Question: return all found modules at modulepath (eg, foo.bar) including modulepath module

def get_modules(modulepath):
    """"""
    m = importlib.import_module(modulepath)
    mpath = m.__file__
    ret = set([m])

    if "__init__." in mpath.lower():
        mpath = os.path.dirname(mpath)

        # https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules
        for module_info in pkgutil.iter_modules([mpath]):
            submodulepath = ".".join([modulepath, module_info[1]])
            if module_info[2]:
                # module is a package
                submodules = get_modules(submodulepath)
                ret.update(submodules)
            else:
                ret.add(importlib.import_module(submodulepath))

    return ret

def find_path(self, test_function=None, on_targets=False):

        assert self.has_referential_domain(), "need context set"

        if not test_function:
            test_function = lambda x, y: True

        def find_path_inner(part, prefix):
            name, structure = part
            if test_function(name, structure):
                yield prefix + [name]
            if isinstance(structure, DictCell):
                for sub_structure in structure:
                    for prefix2 in find_path_inner(sub_structure,\
                            prefix[:] + [name]):
                        yield prefix2

        prefix = []
        if on_targets:
            # apply search to the first target
            results = []
            for _, instance in self.iter_singleton_referents():
                for part in instance:
                    for entry in find_path_inner(part, prefix[:]):
                        results.append(['target'] + entry)
                while results:
                    yield results.pop()
                break # only use first instance
        else:
            # apply search to self
            for part in self:
                for entry in find_path_inner(part, prefix[:]):
                    yield entry

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


Question:
/*
(non-Javadoc)

@see com.ibm.ws.objectManager.InternalTransaction#prePrepare(com.ibm.ws.objectManager.Transaction)

void prePrepare(Transaction transaction)
                    throws ObjectManagerException
    {
        throw new InvalidStateException(this, InternalTransaction.stateTerminated, InternalTransaction.stateNames[InternalTransaction.stateTerminated]);
    }

def execute_transaction(conn, statements: Iterable):
    """"""

    with conn:
        with conn.cursor() as cursor:
            for statement in statements:
                cursor.execute(statement)
        conn.commit()

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


Question:
Gets the key length of the given {@link PublicKey}.

@param publicKey
the public key
@return the key length

public static int getKeyLength(final PublicKey publicKey)
	{
		int length = -1;
		if (publicKey == null)
		{
			return length;
		}
		if (publicKey instanceof RSAPublicKey)
		{
			length = ((RSAPublicKey)publicKey).getModulus().bitLength();
		}
		if (publicKey instanceof DSAPublicKey)
		{
			length = ((DSAPublicKey)publicKey).getParams().getP().bitLength();
		}
		if (publicKey instanceof ECPublicKey)
		{
			length = ((ECPublicKey)publicKey).getParams().getCurve().getField().getFieldSize();
		}

		return length;
	}

func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
	prf := hmac.New(h, password)
	hashLen := prf.Size()
	numBlocks := (keyLen + hashLen - 1) / hashLen

	var buf [4]byte
	dk := make([]byte, 0, numBlocks*hashLen)
	U := make([]byte, hashLen)
	for block := 1; block <= numBlocks; block++ {
		// N.B.: || means concatenation, ^ means XOR
		// for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
		// U_1 = PRF(password, salt || uint(i))
		prf.Reset()
		prf.Write(salt)
		buf[0] = byte(block >> 24)
		buf[1] = byte(block >> 16)
		buf[2] = byte(block >> 8)
		buf[3] = byte(block)
		prf.Write(buf[:4])
		dk = prf.Sum(dk)
		T := dk[len(dk)-hashLen:]
		copy(U, T)

		// U_n = PRF(password, U_(n-1))
		for n := 2; n <= iter; n++ {
			prf.Reset()
			prf.Write(U)
			U = U[:0]
			U = prf.Sum(U)
			for x := range U {
				T[x] ^= U[x]
			}
		}
	}
	return dk[:keyLen]
}

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


Question:
Validate aa-profile-mode settings is disable, enforce, or complain.

        :return ctxt: Dictionary of the apparmor profile or None

def _determine_ctxt(self):

        if config('aa-profile-mode') in ['disable', 'enforce', 'complain']:
            ctxt = {'aa_profile_mode': config('aa-profile-mode'),
                    'ubuntu_release': lsb_release()['DISTRIB_RELEASE']}
            if self.aa_profile:
                ctxt['aa_profile'] = self.aa_profile
        else:
            ctxt = None
        return ctxt

def save_config(self):
        """"""
        self.config_section['match_fuzzy'] = self.model_completer.match_fuzzy
        self.config_section['enable_vi_bindings'] = self.enable_vi_bindings
        self.config_section['show_completion_columns'] = \
            self.show_completion_columns
        self.config_section['show_help'] = self.show_help
        self.config_section['theme'] = self.theme
        self.config_obj.write()

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


Question:
Convert percent to real values

@param percent {Number} X in percent
@returns {Number} X in real

function (percent) {
            var min = this.options.min,
                max = this.options.max,
                min_decimals = min.toString().split(".")[1],
                max_decimals = max.toString().split(".")[1],
                min_length, max_length,
                avg_decimals = 0,
                abs = 0;

            if (percent === 0) {
                return this.options.min;
            }
            if (percent === 100) {
                return this.options.max;
            }

            if (min_decimals) {
                min_length = min_decimals.length;
                avg_decimals = min_length;
            }
            if (max_decimals) {
                max_length = max_decimals.length;
                avg_decimals = max_length;
            }
            if (min_length && max_length) {
                avg_decimals = (min_length >= max_length) ? min_length : max_length;
            }

            if (min < 0) {
                abs = Math.abs(min);
                min = +(min + abs).toFixed(avg_decimals);
                max = +(max + abs).toFixed(avg_decimals);
            }

            var number = ((max - min) / 100 * percent) + min,
                string = this.options.step.toString().split(".")[1],
                result;

            if (string) {
                number = +number.toFixed(string.length);
            } else {
                number = number / this.options.step;
                number = number * this.options.step;

                number = +number.toFixed(0);
            }

            if (abs) {
                number -= abs;
            }

            if (string) {
                result = +number.toFixed(string.length);
            } else {
                result = this.toFixed(number);
            }

            if (result < this.options.min) {
                result = this.options.min;
            } else if (result > this.options.max) {
                result = this.options.max;
            }

            return result;
        }

def install_money_getter attribute, options={}

      define_method :"#{attribute}_with_exchange_typecasting" do
        currency = evaluate_money_option(options[:currency]) if options[:currency]

        test_for_currency_error(currency, attribute)

        time     = evaluate_money_option(options[:at]) if options[:at]

        if value = send(:"#{attribute}_without_exchange_typecasting")
          Exchange::Money.new(value) do |c|
            c.currency = currency
            c.time     = time if time
          end
        end
      end
      exchange_typecasting_alias_method_chain attribute

    end

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


Question:
Get the upload field name

@param null $field
@return mixed|null

public function getUploadFieldName($field = null)
    {
        if (!is_null($field)) {
            return $field;
        }

        $imagesFields = $this->getDefinedUploadFields();
        $fieldKey = array_first(array_keys($imagesFields));

        // return first field name
        return is_int($fieldKey)
            ? $imagesFields[$fieldKey]
            : $fieldKey;
    }

public function formatAttribute($attributes = [])
    {
        $attributes = $attributes ?: $this->attributes;

        if ($this->hasFile()) {
            $attributes['enctype'] = 'multipart/form-data';
        }

        $html = [];
        foreach ($attributes as $key => $val) {
            $html[] = "$key=\"$val\"";
        }

        return implode(' ', $html) ?: '';
    }

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


Question:
@param array $data

@return array

public function setParentGridData($data = [])
    {
        $parentGridData = [];
        foreach ($data as $key => $value) {
            $parentGridData['parentgrid_' . $key] = $value;
        }
        return $parentGridData;
    }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question:
@param $question

@return Relationship

public function answers($question)
    {
        $answers = app(AnswerRepository::class);

        return new Relationship(new Collection($answers->all($question), app(AnswerSerializer::class)));
    }

public function createPersonalSiteEnque(){
        $qry = new InvokePostMethodQuery(
            $this->getResourcePath(),
            "createpersonalsiteenque",
            array(false)
        );
        $this->getContext()->addQuery($qry);
    }

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


Question:
List all of the wireless interfaces

    CLI Example:

        salt minion iwtools.list_interfaces

def list_interfaces(style=None):
    '''

    '''
    ret = {}
    tmp = None
    iface = None
    out = __salt__['cmd.run']('iwconfig')
    for line in out.splitlines():
        if not line:
            continue
        if 'no wireless extensions' in line:
            continue
        comps = line.strip().split('  ')
        if not line.startswith(' '):
            if tmp is not None:
                ret[iface] = tmp.copy()
            iface = comps.pop(0)
            tmp = {'extra': []}
        for item in comps:
            if ':' in item:
                parts = item.split(':')
                key = parts[0].strip()
                value = parts[1].strip()
                if key == 'ESSID':
                    value = value.lstrip('"').rstrip('"')
                tmp[key] = value
            elif '=' in item:
                parts = item.split('=')
                tmp[parts[0].strip()] = parts[1].strip()
            else:
                tmp['extra'].append(item)

    ret[iface] = tmp.copy()

    if style == 'list':
        return ret.keys()

    return ret

def iter_shortcuts():
    """"""
    for context_name, keystr in CONF.items('shortcuts'):
        context, name = context_name.split("/", 1)
        yield context, name, keystr

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


Question:
将一个地址字符串解析为多个地址<br>
地址间使用" "、","、";"分隔

@param address 地址字符串
@param charset 编码
@return 地址列表

public static InternetAddress[] parseAddress(String address, Charset charset) {
		InternetAddress[] addresses;
		try {
			addresses = InternetAddress.parse(address);
		} catch (AddressException e) {
			throw new MailException(e);
		}
		//编码用户名
		if (ArrayUtil.isNotEmpty(addresses)) {
			for (InternetAddress internetAddress : addresses) {
				try {
					internetAddress.setPersonal(internetAddress.getPersonal(), charset.name());
				} catch (UnsupportedEncodingException e) {
					throw new MailException(e);
				}
			}
		}

		return addresses;
	}

private static function _doResponse($type, $objects, $echoResponse, $format) {
        $ret = array();
        $ret['status'] = $type;
        if (is_array($objects)) {
            foreach ($objects as $k => $v) {
                $ret[$k] = $v;
            }
        } else {
            $ret[] = $objects;
        }

        switch ($format) {
            case 'xml':
                require_once 'XML/Serializer.php';
                $options = array(
                    "indent" => "    ",
                    "linebreak" => "\n",
                    "typeHints" => false,
                    "addDecl" => true,
                    "encoding" => "UTF-8",
                    "rootName" => "data",
//					"rootAttributes"  => array("version" => "0.91"),
                    "defaultTagName" => "item",
                    "attributesArray" => "_attributes"
                );

                $serializer = new \XML_Serializer($options);

                $rc = $serializer->serialize($ret);
                if ($rc !== TRUE) {

                }
                $ret = $serializer->getSerializedData();
                break;

            case 'json':
            default:
                $ret = json_encode($ret);
                break;
        }

        if ($echoResponse) {
            echo $ret;
        }
        return $ret;
    }

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


Question:
returns the security object of a database

@link http://wiki.apache.org/couchdb/Security_Features_Overview
@return stdClass security object of the database
@throws CouchException

public function getSecurity()
	{
		$dbname = $this->client->getDatabaseName();
		$raw = $this->client->query(
				"GET", "/" . $dbname . "/_security"
		);
		$resp = Couch::parseRawResponse($raw);
		if ($resp['status_code'] != 200) {
			throw new CouchException($raw);
		}
		if (!property_exists($resp['body'], "admins")) {
			$resp["body"]->admins = new stdClass();
			$resp["body"]->admins->names = array();
			$resp["body"]->admins->roles = array();
			$resp["body"]->readers = new stdClass();
			$resp["body"]->readers->names = array();
			$resp["body"]->readers->roles = array();
		}
		return $resp['body'];
	}

public static function agree_site_policy() {
        global $CFG, $DB, $USER;

        $warnings = array();

        $context = context_system::instance();
        try {
            // We expect an exception here since the user didn't agree the site policy yet.
            self::validate_context($context);
        } catch (Exception $e) {
            // We are expecting only a sitepolicynotagreed exception.
            if (!($e instanceof moodle_exception) or $e->errorcode != 'sitepolicynotagreed') {
                // In case we receive a different exception, throw it.
                throw $e;
            }
        }

        $manager = new \core_privacy\local\sitepolicy\manager();
        if (!empty($USER->policyagreed)) {
            $status = false;
            $warnings[] = array(
                'item' => 'user',
                'itemid' => $USER->id,
                'warningcode' => 'alreadyagreed',
                'message' => 'The user already agreed the site policy.'
            );
        } else if (!$manager->is_defined()) {
            $status = false;
            $warnings[] = array(
                'item' => 'user',
                'itemid' => $USER->id,
                'warningcode' => 'nositepolicy',
                'message' => 'The site does not have a site policy configured.'
            );
        } else {
            $status = $manager->accept();
        }

        $result = array();
        $result['status'] = $status;
        $result['warnings'] = $warnings;
        return $result;
    }

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


Question:
Determine if the sidebar's footer is visible.

@return boolean

public function showFooter()
    {
        // Overridden by permissions
        if (!$this->checkPermission('footer')) {
            return false;
        }

        // Overridden by conditionals
        if (!$this->isObjDeletable() && !$this->isObjResettable() &&!$this->isObjRevisionable()) {
            return false;
        }

        return $this->showFooter;
    }

private static function search($postType, array $details)
    {
        $s = isset($_GET['post_type']) ? $_GET['post_type'] : false;

        if($s === $postType && is_search())
        {
            self::loadController($details);
            exit;
        }
    }

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


Question:
Determine whether attributes are mutations
and should be transformed back. It is considered
a mutation only when the attributes' keys
and mutations keys match.

@param  array  $attributes
@return boolean

public function shouldMutate(array $attributes)
    {
        $grammar = $this->getQuery()->getGrammar();
        $attributes = array_map([$grammar, 'cropLabelIdentifier'], array_keys($attributes));
        $mutations = array_keys($this->mutations);

        $intersect = array_intersect($attributes, $mutations);

        return ! empty($intersect);
    }

public function mergeHeadData($data)
	{
		if (empty($data) || !is_array($data))
		{
			return;
		}

		$this->title = (isset($data['title']) && !empty($data['title']) && !stristr($this->title, $data['title']))
			? $this->title . $data['title']
			: $this->title;
		$this->description = (isset($data['description']) && !empty($data['description']) && !stristr($this->description, $data['description']))
			? $this->description . $data['description']
			: $this->description;
		$this->link = (isset($data['link'])) ? $data['link'] : $this->link;

		if (isset($data['metaTags']))
		{
			foreach ($data['metaTags'] as $type1 => $data1)
			{
				$booldog = $type1 == 'http-equiv' ? true : false;
				foreach ($data1 as $name2 => $data2)
				{
					$this->setMetaData($name2, $data2, $booldog);
				}
			}
		}

		$this->_links = (isset($data['links']) && !empty($data['links']) && is_array($data['links']))
			? array_unique(array_merge($this->_links, $data['links']))
			: $this->_links;

		$this->_styleSheets = (isset($data['styleSheets']) && !empty($data['styleSheets']) && is_array($data['styleSheets']))
			? array_merge($this->_styleSheets, $data['styleSheets'])
			: $this->_styleSheets;

		if (isset($data['style']))
		{
			foreach ($data['style'] as $type => $stdata)
			{
				if (!isset($this->_style[strtolower($type)]) || !stristr($this->_style[strtolower($type)], $stdata))
				{
					$this->addStyleDeclaration($stdata, $type);
				}
			}
		}

		$this->_scripts = (isset($data['scripts']) && !empty($data['scripts']) && is_array($data['scripts']))
			? array_merge($this->_scripts, $data['scripts'])
			: $this->_scripts;

		if (isset($data['script']))
		{
			foreach ($data['script'] as $type => $sdata)
			{
				if (!isset($this->_script[strtolower($type)]) || !stristr($this->_script[strtolower($type)], $sdata))
				{
					$this->addScriptDeclaration($sdata, $type);
				}
			}
		}

		$this->_custom = (isset($data['custom']) && !empty($data['custom']) && is_array($data['custom']))
			? array_unique(array_merge($this->_custom, $data['custom']))
			: $this->_custom;

		return $this;
	}

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


Question:
Exactly like its name, this function starts webpack, runs it and resolves
@param  {Object} webpackConfig webpack configuration
@return {Promise}               the buid will finish, or reject

function createSingleCompiler(webpackConfig: WebpackCompiler): Promise<any> {
  return new Promise((resolve, reject) => {
    try {
      webpack(webpackConfig, (err, stats) => {
        if (err || stats.hasErrors()) {
          debug(err);
          return reject(err);
        }

        return resolve();
      });
    } catch (e) {
      return reject(e);
    }
  });
}

def match(self, request, service):

		uri = self.normalize_uri(request.path())

		if request.session().protocol() not in self.protocols:
			return

		if request.method() not in self.methods:
			return

		if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
			return

		if self.ports and int(request.session().server_address().port()) not in self.ports:
			return

		match_obj = self.re_pattern.match(uri)

		if not match_obj:
			return

		presenter_action = self.action
		presenter_args = self.presenter_args.copy()

		for i in range(len(self.route_args)):
			if self.route_args[i] == 'action':
				presenter_action = match_obj.group(i + 1)
			else:
				presenter_args[self.route_args[i]] = match_obj.group(i + 1)

		return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args)

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


Question:
Filters keys based on the KeyFilter
passed as the argument.

@param filter KeyFilter
@param <R>    Type
@return Set of filtered keys

public static <R> Set<R> filterAndListKeys(Iterator<R> keys, KeyFilter<R> filter) {
        Set<R> ret = new HashSet<R>();
        while (keys.hasNext()) {
            R key = keys.next();
            R filtered = filter.filter(key);
            if (filtered != null) {
                ret.add(filtered);
            }
        }
        return ret;
    }

public static SortedMap getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        SortedMap returnMap = new TreeMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value.trim());
        }
        return returnMap;
    }

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


Question:
Run the migrations.

@return void

public function up()
    {
        Schema::create(
            'taxonomy_vocabularies',
            function (Blueprint $table) {
                $table->increments('id');
                $table->string('name', 255);
                $table->string('machine_name', 255)->unique();
                $table->text('description')->nullable();
                $table->integer('hierarchy')->default(0); // 0 = disabled, 1 = single, 2 = multiple
                $table->integer('translatable')->default(1);
            }
        );

        Schema::create(
            'taxonomy_terms',
            function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('vocabulary_id');
                $table->integer('type')->default(0); // 0 = simple, 1 = category

                $table->foreign('vocabulary_id')->references('id')->on('taxonomy_vocabularies');
            }
        );

        Schema::create(
            'taxonomy_terms_data',
            function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('term_id');
                $table->unsignedInteger('language_id');
                $table->string('title', 255);
                $table->text('description')->nullable();

                $table->foreign('term_id')->references('id')->on('taxonomy_terms');
                $table->foreign('language_id')->references('id')->on('languages');
            }
        );

        Schema::create(
            'taxonomy_term_hierarchy',
            function (Blueprint $table) {
                $table->unsignedInteger('term_id');
                $table->unsignedInteger('parent_id');

                $table->foreign('term_id')->references('id')->on('taxonomy_terms');
                $table->foreign('parent_id')->references('id')->on('taxonomy_terms');

                $table->primary(['term_id', 'parent_id']);
            }
        );

        Schema::create(
            'taxonomy_content',
            function (Blueprint $table) {
                $table->unsignedInteger('term_id');
                $table->unsignedInteger('relationable_id');
                $table->string('relationable_type');

                $table->foreign('term_id')->references('id')->on('taxonomy_terms');

                $table->primary(
                    ['term_id', 'relationable_id', 'relationable_type'],
                    'taxonomy_contents_composed_primary'
                );
            }
        );
    }

func (md *RootMetadataV2) ClearForV4Migration() {
	md.WKeys = nil
	md.RKeys = nil
	md.Extra.UnresolvedWriters = nil
	md.UnresolvedReaders = nil
}

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


Question: Get list of installed templates.

def get_base_templates():
    "  "

    return sorted(filter(
                  lambda x: op.isdir(op.join(TPL_DIR, x)),
                  listdir(TPL_DIR)))

public function is_cached($tpl, $cacheId = null, $compileId = null)
    {
        return $this->isCached($this->makeTemplate($tpl, $cacheId, $compileId));
    }

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


Question: httl.properties: interceptors=httl.spi.interceptors.ExtendsInterceptor

@Reqiured
    public void setInterceptors(Interceptor[] interceptors) {
        Listener last = null;
        for (int i = interceptors.length - 1; i >= 0; i--) {
            final Interceptor current = interceptors[i];
            final Listener next = last;
            last = new Listener() {
                public void render(Context context) throws IOException, ParseException {
                    if (next == null) {
                        Listener listener = (Listener) context.get(LISTENER_KEY);
                        if (listener != null) {
                            current.render(context, listener);
                        }
                    } else {
                        current.render(context, next);
                    }
                }
            };
        }
        this.chain = last;
    }

public static function browserSupportsDHTMLType()
    {
        if ( self::$browserType === null )
        {
            self::$browserType = false;
            $userAgent = eZSys::serverVariable( 'HTTP_USER_AGENT' );
            // Opera 9.6+
            if ( strpos( $userAgent, 'Presto' ) !== false &&
                 preg_match('/Presto\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
            {
                if ( $browserInfo[1] >= 2.1 )
                    self::$browserType = 'Presto';
            }
            // IE 8.0+
            else if ( strpos( $userAgent, 'Trident' ) !== false &&
                      preg_match('/Trident\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
            {
                if ( $browserInfo[1] >= 4.0 )
                    self::$browserType = 'Trident';
            }
            // IE 6 & 7
            else if ( strpos( $userAgent, 'MSIE' ) !== false &&
                      preg_match('/MSIE[ \/]([0-9\.]+)/i', $userAgent, $browserInfo ) )
            {
                if ( $browserInfo[1] >= 6.0 )
                    self::$browserType = 'Trident';
            }
            // Firefox 3+
            else if ( strpos( $userAgent, 'Gecko' ) !== false &&
                      preg_match('/rv:([0-9\.]+)/i', $userAgent, $browserInfo ) )
            {
                if ( $browserInfo[1] >= 1.9 )
                    self::$browserType = 'Gecko';
            }
            // Safari 4+ (and Chrome)
            else if ( strpos( $userAgent, 'WebKit' ) !== false &&
                      strpos( $userAgent, 'Mobile' ) === false &&
                      strpos( $userAgent, 'Android' ) === false &&
                      strpos( $userAgent, 'iPad' ) === false &&
                      strpos( $userAgent, 'iPhone' ) === false &&
                      strpos( $userAgent, 'iPod' ) === false &&
                      preg_match('/WebKit\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
            {
                if ( $browserInfo[1] >= 528.16 )
                    self::$browserType = 'WebKit';
            }
            // iOS 5+
            else if ( strpos( $userAgent, 'AppleWebKit' ) !== false &&
                      strpos( $userAgent, 'Mobile' ) !== false &&
                      preg_match('/AppleWebKit\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
            {
                if ( $browserInfo[1] >= 534.46 )
                    self::$browserType = 'MobileWebKit';
            }
            if ( self::$browserType === false )
                eZDebug::writeNotice( 'Browser not supported: ' . $userAgent, __METHOD__ );
        }
        return self::$browserType;
    }

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


Question: // SetArn sets the Arn field's value.

func (s *ManagedPolicyDetail) SetArn(v string) *ManagedPolicyDetail {
	s.Arn = &v
	return s
}

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

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

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


Question:
// SetTLSConfig will set an SSL/TLS configuration to be used when connecting
// to an MQTT broker. Please read the official Go documentation for more
// information.

func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions {
	o.TLSConfig = t
	return o
}

public void marshall(UpdateUserSettingsRequest updateUserSettingsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(updateUserSettingsRequest.getAccountId(), ACCOUNTID_BINDING);
            protocolMarshaller.marshall(updateUserSettingsRequest.getUserId(), USERID_BINDING);
            protocolMarshaller.marshall(updateUserSettingsRequest.getUserSettings(), USERSETTINGS_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: Return a regex that matches any string in the sorted list of strings.

def regex_opt_inner(strings, open_paren):
    """"""
    close_paren = open_paren and ')' or ''
    # print strings, repr(open_paren)
    if not strings:
        # print '-> nothing left'
        return ''
    first = strings[0]
    if len(strings) == 1:
        # print '-> only 1 string'
        return open_paren + escape(first) + close_paren
    if not first:
        # print '-> first string empty'
        return open_paren + regex_opt_inner(strings[1:], '(?:') \
            + '?' + close_paren
    if len(first) == 1:
        # multiple one-char strings? make a charset
        oneletter = []
        rest = []
        for s in strings:
            if len(s) == 1:
                oneletter.append(s)
            else:
                rest.append(s)
        if len(oneletter) > 1:  # do we have more than one oneletter string?
            if rest:
                # print '-> 1-character + rest'
                return open_paren + regex_opt_inner(rest, '') + '|' \
                    + make_charset(oneletter) + close_paren
            # print '-> only 1-character'
            return open_paren + make_charset(oneletter) + close_paren
    prefix = commonprefix(strings)
    if prefix:
        plen = len(prefix)
        # we have a prefix for all strings
        # print '-> prefix:', prefix
        return open_paren + escape(prefix) \
            + regex_opt_inner([s[plen:] for s in strings], '(?:') \
            + close_paren
    # is there a suffix?
    strings_rev = [s[::-1] for s in strings]
    suffix = commonprefix(strings_rev)
    if suffix:
        slen = len(suffix)
        # print '-> suffix:', suffix[::-1]
        return open_paren \
            + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \
            + escape(suffix[::-1]) + close_paren
    # recurse on common 1-string prefixes
    # print '-> last resort'
    return open_paren + \
        '|'.join(regex_opt_inner(list(group[1]), '')
                 for group in groupby(strings, lambda s: s[0] == first[0])) \
        + close_paren

def search_links(selector)
      uri2links = {}
      search_all_links(selector).each do |link|
        target_uri = link.uri
        uri2links[target_uri.to_s] = link if same_domain? uri, target_uri
      end
      # enforcing deterministicity for testing and debugging
      uri2links.values.sort_by {|link| link.uri.to_s }
    end

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


Question: Write a spreadsheet into a xlsx file.

def wr_xlsx(fout_xlsx, data_xlsx, **kws):
    """"""
    from goatools.wr_tbl_class import WrXlsx
    # optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds
    items_str = kws.get("items", "items") if "items" not in kws else kws["items"]
    if data_xlsx:
        # Open xlsx file
        xlsxobj = WrXlsx(fout_xlsx, data_xlsx[0]._fields, **kws)
        worksheet = xlsxobj.add_worksheet()
        # Write title (optional) and headers.
        row_idx = xlsxobj.wr_title(worksheet)
        row_idx = xlsxobj.wr_hdrs(worksheet, row_idx)
        row_idx_data0 = row_idx
        # Write data
        row_idx = xlsxobj.wr_data(data_xlsx, row_idx, worksheet)
        # Close xlsx file
        xlsxobj.workbook.close()
        sys.stdout.write("  {N:>5} {ITEMS} WROTE: {FOUT}\n".format(
            N=row_idx-row_idx_data0, ITEMS=items_str, FOUT=fout_xlsx))
    else:
        sys.stdout.write("      0 {ITEMS}. NOT WRITING {FOUT}\n".format(
            ITEMS=items_str, FOUT=fout_xlsx))

def _get_format_name_loader_mapping(self):

        loader_table = self._get_common_loader_mapping()
        loader_table.update(
            {
                "excel": ExcelTableFileLoader,
                "json_lines": JsonLinesTableFileLoader,
                "markdown": MarkdownTableFileLoader,
                "mediawiki": MediaWikiTableFileLoader,
                "ssv": CsvTableFileLoader,
            }
        )

        return loader_table

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


Question: Configure the root logger.

def configure_root():
    """"""
    root_logger = logging.getLogger()

    # clear any existing handles to streams because we don't want duplicate logs
    # NOTE: we assume that any stream handles we find are to ROOT_LOG_STREAM, which is usually the case(because it is stdout). This is fine because we will be re-creating that handle. Otherwise we might be deleting a handle that won't be re-created, which could result in dropped logs.
    for hdlr in root_logger.handlers:
        if isinstance(hdlr, logging.StreamHandler):
            root_logger.removeHandler(hdlr)

    # configure the root logger
    root_logger.setLevel(ROOT_LOG_LEVEL)
    hdlr = logging.StreamHandler(ROOT_LOG_STREAM)
    formatter = colorlog.ColoredFormatter(
                        '%(purple)s%(name)-10s %(log_color)s%(levelname)-8s%(reset)s %(white)s%(message)s',
                        reset=True,
                        log_colors={
                            'DEBUG': 'cyan',
                            'INFO': 'green',
                            'WARNING': 'yellow',
                            'ERROR': 'red',
                            'CRITICAL': 'red,bg_white',
                        }
                                         )
    hdlr.setFormatter(formatter)
    root_logger.addHandler(hdlr)

func (s *CreateStageInput) SetAccessLogSettings(v *AccessLogSettings) *CreateStageInput {
	s.AccessLogSettings = v
	return s
}

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


Question: // IsLeader is part of the hooks.Context interface.

func (ctx *leadershipContext) IsLeader() (bool, error) {
	// This doesn't technically need an error return, but that feels like a
	// happy accident of the current implementation and not a reason to change
	// the interface we're implementing.
	err := ctx.ensureLeader()
	switch err {
	case nil:
		return true, nil
	case errIsMinion:
		return false, nil
	}
	return false, errors.Trace(err)
}

def leader_set(settings=None, **kwargs):
    """"""
    # Don't log secrets.
    # log("Juju leader-set '%s'" % (settings), level=DEBUG)
    cmd = ['leader-set']
    settings = settings or {}
    settings.update(kwargs)
    for k, v in settings.items():
        if v is None:
            cmd.append('{}='.format(k))
        else:
            cmd.append('{}={}'.format(k, v))
    subprocess.check_call(cmd)

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


Question:
DELETE /tracking_beacons/:tracking_beacons_id/
        Delete the :format:`tracking_beacons` with the specified :tracking_beacons_id.

def delete_tracking_beacon(self, tracking_beacons_id, **data):

        return self.delete("/tracking_beacons/{0}/".format(tracking_beacons_id), data=data)

func (meta *predicateMetadata) RemovePod(deletedPod *v1.Pod) error {
	deletedPodFullName := schedutil.GetPodFullName(deletedPod)
	if deletedPodFullName == schedutil.GetPodFullName(meta.pod) {
		return fmt.Errorf("deletedPod and meta.pod must not be the same")
	}
	meta.topologyPairsAntiAffinityPodsMap.removePod(deletedPod)
	// Delete pod from the matching affinity or anti-affinity topology pairs maps.
	meta.topologyPairsPotentialAffinityPods.removePod(deletedPod)
	meta.topologyPairsPotentialAntiAffinityPods.removePod(deletedPod)
	// All pods in the serviceAffinityMatchingPodList are in the same namespace.
	// So, if the namespace of the first one is not the same as the namespace of the
	// deletedPod, we don't need to check the list, as deletedPod isn't in the list.
	if meta.serviceAffinityInUse &&
		len(meta.serviceAffinityMatchingPodList) > 0 &&
		deletedPod.Namespace == meta.serviceAffinityMatchingPodList[0].Namespace {
		for i, pod := range meta.serviceAffinityMatchingPodList {
			if schedutil.GetPodFullName(pod) == deletedPodFullName {
				meta.serviceAffinityMatchingPodList = append(
					meta.serviceAffinityMatchingPodList[:i],
					meta.serviceAffinityMatchingPodList[i+1:]...)
				break
			}
		}
	}
	return nil
}

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


Question:
Set current phase of this task.
@param phase phase of this task

void setPhase(Phase phase){
    TaskStatus.Phase oldPhase = getPhase();
    if (oldPhase != phase){
      // sort phase started
      if (phase == TaskStatus.Phase.SORT){
        setShuffleFinishTime(JobTracker.getClock().getTime());
      } else if (phase == TaskStatus.Phase.REDUCE){
        setSortFinishTime(JobTracker.getClock().getTime());
      }
    }
    this.phase = phase;
  }

def store_pulse_jobs(pulse_job, exchange, routing_key):

    newrelic.agent.add_custom_parameter("exchange", exchange)
    newrelic.agent.add_custom_parameter("routing_key", routing_key)

    JobLoader().process_job(pulse_job)

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 AfplibPackage.GSECOL__COLOR:
				return getCOLOR();
		}
		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:
Return the array as an XML string

@param string $outer - optional output tag, used for recursion
@return string - xml string representation of the array

public function toXml(string $outer = null) : string {
        $result = '';
        foreach($this->array as $key => $value) {
            $key = self::getStringValue($key);
            if(strncmp($key, '@', 1) === 0) {

                // skip attributes
            } else {
                $encodedTag = htmlspecialchars($outer ? $outer : $key, ENT_QUOTES);
                if(is_array($value) && (count($value) > 0) && isset($value[0])) {

                    // numeric array found => child nodes
                    $x = new XArray($value);
                    $result .= $x->toXml($key);
                    unset($x);
                } else {
                    if(is_array($value)) {

                        // attribute list found
                        $attrs = '';
                        foreach($value as $attrKey => $attrValue) {
                            $attrKey = self::getStringValue($attrKey);
                            if(strncmp($attrKey, '@', 1) === 0) {
                                $attrValue = self::getStringValue($attrValue);
                                $attrs .= ' ' . htmlspecialchars(substr($attrKey, 1), ENT_QUOTES) . '="' . htmlspecialchars($attrValue, ENT_QUOTES) . '"';
                            }
                        }
                        $x = new XArray($value);
                        $result .= '<' . $encodedTag . $attrs . '>' . $x->toXml() . '</' . $encodedTag . '>';
                        unset($x);
                    } else {
                        $value = self::getStringValue($value);
                        if($encodedTag !== '#text') {
                            $result .= '<' . $encodedTag . '>' . htmlspecialchars($value, ENT_QUOTES) . '</' . $encodedTag . '>';
                        } else {
                            $result .= htmlspecialchars($value, ENT_QUOTES);
                        }
                    }
                }
            }
        }
        return $result;
    }

protected function extractPayload($model, $comments = '')
    {
        $payload = [];
        preg_match('/@payload\ (.*)\n/i', $comments, $doc);
        $isArray = false;
        if (count($doc)) {
            $namespace = str_replace('{__API__}', $model, $doc[1]);
            if (false !== strpos($namespace, '[') && false !== strpos($namespace, ']')) {
                $namespace = str_replace(']', '', str_replace('[', '', $namespace));
                $isArray = true;
            }
            $payload = $this->extractModelFields($namespace);
            $reflector = new \ReflectionClass($namespace);
            $shortName = $reflector->getShortName();
        } else {
            $namespace = $model;
            $shortName = $model;
        }

        return [$namespace, $shortName, $payload, $isArray];
    }

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


Question: // ApplyResourceChange mocks base method

func (m *MockProviderClient) ApplyResourceChange(arg0 context.Context, arg1 *tfplugin5.ApplyResourceChange_Request, arg2 ...grpc.CallOption) (*tfplugin5.ApplyResourceChange_Response, error) {
	m.ctrl.T.Helper()
	varargs := []interface{}{arg0, arg1}
	for _, a := range arg2 {
		varargs = append(varargs, a)
	}
	ret := m.ctrl.Call(m, "ApplyResourceChange", varargs...)
	ret0, _ := ret[0].(*tfplugin5.ApplyResourceChange_Response)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

public function replace(int $i, $value)
    {
        if ($this->isValidType($value) === false) {
            throw new MWrongTypeException("\$value", $this->getType(), $value);
        }

        $this->list[$i] = $value;
    }

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


Question: push current parser state (use at start of new container)

private final void push() {
    if (ptr >= stack.length) {
      // doubling here is probably overkill, but anything that needs to double more than
      // once (32 levels deep) is very atypical anyway.
      byte[] newstack = new byte[stack.length<<1];
      System.arraycopy(stack,0,newstack,0,stack.length);
      stack = newstack;
    }
    stack[ptr++] = state;
  }

def parse_header_links(self):
        """"""
        for linktype, linkinfo in self.url_connection.links.items():
            url = linkinfo["url"]
            name = u"Link: header %s" % linktype
            self.add_url(url, name=name)
        if 'Refresh' in self.headers:
            from ..htmlutil.linkparse import refresh_re
            value = self.headers['Refresh'].strip()
            mo = refresh_re.match(value)
            if mo:
                url = unicode_safe(mo.group("url"))
                name = u"Refresh: header"
                self.add_url(url, name=name)
        if 'Content-Location' in self.headers:
            url = self.headers['Content-Location'].strip()
            name = u"Content-Location: header"
            self.add_url(url, name=name)

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


Question: Manually bind a single named route to a callback. For example:  this.route('search/:query/p:num', 'search', function(query, num) { ... });

function(route, name, callback) {
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      if (typeof name === 'function') {
        callback = name;
        name = '';
      }
      if (!callback) callback = this[name];
      var router = this;
      BackboneContext.history.route(route, function(fragment) {
        var args = router._extractParameters(route, fragment);
        if (router.execute(callback, args, name) !== false) {
          router.trigger.apply(router, ['route:' + name].concat(args));
          router.trigger('route', name, args);
          BackboneContext.history.trigger('route', router, name, args);
        }
      });
      return this;
    }

public function setSearch(SearchInterface $search)
    {
        if (null !== $this->search) {
            $this->search->free();
        }
        $this->search = $search;
        $this->rewind();
    }

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


Question: Create global Config object, parse command flags

def _init():

    global config, _data_path, _allowed_config_keys

    app_dir = _get_vispy_app_dir()
    if app_dir is not None:
        _data_path = op.join(app_dir, 'data')
        _test_data_path = op.join(app_dir, 'test_data')
    else:
        _data_path = _test_data_path = None

    # All allowed config keys and the types they may have
    _allowed_config_keys = {
        'data_path': string_types,
        'default_backend': string_types,
        'gl_backend': string_types,
        'gl_debug': (bool,),
        'glir_file': string_types+file_types,
        'include_path': list,
        'logging_level': string_types,
        'qt_lib': string_types,
        'dpi': (int, type(None)),
        'profile': string_types + (type(None),),
        'audit_tests': (bool,),
        'test_data_path': string_types + (type(None),),
    }

    # Default values for all config options
    default_config_options = {
        'data_path': _data_path,
        'default_backend': '',
        'gl_backend': 'gl2',
        'gl_debug': False,
        'glir_file': '',
        'include_path': [],
        'logging_level': 'info',
        'qt_lib': 'any',
        'dpi': None,
        'profile': None,
        'audit_tests': False,
        'test_data_path': _test_data_path,
    }

    config = Config(**default_config_options)

    try:
        config.update(**_load_config())
    except Exception as err:
        raise Exception('Error while reading vispy config file "%s":\n  %s' %
                        (_get_config_fname(), err.message))
    set_log_level(config['logging_level'])

    _parse_command_line_arguments()

func (cmd *CLI) DefineInt64Flag(name string, value int64, usage string) *int64 {
	p := new(int64)
	cmd.DefineInt64FlagVar(p, name, value, usage)
	return p
}

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


Question: This tries to unify In([1]) with GT(1) -> GTE(1)

function makeOrWithInAndRange(inSet, rangeSet) {
	if(rangeSet instanceof is.Or) {
		var firstResult = makeOrWithInAndRange(inSet, rangeSet.values[0]);
		if( !(firstResult instanceof is.Or) ) {
			return set.union(firstResult, rangeSet.values[1]);
		}
		var secondResult = makeOrWithInAndRange(inSet, rangeSet.values[1]);
		if( !(secondResult instanceof is.Or) ) {
			return set.union(secondResult, rangeSet.values[0]);
		}
		return makeOr([inSet, rangeSet]);
	} else {
		if(rangeSet instanceof is.GreaterThan) {
			return combineValueWithRangeCheck(inSet, rangeSet, is.GreaterThanEqual);
		}
		if(rangeSet instanceof is.LessThan) {
			return combineValueWithRangeCheck(inSet, rangeSet, is.LessThanEqual);
		}
		return makeOr([inSet, rangeSet]);
	}
}

def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_interface = ET.Element("fcoe_get_interface")
        config = fcoe_get_interface
        output = ET.SubElement(fcoe_get_interface, "output")
        fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
        fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
        fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
        fcoe_intf_port_type = ET.SubElement(fcoe_intf_list, "fcoe-intf-port-type")
        fcoe_intf_port_type.text = kwargs.pop('fcoe_intf_port_type')

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

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


Question: // name is '/'-separated, not filepath.Separator.

func serveFile(ctx context.Context, fs http.FileSystem, name string, redirect bool, showList bool, gzip bool) (string, int) {
	// redirect .../index.html to .../
	// can't use Redirect() because that would make the path absolute,
	// which would be a problem running under StripPrefix
	if strings.HasSuffix(ctx.Request().URL.Path, indexPage) {
		localRedirect(ctx, "./")
		return "", http.StatusMovedPermanently
	}

	f, err := fs.Open(name)
	if err != nil {
		return err.Error(), 404
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		return err.Error(), 404
	}

	if redirect {
		// redirect to canonical path: / at end of directory url
		// ctx.Request.URL.Path always begins with /
		url := ctx.Request().URL.Path
		if d.IsDir() {
			if url[len(url)-1] != '/' {
				localRedirect(ctx, path.Base(url)+"/")
				return "", http.StatusMovedPermanently
			}
		} else {
			if url[len(url)-1] == '/' {
				localRedirect(ctx, "../"+path.Base(url))
				return "", http.StatusMovedPermanently
			}
		}
	}

	// redirect if the directory name doesn't end in a slash
	if d.IsDir() {
		url := ctx.Request().URL.Path
		if url[len(url)-1] != '/' {
			localRedirect(ctx, path.Base(url)+"/")
			return "", http.StatusMovedPermanently
		}
	}

	// use contents of index.html for directory, if present
	if d.IsDir() {
		index := strings.TrimSuffix(name, "/") + indexPage
		ff, err := fs.Open(index)
		if err == nil {
			defer ff.Close()
			dd, err := ff.Stat()
			if err == nil {
				d = dd
				f = ff
			}
		}
	}

	// Still a directory? (we didn't find an index.html file)
	if d.IsDir() {
		if !showList {
			return "", http.StatusForbidden
		}
		if modified, err := ctx.CheckIfModifiedSince(d.ModTime()); !modified && err == nil {
			ctx.WriteNotModified()
			return "", http.StatusNotModified
		}
		ctx.SetLastModified(d.ModTime())
		return dirList(ctx, f)
	}

	// if gzip disabled then continue using content byte ranges
	if !gzip {
		// serveContent will check modification time
		sizeFunc := func() (int64, error) { return d.Size(), nil }
		return serveContent(ctx, d.Name(), d.ModTime(), sizeFunc, f)
	}

	// else, set the last modified as "serveContent" does.
	ctx.SetLastModified(d.ModTime())

	// write the file to the response writer.
	contents, err := ioutil.ReadAll(f)
	if err != nil {
		ctx.Application().Logger().Debugf("err reading file: %v", err)
		return "error reading the file", http.StatusInternalServerError
	}

	// Use `WriteNow` instead of `Write`
	// because we need to know the compressed written size before
	// the `FlushResponse`.
	_, err = ctx.GzipResponseWriter().Write(contents)
	if err != nil {
		ctx.Application().Logger().Debugf("short write: %v", err)
		return "short write", http.StatusInternalServerError
	}

	// try to find and send the correct content type based on the filename
	// and the binary data inside "f".
	detectOrWriteContentType(ctx, d.Name(), f)

	return "", http.StatusOK
}

func ReadFile(path string, offset uint64) *master.Call {
	return &master.Call{
		Type: master.Call_READ_FILE,
		ReadFile: &master.Call_ReadFile{
			Path:   path,
			Offset: offset,
		},
	}
}

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


Question:
Configure a component

@param {String} configPath Component configuration path
@param {Object} component Component properties
@param {String} componentPath Component path

function configureComponent(configPath, component, componentPath) {
    let config;
    try {
        config = require(configPath);

        // If this is the default variant
        if (!component.variant) {
            config.title = component.name;
            config.status = component.status;
            config.context = config.context || {};
            config.context.type = component.type;
        }

        config.variants = config.variants || [];
    } catch (e) {
        config = {
            title: component.name,
            status: component.status,
            context: {
                type: component.type,
            },
            variants: [],
        };
    }

    // Register the preview component
    if (component.preview) {
        config.preview = `@${[...componentPath, dashify(component.name), 'preview'].join('-')}`;
    }

    // Remove the variant if already present
    const variant = component.variant || 'default';
    config.variants = config.variants.filter(vt => vt.name !== variant);

    // Register the variant
    config.variants.push({
        name: variant,
        label: component.label || ((variant === 'default') ? component.name : variant),
        context: {
            config: component.config,
            parameters: component.parameters || {},
            request: component.request,
            component: component.class,
        },
    });

    config.variants = config.variants.sort((a, b) => {
        const aName = a.label.toLowerCase();
        const bName = b.label.toLowerCase();
        if (aName > bName) {
            return 1;
        }
        return (aName < bName) ? -1 : 0;
    });
    config.variants.forEach((v, i) => {
        config.variants[i].order = i;
    });

    // Write the configuration file
    writeFile(configPath, JSON.stringify(config, null, 4));

    // If there's a component note
    if ((variant === 'default') && component.notice) {
        const readme = path.join(path.dirname(configPath), 'README.md');
        writeFile(readme, component.notice);
    }
}

private function completeDefinition($id, Definition $definition)
    {
        if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
            return;
        }

        if ($this->container->isTrackingResources()) {
            $this->container->addResource(static::createResourceForClass($reflectionClass));
        }

        if (!$constructor = $reflectionClass->getConstructor()) {
            return;
        }

        $arguments = $definition->getArguments();
        foreach ($constructor->getParameters() as $index => $parameter) {
            if (array_key_exists($index, $arguments) && '' !== $arguments[$index]) {
                continue;
            }

            try {
                if (!$typeHint = $parameter->getClass()) {
                    // no default value? Then fail
                    if (!$parameter->isOptional()) {
                        throw new RuntimeException(sprintf('Unable to autowire argument index %d ($%s) for the service "%s". If this is an object, give it a type-hint. Otherwise, specify this argument\'s value explicitly.', $index, $parameter->name, $id));
                    }

                    if (!array_key_exists($index, $arguments)) {
                        // specifically pass the default value
                        $arguments[$index] = $parameter->getDefaultValue();
                    }

                    continue;
                }

                if (null === $this->types) {
                    $this->populateAvailableTypes();
                }

                if (isset($this->types[$typeHint->name])) {
                    $value = new Reference($this->types[$typeHint->name]);
                } else {
                    try {
                        $value = $this->createAutowiredDefinition($typeHint, $id);
                    } catch (RuntimeException $e) {
                        if ($parameter->allowsNull()) {
                            $value = null;
                        } elseif ($parameter->isDefaultValueAvailable()) {
                            $value = $parameter->getDefaultValue();
                        } else {
                            throw $e;
                        }
                    }
                }
            } catch (\ReflectionException $e) {
                // Typehint against a non-existing class

                if (!$parameter->isDefaultValueAvailable()) {
                    throw new RuntimeException(sprintf('Cannot autowire argument %s for %s because the type-hinted class does not exist (%s).', $index + 1, $definition->getClass(), $e->getMessage()), 0, $e);
                }

                $value = $parameter->getDefaultValue();
            }

            $arguments[$index] = $value;
        }

        // it's possible index 1 was set, then index 0, then 2, etc
        // make sure that we re-order so they're injected as expected
        ksort($arguments);
        $definition->setArguments($arguments);
    }

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


Question:
Create a Button Tag
@param string $label Button Content
@param string $type type attribute
@param string $onclick onclick attribute
@param array $attributes further attributes
@return string HTML Code

public static function button(
        string $label,
        string $type = "submit",
        string $onclick = null,
        array $attributes = []
    ) : string
    {
        $buttonPreAttributes = [
            "type" => $type,
        ];

        if ($onclick) {
            $buttonPreAttributes["onclick"] = $onclick;
        }
        $buttonAttributes = array_merge($buttonPreAttributes, $attributes);

        return self::tag("button", $label, $buttonAttributes);
    }

function btnOnClick(e, opts, callback, target, k) {
        var that = void 0;
        if (e.srcElement) e.target = e.srcElement;

        target = U.findParentNode(e.target, function (target) {
          if (target.getAttribute("data-modal-header-btn")) {
            return true;
          }
        });

        if (target) {
          k = target.getAttribute("data-modal-header-btn");

          that = {
            self: this,
            key: k,
            value: opts.header.btns[k],
            dialogId: opts.id,
            btnTarget: target
          };

          if (opts.header.btns[k].onClick) {
            opts.header.btns[k].onClick.call(that, k);
          }
        }

        that = null;
        opts = null;
        callback = null;
        target = null;
        k = null;
      }

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


Question:
Log messages on 'producer.log' file.

@param mixed $object
@param mixed $file

public static function read($file)
    {
        $cwd = getcwd();
        $log = $cwd.'/producer.log';

        if (file_exists($file)) {
            file_put_contents($log, file_get_contents($file), FILE_APPEND);
        }
    }

func (cli *HyperClient) HyperCmdRun(args ...string) error {
	var (
		parser *gflag.Parser
		opts   = &RunFlags{}
		err    error
	)
	parser = gflag.NewParser(opts, gflag.Default|gflag.IgnoreUnknown|gflag.PassAfterNonOption)
	parser.Usage = "run [OPTIONS] IMAGE [COMMAND] [ARG...]\n\nCreate and start a pod"
	args, err = parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}

	specjson, err := cli.ParseCommonOptions(&opts.CommonFlags, false, args...)
	if err != nil {
		return err
	}

	var (
		podId  string
		spec   apitype.UserPod
		code   int
		attach = opts.Attach
		tty    = false
		res    chan error
	)

	t1 := time.Now()

	err = json.Unmarshal([]byte(specjson), &spec)
	if err != nil {
		return err
	}

	podId, code, err = cli.client.CreatePod(&spec)
	if err != nil {
		if code == http.StatusNotFound {
			err = cli.PullImages(&spec)
			if err != nil {
				return err
			}
			podId, code, err = cli.client.CreatePod(&spec)
		}
		if err != nil {
			return err
		}
	}
	if opts.PodFile == "" {
		attach = !opts.Detach
	}
	if !attach {
		fmt.Printf("POD id is %s\n", podId)
	}

	if opts.Remove {
		defer func() {
			rmerr := cli.client.RmPod(podId)
			if rmerr != nil {
				fmt.Fprintf(cli.out, "failed to rm pod, %v\n", rmerr)
			}
		}()
	}

	if attach && len(spec.Containers) > 0 {
		res = make(chan error, 1)
		tty = spec.Tty || spec.Containers[0].Tty
		p, err := cli.client.GetPodInfo(podId)
		if err != nil {
			fmt.Fprintf(cli.err, "failed to get pod info: %v", err)
			return err
		}
		if tty {
			cli.monitorTtySize(p.Spec.Containers[0].ContainerID, "")
			oldState, err := term.SetRawTerminal(cli.inFd)
			if err != nil {
				return err
			}
			defer term.RestoreTerminal(cli.inFd, oldState)
		}
		cname := spec.Containers[0].Name

		go func() {
			res <- cli.client.Attach(cname, tty, cli.in, cli.out, cli.err)
		}()
	}

	err = cli.client.StartPod(podId)
	if err != nil {
		return err
	}

	if !attach {
		t2 := time.Now()
		fmt.Printf("Time to run a POD is %d ms\n", (t2.UnixNano()-t1.UnixNano())/1000000)
	}

	if res != nil {
		err = <-res
		// a container having tty may detach from the terminal, don't wait
		return cli.client.GetExitCode(spec.Containers[0].Name, "", !tty)
	}

	return nil
}

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


Question:
// validateVolumeParams validates the volume parameters, and returns the
// machine ID to use as the scope in the volume tag.

func (sb *storageBackend) validateVolumeParams(params VolumeParams, machineId string) (maybeMachineId string, _ error) {
	if err := validateStoragePool(sb, params.Pool, storage.StorageKindBlock, &machineId); err != nil {
		return "", err
	}
	if params.Size == 0 {
		return "", errors.New("invalid size 0")
	}
	return machineId, nil
}

public function bind(MapInterface $values): self
    {
        if (
            (string) $values->keyType() !== 'string' ||
            (string) $values->valueType() !== 'mixed'
        ) {
            throw new \TypeError('Argument 1 must be of type MapInterface<string, mixed>');
        }

        $this
            ->arguments
            ->filter(static function(string $name, Argument $argument): bool {
                return !$argument->optional() && !$argument->hasDefault();
            })
            ->foreach(static function(string $name) use ($values): void {
                if (!$values->contains($name)) {
                    throw new MissingArgument($name);
                }
            });
        $this
            ->arguments
            ->filter(static function(string $name) use ($values): bool {
                return $values->contains($name);
            })
            ->foreach(static function(string $name, Argument $argument) use ($values): void {
                $argument->validate($values->get($name));
            });

        $self = clone $this;
        $self->values = $values;

        return $self;
    }

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


Question: // ValidateName produces an error message name for an aliased property

func (e *Validation) ValidateName(name string) *Validation {
	if e.Name == "" && name != "" {
		e.Name = name
		e.message = name + e.message
	}
	return e
}

public function getValidationStatusDescription($status)
    {
        $options = $this->getValidationStatusOptions();
        if (!isset($options[$status])) {
            $status = static::ADDRESS_UNKNOWN;
        }

        return $options[$status];
    }

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


Question:
GET /users
 GET /users.json

def index
      @users = User.order("created_at desc").page([params[:page].to_i, 1].max).per(100)

      respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @users }
      end
    end

func (c *RegionsClient) List(ctx context.Context, opts *RegionsListOpts) *RegionIter {
	iter := RegionIter{
		first: true,
		i:     -1,
	}

	p := "/regions/"

	var q url.Values
	if opts != nil {
		q = make(url.Values)
		if opts.Location != nil {
			q.Set("location", *opts.Location)
		}

		if opts.Platform != nil {
			q.Set("platform", *opts.Platform)
		}
	}

	var req *http.Request
	req, iter.err = c.backend.NewRequest(http.MethodGet, p, q, nil)
	if iter.err != nil {
		return &iter
	}

	_, iter.err = c.backend.Do(ctx, req, &iter.page, func(code int) error {
		if code == 500 {
			return &Error{}
		}
		return nil
	})
	return &iter
}

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


Question: Geocode function used to geocode the origin (entered location)

function (thisObj) {
			thisObj.writeDebug('googleGeocode',arguments);
			var geocoder = new google.maps.Geocoder();
			this.geocode = function (request, callbackFunction) {
				geocoder.geocode(request, function (results, status) {
					if (status === google.maps.GeocoderStatus.OK) {
						var result = {};
						result.latitude = results[0].geometry.location.lat();
						result.longitude = results[0].geometry.location.lng();
						result.geocodeResult = results[0];
						callbackFunction(result);
					} else {
						callbackFunction(null);
						throw new Error('Geocode was not successful for the following reason: ' + status);
					}
				});
			};
		}

@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "coord")
    public JAXBElement<CoordType> createCoord(CoordType value) {
        return new JAXBElement<CoordType>(_Coord_QNAME, CoordType.class, null, value);
    }

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


Question:
Get printable version for message type

    :param message_type: Message type
    :type message_type: int
    :return: Printable version
    :rtype: str

def format_message_type(message_type):

    if message_type == MsgType.NOT_SET:
        return "NOT_SET"
    elif message_type == MsgType.ACK:
        return "ACK"
    elif message_type == MsgType.JOIN:
        return "JOIN"
    elif message_type == MsgType.UNJOIN:
        return "UNJOIN"
    elif message_type == MsgType.CONFIG:
        return "CONFIG"
    elif message_type == MsgType.UPDATE:
        return "UPDATE"
    elif message_type == MsgType.DATA:
        return "DATA"
    else:
        return u"{}".format(message_type)

def _serialized(self):
        """"""
        return {'title': self.title,
                'summary': self.summary,
                'areadesc': self.areadesc,
                'event': self.event,
                'samecodes': self.samecodes,
                'zonecodes': self.zonecodes,
                'expiration': self.expiration,
                'updated': self.updated,
                'effective': self.effective,
                'published': self.published,
                'severity': self.severity,
                'category': self.category,
                'urgency': self.urgency,
                'msgtype': self.msgtype,
                'link': self.link,
                }

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


Question:
The programmatical equivalent of clicking a Tab.

@param {lm.item.AbstractContentItem} contentItem

function( contentItem ) {
		var i, j, isActive, activeTab;

		if (this.activeContentItem === contentItem) return;

		for( i = 0; i < this.tabs.length; i++ ) {
			isActive = this.tabs[ i ].contentItem === contentItem;
			this.tabs[ i ].setActive( isActive );
			if( isActive === true ) {
				this.activeContentItem = contentItem;
				this.parent.config.activeItemIndex = i;
			}
		}

		if (this.layoutManager.config.settings.reorderOnTabMenuClick) {
			/**
			 * If the tab selected was in the dropdown, move everything down one to make way for this one to be the first.
			 * This will make sure the most used tabs stay visible.
			 */
			if (this._lastVisibleTabIndex !== -1 && this.parent.config.activeItemIndex > this._lastVisibleTabIndex) {
				activeTab = this.tabs[this.parent.config.activeItemIndex];
				for ( j = this.parent.config.activeItemIndex; j > 0; j-- ) {
					this.tabs[j] = this.tabs[j - 1];
				}
				this.tabs[0]                       = activeTab;
				this.parent.config.activeItemIndex = 0;
			}
		}

		this._updateTabSizes();
		this.parent.emitBubblingEvent( 'stateChanged' );
	}

private String[] getProduces( Produces baseProduces, ExecutableElement method ) {
        Produces localProduces = method.getAnnotation( Produces.class );
        return localProduces != null ? localProduces.value() : baseProduces != null ? baseProduces.value() : null;
    }

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


Question:
Create a list from values.

@param values values to create a list from.
@return list with values.

public static <T> List<T> list(T... values) {
        return new ArrayList<T>(Arrays.asList(values));
    }

def get_item_api(self, resource):

        parameters = self.get_item_parameters(resource)

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

        return get_item_api

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