Question:
Get all declared constructors in the class and set accessible to
{@code true}.

@param clazz The class whose constructors to get.
@return All constructors declared in this class hierarchy.

public static Constructor<?>[] getAllConstructors(Class<?> clazz) {
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : declaredConstructors) {
            if (!constructor.isAccessible()) {
                constructor.setAccessible(true);
            }
        }
        return declaredConstructors;
    }

private Op compile(Token tok, Op next, boolean reverse) {
		Op ret;
		switch (tok.type) {
		case Token.DOT:
			ret = Op.createDot();
			ret.next = next;
			break;

		case Token.CHAR:
			ret = Op.createChar(tok.getChar());
			ret.next = next;
			break;

		case Token.ANCHOR:
			ret = Op.createAnchor(tok.getChar());
			ret.next = next;
			break;

		case Token.RANGE:
		case Token.NRANGE:
			ret = Op.createRange(tok);
			ret.next = next;
			break;

		case Token.CONCAT:
			ret = next;
			if (!reverse) {
				for (int i = tok.size() - 1; i >= 0; i--) {
					ret = compile(tok.getChild(i), ret, false);
				}
			} else {
				for (int i = 0; i < tok.size(); i++) {
					ret = compile(tok.getChild(i), ret, true);
				}
			}
			break;

		case Token.UNION:
			Op.UnionOp uni = Op.createUnion(tok.size());
			for (int i = 0; i < tok.size(); i++) {
				uni.addElement(compile(tok.getChild(i), next, reverse));
			}
			ret = uni; // ret.next is null.
			break;

		case Token.CLOSURE:
		case Token.NONGREEDYCLOSURE:
			Token child = tok.getChild(0);
			int min = tok.getMin();
			int max = tok.getMax();
			if (min >= 0 && min == max) { // {n}
				ret = next;
				for (int i = 0; i < min; i++) {
					ret = compile(child, ret, reverse);
				}
				break;
			}
			if (min > 0 && max > 0)
				max -= min;
			if (max > 0) {
				// X{2,6} -> XX(X(X(XX?)?)?)?
				ret = next;
				for (int i = 0; i < max; i++) {
					Op.ChildOp q = Op
							.createQuestion(tok.type == Token.NONGREEDYCLOSURE);
					q.next = next;
					q.setChild(compile(child, ret, reverse));
					ret = q;
				}
			} else {
				Op.ChildOp op;
				if (tok.type == Token.NONGREEDYCLOSURE) {
					op = Op.createNonGreedyClosure();
				} else { // Token.CLOSURE
					op = Op.createClosure(this.numberOfClosures++);
				}
				op.next = next;
				op.setChild(compile(child, op, reverse));
				ret = op;
			}
			if (min > 0) {
				for (int i = 0; i < min; i++) {
					ret = compile(child, ret, reverse);
				}
			}
			break;

		case Token.EMPTY:
			ret = next;
			break;

		case Token.STRING:
			ret = Op.createString(tok.getString());
			ret.next = next;
			break;

		case Token.BACKREFERENCE:
			ret = Op.createBackReference(tok.getReferenceNumber());
			ret.next = next;
			break;

		case Token.PAREN:
			if (tok.getParenNumber() == 0) {
				ret = compile(tok.getChild(0), next, reverse);
			} else if (reverse) {
				next = Op.createCapture(tok.getParenNumber(), next);
				next = compile(tok.getChild(0), next, reverse);
				ret = Op.createCapture(-tok.getParenNumber(), next);
			} else {
				next = Op.createCapture(-tok.getParenNumber(), next);
				next = compile(tok.getChild(0), next, reverse);
				ret = Op.createCapture(tok.getParenNumber(), next);
			}
			break;

		case Token.LOOKAHEAD:
			ret = Op.createLook(Op.LOOKAHEAD, next,
					compile(tok.getChild(0), null, false));
			break;
		case Token.NEGATIVELOOKAHEAD:
			ret = Op.createLook(Op.NEGATIVELOOKAHEAD, next,
					compile(tok.getChild(0), null, false));
			break;
		case Token.LOOKBEHIND:
			ret = Op.createLook(Op.LOOKBEHIND, next,
					compile(tok.getChild(0), null, true));
			break;
		case Token.NEGATIVELOOKBEHIND:
			ret = Op.createLook(Op.NEGATIVELOOKBEHIND, next,
					compile(tok.getChild(0), null, true));
			break;

		case Token.INDEPENDENT:
			ret = Op.createIndependent(next,
					compile(tok.getChild(0), null, reverse));
			break;

		case Token.MODIFIERGROUP:
			ret = Op.createModifier(next,
					compile(tok.getChild(0), null, reverse),
					((Token.ModifierToken) tok).getOptions(),
					((Token.ModifierToken) tok).getOptionsMask());
			break;

		case Token.CONDITION:
			Token.ConditionToken ctok = (Token.ConditionToken) tok;
			int ref = ctok.refNumber;
			Op condition = ctok.condition == null ? null : compile(
					ctok.condition, null, reverse);
			Op yes = compile(ctok.yes, next, reverse);
			Op no = ctok.no == null ? null : compile(ctok.no, next, reverse);
			ret = Op.createCondition(next, ref, condition, yes, no);
			break;

		default:
			throw new RuntimeException("Unknown token type: " + tok.type);
		} // switch (tok.type)
		return ret;
	}

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


Question:
Converts value into boolean or returns None when conversion is not possible.

        :param value: the value to convert.

        :return: boolean value or None when convertion is not supported.

def to_nullable_boolean(value):

        # Shortcuts
        if value == None:
            return None
        if type(value) == type(True):
            return value

        str_value = str(value).lower()
        # All true values
        if str_value in ['1', 'true', 't', 'yes', 'y']:
            return True
        # All false values
        if str_value in ['0', 'frue', 'f', 'no', 'n']:
            return False

        # Everything else:
        return None

def _resolved_type(self):
        """"""
        import datetime

        self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None
                            for test, testf in tests + [(None, None)]}

        # If it is more than 5% str, it's a str

        try:
            if self.type_ratios.get(text_type,0) + self.type_ratios.get(binary_type,0) > .05:
                if self.type_counts[text_type] > 0:
                    return text_type, False

                elif self.type_counts[binary_type] > 0:
                    return binary_type, False
        except TypeError as e:
            # This is probably the result of the type being unknown
            pass

        if self.type_counts[datetime.datetime] > 0:
            num_type = datetime.datetime

        elif self.type_counts[datetime.date] > 0:
            num_type = datetime.date

        elif self.type_counts[datetime.time] > 0:
            num_type = datetime.time

        elif self.type_counts[float] > 0:
            num_type = float

        elif self.type_counts[int] > 0:
            num_type = int

        elif self.type_counts[text_type] > 0:
            num_type = text_type

        elif self.type_counts[binary_type] > 0:
            num_type = binary_type

        else:
            num_type = unknown

        if self.type_counts[binary_type] > 0 and num_type != binary_type:
            has_codes = True
        else:
            has_codes = False

        return num_type, has_codes

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


Question: Set form's action attribute

protected function setActionAttribute()
    {
        $Eresus = Eresus_CMS::getLegacyKernel();

        /** @var DOMElement $form */
        $form = $this->xml->getElementsByTagName('form')->item(0);
        $url = $Eresus->request['path'];

        /*
         * Если есть тег marker и нет тега redirect, то маркер надо добавить к адресу в атрибуте
         * action.
         */
        $markers = $this->xml->getElementsByTagNameNS(self::NS, 'marker');
        $redirects = $this->xml->getElementsByTagNameNS(self::NS, 'redirect');
        if ($markers->length > 0 && 0 == $redirects->length)
        {
            // На случай если указано несколько маркеров, берём только последний
            /** @var DOMElement $marker */
            $marker = $markers->item($markers->length - 1);
            $url .= '#' . $marker->getAttribute('value');
        }

        $form->setAttribute('action', $url);
    }

public function submitButton($name, $value = '')
    {
        $button = new SubmitButton($this, $value);
        $button->setName($name);
        return $button;
    }

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


Question: // SetFunctionName sets the FunctionName field's value.

func (s *GetPolicyInput) SetFunctionName(v string) *GetPolicyInput {
	s.FunctionName = &v
	return s
}

func (s *LoadBalancerDescription) SetHealthCheck(v *HealthCheck) *LoadBalancerDescription {
	s.HealthCheck = v
	return s
}

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


Question: // run initializes local config and installs Tiller to Kubernetes cluster.

func (i *initCmd) run() error {
	if err := i.tlsOptions(); err != nil {
		return err
	}
	i.opts.Namespace = i.namespace
	i.opts.UseCanary = i.canary
	i.opts.ImageSpec = i.image
	i.opts.ForceUpgrade = i.forceUpgrade
	i.opts.ServiceAccount = i.serviceAccount
	i.opts.MaxHistory = i.maxHistory
	i.opts.Replicas = i.replicas

	writeYAMLManifests := func(manifests []string) error {
		w := i.out
		for _, manifest := range manifests {
			if _, err := fmt.Fprintln(w, "---"); err != nil {
				return err
			}

			if _, err := fmt.Fprintln(w, manifest); err != nil {
				return err
			}
		}

		// YAML ending document boundary marker
		_, err := fmt.Fprintln(w, "...")
		return err
	}
	if len(i.opts.Output) > 0 {
		var manifests []string
		var err error
		if manifests, err = installer.TillerManifests(&i.opts); err != nil {
			return err
		}
		switch i.opts.Output.String() {
		case "json":
			for _, manifest := range manifests {
				var out bytes.Buffer
				jsonb, err := yaml.ToJSON([]byte(manifest))
				if err != nil {
					return err
				}
				buf := bytes.NewBuffer(jsonb)
				if err := json.Indent(&out, buf.Bytes(), "", "    "); err != nil {
					return err
				}
				if _, err = i.out.Write(out.Bytes()); err != nil {
					return err
				}
				fmt.Fprint(i.out, "\n")
			}
			return nil
		case "yaml":
			return writeYAMLManifests(manifests)
		default:
			return fmt.Errorf("unknown output format: %q", i.opts.Output)
		}
	}
	if settings.Debug {
		var manifests []string
		var err error

		// write Tiller manifests
		if manifests, err = installer.TillerManifests(&i.opts); err != nil {
			return err
		}

		if err = writeYAMLManifests(manifests); err != nil {
			return err
		}
	}

	if i.dryRun {
		return nil
	}

	if err := installer.Initialize(i.home, i.out, i.skipRefresh, settings, stableRepositoryURL, localRepositoryURL); err != nil {
		return fmt.Errorf("error initializing: %s", err)
	}
	fmt.Fprintf(i.out, "$HELM_HOME has been configured at %s.\n", settings.Home)

	if !i.clientOnly {
		if i.kubeClient == nil {
			_, c, err := getKubeClient(settings.KubeContext, settings.KubeConfig)
			if err != nil {
				return fmt.Errorf("could not get kubernetes client: %s", err)
			}
			i.kubeClient = c
		}
		if err := installer.Install(i.kubeClient, &i.opts); err != nil {
			if !apierrors.IsAlreadyExists(err) {
				return fmt.Errorf("error installing: %s", err)
			}
			if i.upgrade {
				if err := installer.Upgrade(i.kubeClient, &i.opts); err != nil {
					return fmt.Errorf("error when upgrading: %s", err)
				}
				if err := i.ping(i.opts.SelectImage()); err != nil {
					return err
				}
				fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been upgraded to the current version.")
			} else {
				fmt.Fprintln(i.out, "Warning: Tiller is already installed in the cluster.\n"+
					"(Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)")
			}
		} else {
			fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been installed into your Kubernetes Cluster.")
			if !tlsVerify {
				fmt.Fprintln(i.out, "\nPlease note: by default, Tiller is deployed with an insecure 'allow unauthenticated users' policy.\n"+
					"To prevent this, run `helm init` with the --tiller-tls-verify flag.\n"+
					"For more information on securing your installation see: https://docs.helm.sh/using_helm/#securing-your-helm-installation")
			}
		}
		if err := i.ping(i.opts.SelectImage()); err != nil {
			return err
		}
	} else {
		fmt.Fprintln(i.out, "Not installing Tiller due to 'client-only' flag having been set")
	}

	needsDefaultImage := !i.clientOnly && !i.opts.UseCanary && len(i.opts.ImageSpec) == 0 && version.BuildMetadata == "unreleased"
	if needsDefaultImage {
		fmt.Fprintf(i.out, "\nWarning: You appear to be using an unreleased version of Helm. Please either use the\n"+
			"--canary-image flag, or specify your desired tiller version with --tiller-image.\n\n"+
			"Ex:\n"+
			"$ helm init --tiller-image gcr.io/kubernetes-helm/tiller:v2.8.2\n\n")
	}

	return nil
}

func (c *ServicedCli) cmdHostRegister(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "register")
		return
	}

	var (
		data []byte
		err  error
	)
	fname := args[0]
	switch fname {
	case "-":
		data, err = ioutil.ReadAll(os.Stdin)
	default:
		data, err = ioutil.ReadFile(fname)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := c.driver.RegisterHost(data); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

}

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


Question:
Extract HAL ids from a text.

    :param text: The text to extract HAL ids from.
    :returns: A list of matching HAL ids.

    >>> sorted(extract_from_text("hal-01258754 hal-01258754v2 foobar"))
    ['hal-01258754', 'hal-01258754v2']

def extract_from_text(text):

    return tools.remove_duplicates([i[0]
                                    for i in REGEX.findall(text) if i != ''])

func (i *GetWAFRuleStatusesInput) formatFilters() map[string]string {
	input := i.Filters
	result := map[string]string{}
	pairings := map[string]interface{}{
		"filter[status]":           input.Status,
		"filter[rule][accuracy]":   input.Accuracy,
		"filter[rule][maturity]":   input.Maturity,
		"filter[rule][message]":    input.Message,
		"filter[rule][revision]":   input.Revision,
		"filter[rule][rule_id]":    input.RuleID,
		"filter[rule][tags]":       input.TagID,
		"filter[rule][tags][name]": input.TagName,
		"filter[rule][version]":    input.Version,
		"include":                  input.Tags,
		"page[size]":               input.MaxResults,
		"page[number]":             input.Page, // starts at 1, not 0
	}
	// NOTE: This setup means we will not be able to send the zero value
	// of any of these filters. It doesn't appear we would need to at present.
	for key, value := range pairings {
		switch t := reflect.TypeOf(value).String(); t {
		case "string":
			if value != "" {
				result[key] = value.(string)
			}
		case "int":
			if value != 0 {
				result[key] = strconv.Itoa(value.(int))
			}
		case "[]int":
			// convert ints to strings
			toStrings := []string{}
			values := value.([]int)
			for _, i := range values {
				toStrings = append(toStrings, strconv.Itoa(i))
			}
			// concat strings
			if len(values) > 0 {
				result[key] = strings.Join(toStrings, ",")
			}
		}
	}
	return result
}

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


Question:
Establish a queue connection.

@param array $config
@param array $config

@return IronQueue

public function connect(array $config)
    {
        $ironConfig = ['token' => $config['token'], 'project_id' => $config['project']];

        if (isset($config['host'])) {
            $ironConfig['host'] = $config['host'];
        }

        $iron = new IronMQ($ironConfig);

        if (isset($config['ssl_verifypeer'])) {
            $iron->ssl_verifypeer = $config['ssl_verifypeer'];
        }

        $queue = new IronQueue($iron, $this->request, $config['queue'], $config['encrypt'], $config['timeout']);
        $queue->setEncrypter($this->crypt);

        return $queue;
    }

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

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

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


Question:
Returns true if the condition is met, false otherwise.

@param mixed $caller The condition caller. Optional.
@return bool

public function isOk($caller = null) {
		foreach ($this->conditions as $condition) {
			if (!$condition->isOk($caller)) {
				return false;
			}
		}
		return true;
	}

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $method = $input->getOption('method');
    $routes = array();

    foreach (Route::$routes as $key => $route) {
      if ($method == 'all') {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      } else if (str_contains(implode(' ', $route['method']), $method)) {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      }
    }

    $table = new Table($output);
    $table->setStyle('box');
    $table
        ->setHeaders(array('Method', 'URI', 'Name', 'Action', 'Middleware'))
        ->setRows(
            $routes
        )
    ;
    $table->render();
  }

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


Question:
Capture request

@param array $server
@param array $post
@param array $files
@param array $headers
@param array $cookies
@return Request

public static function capture(
        array $server = null,
        array $post = null,
        array $files = null,
        array $headers = null,
        array $cookies = null
    ) {
        $server  = $server ?? $_SERVER;
        $post    = $post ?? $_POST;
        $cookies = $cookies ?? $_COOKIE;

        $method = $server['REQUEST_METHOD'] ?? 'GET';
        $url    = Url::capture($server);

        $request = new static($method, $url, $post);
        $request->files   = Upload::capture($files);
        $request->headers = Header::capture($headers);
        $request->cookie  = $cookies;

        return $request;
    }

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

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

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

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

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

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

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

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

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

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

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

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


Question:
To get request data from session

@param string $name

@return string

public function get($name)
    {
        return ($this->session->has($name)) ? $this->session->get($name) : '';
    }

func (ws *WebSessionV2) V1() *WebSessionV1 {
	return &WebSessionV1{
		ID:          ws.Metadata.Name,
		Priv:        ws.Spec.Priv,
		Pub:         ws.Spec.Pub,
		BearerToken: ws.Spec.BearerToken,
		Expires:     ws.Spec.Expires,
	}
}

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


Question:
{@inheritdoc}

@param \Ems\Contracts\Model\Relation\TagGroup $group

@return bool

public function hasGroup(TagGroup $group)
    {
        foreach ($this->_groups as $knownGroup) {
            if ($knownGroup->getId() == $group->getId()) {
                return true;
            }
        }

        return false;
    }

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
activate group action

@param $class
@return boolean

protected function activateGroupAction($class)
    {
        $users = $class::whereIn('id', $this->request->id)->get();
        foreach($users as $user) {
            $this->setModel($user);
            $this->activationComplete();
        }
        return true;
    }

public function addBooleanAccessorOpen(&$script, Column $column)
    {
        $name = self::getBooleanAccessorName($column);
        $visibility = $column->getAccessorVisibility();

        $script .= "
    ".$visibility." function $name(";
        if ($column->isLazyLoad()) {
            $script .= "ConnectionInterface \$con = null";
        }

        $script .= ")
    {";
    }

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


Question: // GetParameter extracts interface{} value based on the passed string

func GetParameter(s string, params interface{}) (interface{}, bool) {
	if params == nil {
		return nil, false
	}

	if paramsValue := reflect.ValueOf(params); paramsValue.Kind() == reflect.Slice {
		if paramsValueSliceLength := paramsValue.Len(); paramsValueSliceLength > 0 {

			if p := strings.SplitN(s, ".", 2); len(p) > 1 {
				index, err := strconv.ParseUint(p[0], 10, 64)

				if err != nil || paramsValueSliceLength <= int(index) {
					return nil, false
				}

				return GetParameter(p[1], params.([]interface{})[index])
			}

			index, err := strconv.ParseUint(s, 10, 64)

			if err != nil || paramsValueSliceLength <= int(index) {
				return nil, false
			}

			return params.([]interface{})[index], true
		}

		return nil, false
	}

	if p := strings.SplitN(s, ".", 2); len(p) > 1 {
		if paramsValue := reflect.ValueOf(params); paramsValue.Kind() == reflect.Map {
			if pValue, ok := params.(map[string]interface{})[p[0]]; ok {
				return GetParameter(p[1], pValue)
			}
		} else {
			return nil, false
		}
	} else {
		if pValue, ok := params.(map[string]interface{})[p[0]]; ok {
			return pValue, true
		}
	}

	return nil, false
}

public function resolve(ContainerInterface $container, $id, $definition)
    {
        $definition = substr($definition, 1);
        if ($container->has($definition)) {
            return $container->get($definition);
        }

        return false;
    }

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


Question:
hack: have to override
 Array of array args with optional defaults. Scraped with MethodInspector

def args(lib=library)
      @args = !@args.nil? ? @args : begin
        if lib
          file_string, meth = file_string_and_method_for_args(lib)
          (file_string && meth && (@file_parsed_args = true) &&
            MethodInspector.scrape_arguments(file_string, meth))
        end || false
      end
    end

public function init($argument = false, $multiple = false)
    {
        if (!empty($argument)) {
            return new ArgumentTypeAbstract(
                ($multiple === true) ? $this->makeMultiple($this->getArguments()) : $this->getArguments(),
                $this->getName(),
                $this->getDescription(),
                $multiple
            );
        }

        return new FieldAbstract(
            ($multiple === true) ? new ListType($this->getFields()) : $this->getFields(),
            $this->getName(),
            $this->getDescription()
        );
    }

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


Question:
Sets the value of the slaves according the value of the master.

@param masterOutputValue Master value.

private void updateSlaves(MO masterOutputValue) {
        // Transform value
        SI slaveInputValue = transformer.transform(masterOutputValue);

        // Notify slave(s)
        slave.setValue(slaveInputValue);
    }

def check(self) -> z3.CheckSatResult:

        dependence_map = DependenceMap()
        for constraint in self.constraints:
            dependence_map.add_condition(constraint)

        self.models = []
        for bucket in dependence_map.buckets:
            self.raw.reset()
            self.raw.append(*bucket.conditions)
            check_result = self.raw.check()
            if check_result == z3.sat:
                self.models.append(self.raw.model())
            else:
                return check_result

        return z3.sat

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


Question:
Rounds a float to the specified number of decimal places.

@param {Float} num A number to round
@param {Integer} dec The number of decimal places
@returns {Float} The rounded result

function(num, dec) {
      var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
      return result;
    }

private function valueModification($value, array $modifiers)
    {
        if (is_null($value)) {
            if ($modifiers['n'] || Compat::getOpt('types')) {
                return $this->implementation->reprNULL($this->connection);
            }
        }
        if ($modifiers['h']) {
            return $this->implementation->reprHexadecimal($this->connection, $value);
        }
        if ($modifiers['r']) {
            return $this->implementation->reprString($this->connection, $value);
        }
        if ($modifiers['i']) {
            return $this->implementation->reprInt($this->connection, $value);
        } elseif ($modifiers['f']) {
            return $this->implementation->reprFloat($this->connection, $value);
        } elseif ($modifiers['b']) {
            return $this->implementation->reprBool($this->connection, $value);
        }
        if (Compat::getOpt('types')) {
            $type = gettype($value);
            if ($type === 'integer') {
                return $this->implementation->reprInt($this->connection, $value);
            } elseif ($type === 'double') {
                return $this->implementation->reprFloat($this->connection, $value);
            } elseif ($type === 'boolean') {
                return $this->implementation->reprBool($this->connection, $value);
            }
        }
        return $this->implementation->reprString($this->connection, $value);
    }

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


Question:
Get status

@return status
@throws DevFailed

public String getStatus() throws DevFailed {
        MDC.setContextMap(contextMap);
        xlogger.entry();

        if (initImpl.isInitInProgress()) {
            // set status while init is in progress
            final String tmp = statusImpl.updateStatus(DeviceState.getDeviceState(getState()));
            if (tmp.equals(Constants.INIT_IN_PROGRESS)) {
                status = tmp;
            } else {
                status = Constants.INIT_IN_PROGRESS + System.getProperty("line.separator") + tmp;
            }
        } else if (isCorrectlyInit.get() && initImpl.isInitDoneCorrectly()) {
            // init finished
            status = statusImpl.updateStatus(DeviceState.getDeviceState(getState()));
        } else {
            // init failed
            status = statusImpl.getStatus();
        }

        return status;
    }

public function send(Request $request)
    {
        $this->logger()->debug('Sending request. {request}', [
            'request'  => $request,
        ]);

        $response = $this->sendOrRetry($request, $request->getRetries());

        $this->logger()->debug('Response received. {response}', [
            'request'  => $request,
            'response' => $response,
        ]);

        return $response;
    }

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


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

@throws \RuntimeException
@throws \GuzzleHttp\Exception\GuzzleException

@return int

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $organizationName = $input->getOption('organization');
        if (!$organizationName = $this->resolveOrganizationName($organizationName, $output)) {
            return -1;
        }

        $userid = $input->getArgument('user_id');

        $client = $this->clientProvider->getUserClient();
        $membership = $client->getMembership($userid, $organizationName);

        $output->writeln('Membership');
        $this->formatterHelper->outputOrganizationMembershipInfo($membership, $output);

        return 0;
    }

public static void main( String [] args )
    {
        if ( args.length > 0 ) {
            String filename = args[0];

            String [] bshArgs;
            if ( args.length > 1 ) {
                bshArgs = new String [ args.length -1 ];
                System.arraycopy( args, 1, bshArgs, 0, args.length-1 );
            } else
                bshArgs = new String [0];

            try {
                Interpreter interpreter = new Interpreter();
                interpreter.setu( "bsh.args", bshArgs );
                Object result =
                    interpreter.source( filename, interpreter.globalNameSpace );
                if ( result instanceof Class )
                    try {
                        invokeMain( (Class<?>)result, bshArgs );
                    } catch ( Exception e )
                    {
                        Object o = e;
                        if ( e instanceof InvocationTargetException )
                            o = e.getCause();
                        System.err.println(
                            "Class: "+result+" main method threw exception:"+o);
                    }
            } catch ( FileNotFoundException e ) {
                System.err.println("File not found: "+e);
            } catch ( TargetError e ) {
                System.err.println("Script threw exception: "+e);
                if ( e.inNativeCode() )
                    e.printStackTrace( DEBUG.get(), System.err );
            } catch ( EvalError e ) {
                System.err.println("Evaluation Error: "+e);
            } catch ( IOException e ) {
                System.err.println("I/O Error: "+e);
            }
        } else {
            @SuppressWarnings("resource")
            Interpreter interpreter =
            new Interpreter(new CommandLineReader(
                new FileReader(System.in)),
                System.out, System.err, true );
            interpreter.run();
        }
    }

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


Question: // SetCategory sets the Category field's value.

func (s *CreateJobTemplateInput) SetCategory(v string) *CreateJobTemplateInput {
	s.Category = &v
	return s
}

def get_catalog_form(self, *args, **kwargs):
        """"""
        # Implemented from kitosid template for -
        # osid.resource.BinAdminSession.get_bin_form_for_update_template
        # This method might be a bit sketchy. Time will tell.
        if isinstance(args[-1], list) or 'catalog_record_types' in kwargs:
            return self.get_catalog_form_for_create(*args, **kwargs)
        else:
            return self.get_catalog_form_for_update(*args, **kwargs)

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


Question:
Try to get a token for this server address.
    `address` has to be ip:port, e.g. `'1.2.3.4:1234'`
    Returns tuple(address, token)

def gcommer_claim(address=None):

    if not address:
        # get token for any world
        # this is only useful for testing,
        # because that is exactly what m.agar.io does
        url = 'http://at.gcommer.com/status'
        text = urllib.request.urlopen(url).read().decode()
        j = json.loads(text)
        for address, num in j['status'].items():
            if num > 0:
                break  # address is now one of the listed servers with tokens
    url = 'http://at.gcommer.com/claim?server=%s' % address
    text = urllib.request.urlopen(url).read().decode()
    j = json.loads(text)
    token = j['token']
    return address, token

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question:
// notifyParent notifies parent process that this process has started
// by writing to in-memory pipe used by communication channel.

func (process *TeleportProcess) notifyParent() {
	signalPipe, err := process.importSignalPipe()
	if err != nil {
		if !trace.IsNotFound(err) {
			process.Warningf("Failed to import signal pipe")
		}
		process.Debugf("No signal pipe to import, must be first Teleport process.")
		return
	}
	defer signalPipe.Close()

	ctx, cancel := context.WithTimeout(process.ExitContext(), signalPipeTimeout)
	defer cancel()

	eventC := make(chan Event, 1)
	process.WaitForEvent(ctx, TeleportReadyEvent, eventC)
	select {
	case <-eventC:
		process.Infof("New service has started successfully.")
	case <-ctx.Done():
		process.Errorf("Timeout waiting for a forked process to start: %v. Initiating self-shutdown.", ctx.Err())
		if err := process.Close(); err != nil {
			process.Warningf("Failed to shutdown process: %v.", err)
		}
		return
	}

	if err := process.writeToSignalPipe(signalPipe, fmt.Sprintf("Process %v has started.", os.Getpid())); err != nil {
		process.Warningf("Failed to write to signal pipe: %v", err)
		// despite the failure, it's ok to proceed,
		// it could mean that the parent process has crashed and the pipe
		// is no longer valid.
	}
}

public static function onStart($serv) {
		self::setProcessName(Yesf::app()->getConfig('name', Yesf::CONF_PROJECT) . ' master');
		$pidPath = rtrim(Yesf::app()->getConfig('pid', Yesf::CONF_SERVER), '/') . '/';
		try {
			file_put_contents($pidPath . Yesf::app()->getConfig('name', Yesf::CONF_PROJECT) . '_master.pid', $serv->master_pid);
			file_put_contents($pidPath . Yesf::app()->getConfig('name', Yesf::CONF_PROJECT) . '_manager.pid', $serv->manager_pid);
		} catch (\Exception $e) {
			//忽略写入错误
		}
	}

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


Question: add a new inference var to this inference context

void addVar(TypeVar t) {
        this.undetvars = this.undetvars.prepend(infer.fromTypeVarFun.apply(t));
        this.inferencevars = this.inferencevars.prepend(t);
    }

def _generate_typevars(self):
        # type: () -> None

        self.emit("T = TypeVar('T', bound=bb.AnnotationType)")
        self.emit("U = TypeVar('U')")
        self.import_tracker._register_typing_import('TypeVar')
        self.emit()

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


Question:
Adds a tag to the list of self closing tags that should not have a trailing slash

@param $tag
@return Dom
@chainable

public function addNoSlashTag($tag): Dom
    {
        if ( ! is_array($tag)) {
            $tag = [$tag];
        }
        foreach ($tag as $value) {
            $this->noSlash[] = $value;
        }

        return $this;
    }

function findLinks(rootNode, callback)
{
	var attrName,i,link,linkAttrs,numAttrs,url;

	walk(rootNode, function(node)
	{
		linkAttrs = maxFilterLevel[node.nodeName];

		// If a supported element
		if (linkAttrs != null)
		{
			numAttrs = node.attrs.length;

			// Faster to loop through Arrays than Objects
			for (i=0; i<numAttrs; i++)
			{
				attrName = node.attrs[i].name;
				url = null;

				// If a supported attribute
				if (linkAttrs[attrName] === true)
				{
					// Special case for `<meta http-equiv="refresh" content="5; url=redirect.html">`
					if (node.nodeName==="meta" && attrName==="content")
					{
						if (node.attrMap["http-equiv"]!=null && node.attrMap["http-equiv"].toLowerCase()==="refresh")
						{
							url = parseMetaRefresh( node.attrMap[attrName] ).url;
						}
					}
					else
					{
						// https://html.spec.whatwg.org/multipage/infrastructure.html#valid-url-potentially-surrounded-by-spaces
						url = node.attrMap[attrName].trim();
					}

					if (url != null)
					{
						callback(node, attrName, url);
					}
				}
			}
		}
	});
}

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


Question:
Stub an object. If attr is not None, will attempt to stub that
        attribute on the object. Only required for modules and other rare
        cases where we can't determine the binding from the object.

def stub(self, obj, attr=None):
        '''

        '''
        s = stub(obj, attr)
        if s not in self._stubs:
            self._stubs.append(s)
        return s

def dumpable_obj(obj):
    ''' '''

    if isinstance(obj, list):
        _return_list = []
        for item in obj:
            if isinstance(item, list):
                _return_list.append(dumpable_obj(item))
            elif isinstance(item, set):
                _return_list.append(list(item))
            elif isinstance(item, dict):
                _return_list.append(dumpable_obj(item))
            else:
                try:
                    json.dumps(item)
                    _return_list.append(item)
                except:
                    _return_list.append(str(type(item)))
        return _return_list
    elif isinstance(obj, set):
        return list(obj)
    elif isinstance(obj, dict):
        _return_obj = {}
        for key, item in obj.items():
            if isinstance(item, list):
                _return_obj[key] = dumpable_obj(item)
            elif isinstance(item, set):
                _return_obj[key] = list(item)
            elif isinstance(item, dict):
                _return_obj[key] = dumpable_obj(item)
            else:
                try:
                    json.dumps(item)
                    _return_obj[key] = item
                except:
                    _return_obj[key] = str(type(item))
        return _return_obj
    else:
        try:
            json.dumps(obj)
            return obj
        except:
            return str(type(obj))

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


Question:
Run the Normalizer.

@return mixed normalized $value

public function run()
    {

        // critical ctrl values
        $search = [
            chr(0), chr(1), chr(2), chr(3), chr(4), chr(5),
            chr(6), chr(7), chr(8), chr(11), chr(12), chr(14),
            chr(15), chr(16), chr(17), chr(18), chr(19), chr(24),
            chr(25), chr(192), chr(193), chr(238), chr(255), '\\0',
        ];

        $this->value = str_replace($search, '%00', $this->value);

        if (! $this->runPreSearch()) {
            return $this->value;
        }

        //take care for malicious unicode characters
        $this->value = urldecode(
            preg_replace(
                '/(?:%E(?:2|3)%8(?:0|1)%(?:A|8|9)\w|%EF%BB%BF|%EF%BF%BD)|(?:&#(?:65|8)\d{3};?)/i',
                null,
                urlencode($this->value)
            )
        );
        $this->value = urlencode($this->value);
        $this->value = preg_replace('/(?:%F0%80%BE)/i', '>', $this->value);
        $this->value = preg_replace('/(?:%F0%80%BC)/i', '<', $this->value);
        $this->value = preg_replace('/(?:%F0%80%A2)/i', '"', $this->value);
        $this->value = preg_replace('/(?:%F0%80%A7)/i', '\'', $this->value);
        $this->value = urldecode($this->value);

        $this->value = preg_replace('/(?:%ff1c)/', '<', $this->value);
        $this->value = preg_replace('/(?:&[#x]*(200|820|200|820|zwn?j|lrm|rlm)\w?;?)/i', null, $this->value);
        $this->value = preg_replace(
            '/(?:&#(?:65|8)\d{3};?)|'.
            '(?:&#(?:56|7)3\d{2};?)|'.
            '(?:&#x(?:fe|20)\w{2};?)|'.
            '(?:&#x(?:d[c-f])\w{2};?)/i',
            null,
            $this->value
        );

        $this->value = str_replace(
            [
                '«',
                '〈',
                '＜',
                '‹',
                '〈',
                '⟨',
            ],
            '<',
            $this->value
        );
        $this->value = str_replace(
            [
                '»',
                '〉',
                '＞',
                '›',
                '〉',
                '⟩',
            ],
            '>',
            $this->value
        );

        return $this->value;
    }

protected function handleMixinCall(array $token)
    {

        $node = $this->createNode('mixinCall', $token);
        $node->name = $token['name'];
        $node->attributes = [];
        $node->assignments = [];

        $this->current = $node;
    }

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


Question:
Add the function to the apply function call stack.

        This function will be executed when apply is called. It will be executed
        in the order inserted; apply's func operates the last and return

def add_to_apply_calls(self, func, **kwargs):

        import dask

        self.delayed_call = dask.delayed(func)(self.delayed_call, **kwargs)
        return self

def p_data(p):

    label_ = make_label(gl.DATA_PTR_CURRENT, lineno=p.lineno(1))
    datas_ = []
    funcs = []

    if p[2] is None:
        p[0] = None
        return

    for d in p[2].children:
        value = d.value
        if is_static(value):
            datas_.append(d)
            continue

        new_lbl = '__DATA__FUNCPTR__{0}'.format(len(gl.DATA_FUNCTIONS))
        entry = make_func_declaration(new_lbl, p.lineno(1), type_=value.type_)
        if not entry:
            continue

        func = entry.entry
        func.convention = CONVENTION.fastcall
        SYMBOL_TABLE.enter_scope(new_lbl)
        func.local_symbol_table = SYMBOL_TABLE.table[SYMBOL_TABLE.current_scope]
        func.locals_size = SYMBOL_TABLE.leave_scope()

        gl.DATA_FUNCTIONS.append(func)
        sent = make_sentence('RETURN', func, value)
        func.body = make_block(sent)
        datas_.append(entry)
        funcs.append(entry)

    gl.DATAS.append([label_, datas_])
    id_ = api.utils.current_data_label()
    gl.DATA_PTR_CURRENT = id_

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


Question: Build the proxy methods

public void addProxyMethods(TypeSpec.Builder classBuilder) {
        processRemoterElements(classBuilder, new ElementVisitor() {
            @Override
            public void visitElement(TypeSpec.Builder classBuilder, Element member, int methodIndex, MethodSpec.Builder methodBuilder) {
                addProxyMethods(classBuilder, member, methodIndex);
            }
        }, null);

        addProxyExtras(classBuilder);
        addCommonExtras(classBuilder);
    }

def populate_class_members(self, element_cls, prop_name):

        super(OneAndOnlyOne, self).populate_class_members(
            element_cls, prop_name
        )
        self._add_getter()

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


Question:
Helper to get locale specific properties.

@return the locale specific properties map.

private Map<String, String> getLocaleProperties() {

        if (m_localeProperties == null) {
            m_localeProperties = CmsCollectionsGenericWrapper.createLazyMap(
                new CmsProperty.CmsPropertyLocaleTransformer(m_properties, m_locale));
        }
        return m_localeProperties;
    }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

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

			container_config.events = {};

			for (name in x.event) {

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

			}

		}

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

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

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

		}

		if ('style' in x) {

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

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

		}

		if ('classes' in x) {

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

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

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question:
Upon successful transaction commit status, store the value of the committed metrics.
Upon any other status value roll back the metrics to the last committed value.

@see javax.transaction.Synchronization#afterCompletion(int)

@Override
    public void afterCompletion(int status) {

	    logger.log(Level.FINE, "The status of the transaction commit is: " + status);

        if (status == Status.STATUS_COMMITTED){
        	//Save the metrics object after a successful commit
        	runtimeStepExecution.setCommittedMetrics();
        } else{
        	//status = 4 = STATUS_ROLLEDBACK;
        	runtimeStepExecution.rollBackMetrics();
        }
    }

public void encode(AsnOutputStream aos) throws EncodeException {

        if (this.originatingTransactionId == null || this.originatingTransactionId.length != 4)
            throw new EncodeException("Error while encoding TCConversationMessage: originatingTransactionId is not defined or has not a length 4");
        if (this.destinationTransactionId == null || this.destinationTransactionId.length != 4)
            throw new EncodeException("Error while encoding TCConversationMessage: destinationTransactionId is not defined or has not a length 4");

        // TODO: should we send a Component without both components and dialogPortion ?
        if ((this.component == null || this.component.length == 0) && this.dp == null)
            throw new EncodeException("Error while encoding TCConversationMessage: neither dialogPortion nor componentPortion is defined");

        try {
            if (this.dialogTermitationPermission)
                aos.writeTag(Tag.CLASS_PRIVATE, false, TCConversationMessage._TAG_CONVERSATION_WITH_PERM);
            else
                aos.writeTag(Tag.CLASS_PRIVATE, false, TCConversationMessage._TAG_CONVERSATION_WITHOUT_PERM);
            int pos = aos.StartContentDefiniteLength();

            byte[] buf = new byte[8];
            System.arraycopy(this.originatingTransactionId, 0, buf, 0, 4);
            System.arraycopy(this.destinationTransactionId, 0, buf, 4, 4);
            aos.writeOctetString(Tag.CLASS_PRIVATE, TCQueryMessage._TAG_TRANSACTION_ID, buf);

            if (this.dp != null)
                this.dp.encode(aos);

            if (component != null && component.length > 0) {
                aos.writeTag(Tag.CLASS_PRIVATE, false, TCQueryMessage._TAG_COMPONENT_SEQUENCE);
                int pos2 = aos.StartContentDefiniteLength();
                for (Component c : this.component) {
                    c.encode(aos);
                }
                aos.FinalizeContent(pos2);
            }

            aos.FinalizeContent(pos);

        } catch (IOException e) {
            throw new EncodeException("IOException while encoding TCConversationMessage: " + e.getMessage(), e);
        } catch (AsnException e) {
            throw new EncodeException("AsnException while encoding TCConversationMessage: " + e.getMessage(), e);
        }
    }

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


Question:
Translates a flask.ext.wtf bare import into a non-magical import.

    Translates:
        import flask.ext.admin as admin
    Into:
        import flask_admin as admin

def transform_flask_bare_import(node):
    '''
    '''

    new_names = []
    for (name, as_name) in node.names:
        match = re.match(r'flask\.ext\.(.*)', name)
        from_name = match.group(1)
        actual_module_name = 'flask_{}'.format(from_name)
        new_names.append((actual_module_name, as_name))

    new_node = nodes.Import()
    copy_node_info(node, new_node)
    new_node.names = new_names
    mark_transformed(new_node)
    return new_node

def compiled_columns(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type'):
                    if arg_name in ('server_default', 'server_onupdate'):
                        arg_val = '"{}"'.format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.column_definitions:
            column_args = get_column_args(column)
            column_type, type_params = ModelCompiler.get_col_type_info(column.get('type'))
            column_name = column.get('name')
            if column_type in MUTABLE_DICT_TYPES:
                column_type = ALCHEMY_TEMPLATES.mutable_dict_type.safe_substitute(type=column_type,
                                                                                type_params=type_params)
                type_params = ''
            res.append(
                ALCHEMY_TEMPLATES.column_definition.safe_substitute(column_name=column_name,
                                                                    column_type=column_type,
                                                                    column_args=column_args,
                                                                    type_params=type_params))
        join_string = "\n" + self.tab
        return join_string.join(res)

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


Question:
Converts a {@code LocalDate} to a {@code java.sql.Date}.

@param date  the local date, not null
@return the SQL date, not null

@SuppressWarnings("deprecation")
    public static java.sql.Date toSqlDate(LocalDate date) {
        return new java.sql.Date(date.getYear() - 1900, date.getMonthValue() -1, date.getDayOfMonth());
    }

public static String resolveDataSourceTypeFromDialect(String dialect)
    {
        if (StringUtils.contains(dialect, "Oracle"))
        {
            return "Oracle";
        }
        else if (StringUtils.contains(dialect, "MySQL"))
        {
            return "MySQL";
        }
        else if (StringUtils.contains(dialect, "DB2390Dialect"))
        {
            return "DB2/390";
        }
        else if (StringUtils.contains(dialect, "DB2400Dialect"))
        {
            return "DB2/400";
        }
        else if (StringUtils.contains(dialect, "DB2"))
        {
            return "DB2";
        }
        else if (StringUtils.contains(dialect, "Ingres"))
        {
            return "Ingres";
        }
        else if (StringUtils.contains(dialect, "Derby"))
        {
            return "Derby";
        }
        else if (StringUtils.contains(dialect, "Pointbase"))
        {
            return "Pointbase";
        }
        else if (StringUtils.contains(dialect, "Postgres"))
        {
            return "Postgres";
        }
        else if (StringUtils.contains(dialect, "SQLServer"))
        {
            return "SQLServer";
        }
        else if (StringUtils.contains(dialect, "Sybase"))
        {
            return "Sybase";
        }
        else if (StringUtils.contains(dialect, "HSQLDialect"))
        {
            return "HyperSQL";
        }
        else if (StringUtils.contains(dialect, "H2Dialect"))
        {
            return "H2";
        }

        return dialect;

    }

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


Question:
Registers the minimal config file.
It stores the array items from the minimal config file in the Config
object and eventually sets the phpini error_reporting and display_errors.

@param string|null $filePath

public function registerMinimal(string $filePath = null)
    {
        is_file($filePath) || $filePath = App::getBasePath() . $filePath;

        if (is_file($filePath)) {
            /** @noinspection PhpIncludeInspection */
            $configItems = require_once $filePath;

            !is_array($configItems) || Config::items($configItems);

            ini_set('error_reporting',
                Config::exists('errors.error_reporting', 0));
            ini_set('display_errors',
                Config::exists('errors.display_errors', 0));

            Event::dispatch('minimal.loaded.minimal', [
                $filePath,
                is_array($configItems) ? $configItems : []
            ]);
        }
    }

def log(self):
        """"""
        log.info('PyPhi v%s', __about__.__version__)
        if self._loaded_files:
            log.info('Loaded configuration from %s', self._loaded_files)
        else:
            log.info('Using default configuration (no configuration file '
                     'provided)')
        log.info('Current PyPhi configuration:\n %s', str(self))

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


Question: set values set by configuration dialog

void setConfigValues(Configuration config) {
    this.config = config;
    numParasToCheck = config.getNumParasToCheck();
    defaultParaCheck = numParasToCheck * PARA_CHECK_FACTOR;
    doResetCheck = config.isResetCheck();
  }

public function getOption($name) {
		$this->validateName($name);
		if (array_key_exists($name, $this->config))
			return $this->config[$name];

		return null;
	}

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


Question: Code cleanup to allow for cleaner get_error_message method

def use_response_error_message?(request, response)
      if (request.path.include?('/data/') && !response.content_type.nil?)
        response.content_type.include? 'text/plain'
      else
        false
      end
    end

public function err($text = '', $nl = true)
	{
		fwrite(STDERR, $this->processor->process($text) . ($nl ? "\n" : null));

		return $this;
	}

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


Question: Gets a random date in the last 100 years

public static GregorianCalendar getRandomDate(long seed) {
        GregorianCalendar gc = new GregorianCalendar();
        Random rand = new Random(seed);
        gc.set(GregorianCalendar.YEAR,1900+rand.nextInt(120)); //Between 1900 & 2020
        gc.set(GregorianCalendar.DAY_OF_YEAR,rand.nextInt(364)+1); //Day of year
        return gc;
    }

public static Timestamp of(java.sql.Timestamp timestamp) {
    return ofTimeSecondsAndNanos(timestamp.getTime() / 1000, timestamp.getNanos());
  }

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


Question: // New return a new ErrorObject object

func New(text string, errs ...error) ErrorObject {
	if text != "" {
		errs = append([]error{errors.New(text)}, errs...)
	}
	return NewErrorsSkip(1, errs...)
}

function _addFailure(attribute, rule, parameters) {
    _addError(attribute, rule, parameters);
    if (! _failedRules[attribute]) {
      _failedRules[attribute] = {};
    }
    _failedRules[attribute][rule] = parameters;
  }

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


Question:
////////////////////////////////////////////////////////////////////////
// FileSystem methods
////////////////////////////////////////////////////////////////////////

func (fs *memFS) StatFS(
	ctx context.Context,
	op *fuseops.StatFSOp) (err error) {
	return
}

private File generate(String pattern, int generation, int unique) throws IOException {
        File file = null;
        String word = "";
        int ix = 0;
        boolean sawg = false;
        boolean sawu = false;
        while (ix < pattern.length()) {
            char ch = pattern.charAt(ix);
            ix++;
            char ch2 = 0;
            if (ix < pattern.length()) {
                ch2 = Character.toLowerCase(pattern.charAt(ix));
            }
            if (ch == '/') {
                if (file == null) {
                    file = new File(word);
                } else {
                    file = new File(file, word);
                }
                word = "";
                continue;
            } else  if (ch == '%') {
                if (ch2 == 't') {
                    String tmpDir = System.getProperty("java.io.tmpdir");
                    if (tmpDir == null) {
                        tmpDir = System.getProperty("user.home");
                    }
                    file = new File(tmpDir);
                    ix++;
                    word = "";
                    continue;
                } else if (ch2 == 'h') {
                    file = new File(System.getProperty("user.home"));
                    // Android-changed: Don't make a special exemption for setuid programs.
                    //
                    // if (isSetUID()) {
                    //     // Ok, we are in a set UID program.  For safety's sake
                    //     // we disallow attempts to open files relative to %h.
                    //     throw new IOException("can't use %h in set UID program");
                    // }
                    ix++;
                    word = "";
                    continue;
                } else if (ch2 == 'g') {
                    word = word + generation;
                    sawg = true;
                    ix++;
                    continue;
                } else if (ch2 == 'u') {
                    word = word + unique;
                    sawu = true;
                    ix++;
                    continue;
                } else if (ch2 == '%') {
                    word = word + "%";
                    ix++;
                    continue;
                }
            }
            word = word + ch;
        }
        if (count > 1 && !sawg) {
            word = word + "." + generation;
        }
        if (unique > 0 && !sawu) {
            word = word + "." + unique;
        }
        if (word.length() > 0) {
            if (file == null) {
                file = new File(word);
            } else {
                file = new File(file, word);
            }
        }
        return file;
    }

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


Question:
Find elements matching selector.

@param evaluator CSS selector
@param root root element to descend into
@return matching elements, empty if none

public static Elements select(Evaluator evaluator, Element root) {
        Validate.notNull(evaluator);
        Validate.notNull(root);
        return Collector.collect(evaluator, root);
    }

private function selectNodeType(\DOMNode $node, $val): bool
    {
        if (\is_array($val)) {
            return $this->buildXml($node, $val);
        } elseif ($val instanceof \SimpleXMLElement) {
            $child = $this->dom->importNode(dom_import_simplexml($val), true);
            $node->appendChild($child);
        } elseif ($val instanceof \Traversable) {
            $this->buildXml($node, $val);
        } elseif (\is_object($val)) {
            return $this->selectNodeType($node, $this->serializer->normalize($val, $this->format, $this->context));
        } elseif (is_numeric($val)) {
            return $this->appendText($node, (string) $val);
        } elseif (\is_string($val) && $this->needsCdataWrapping($val)) {
            return $this->appendCData($node, $val);
        } elseif (\is_string($val)) {
            return $this->appendText($node, $val);
        } elseif (\is_bool($val)) {
            return $this->appendText($node, (int) $val);
        } elseif ($val instanceof \DOMNode) {
            $child = $this->dom->importNode($val, true);
            $node->appendChild($child);
        }

        return true;
    }

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


Question:
Creates a {@link Predicate} for matching the subject only.

@param subjectPattern
the regex pattern to match
@return the predicate

public static Predicate<MailMessage> forSubject(final Pattern subjectPattern) {
		return new Predicate<MailMessage>() {
			@Override
			public boolean apply(final MailMessage input) {
				return subjectPattern.matcher(input.getSubject()).matches();
			}

			@Override
			public String toString() {
				return String.format("subject to match pattern '%s'", subjectPattern);
			}
		};
	}

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Sets SELECT DISTINCT / SELECT ALL flag

@param string $field

@return array

public function values($field)
    {
        $source = $this->getSource();
        if ($pos = strpos($source, '.')) {
            $db = substr($source, 0, $source);
            $collection = substr($source, $pos + 1);
        } else {
            $db = null;
            $collection = $source;
        }

        $mongodb = $this->getConnection();

        $cmd = ['distinct' => $collection, 'key' => $field];
        if ($this->_filters) {
            $filters = [];
            foreach ($this->_filters as $filter) {
                $key = key($filter);
                $value = current($filter);
                if (isset($filters[$key]) || count($filter) !== 1) {
                    $filters = ['$and' => $this->_filters];
                    break;
                }
                $filters[$key] = $value;
            }
            $cmd['query'] = $filters;
        }

        $r = $mongodb->command($cmd, $db)[0];
        if (!$r['ok']) {
            throw new InvalidFormatException([
                '`:distinct` distinct for `:collection` collection failed `:code`: `:msg`',
                'distinct' => $field,
                'code' => $r['code'],
                'msg' => $r['errmsg'],
                'collection' => $source
            ]);
        }

        return $this->_limit ? array_slice($r['values'], $this->_offset, $this->_limit) : $r['values'];
    }

private function generateSQL(&$sql, $from, $joins, $where, $having, $group, $values) {
        $froms = [];
        foreach ($from as $f) {
            $froms [] = $f [0] . ' AS ' . $f [1];
        }
        $sql [] = implode(',', $froms);
        if ($joins) {
            foreach ($joins as $join) {
                $sql [] = $join [2] . ' ' . $join [0] . ' AS ' . $join [3] . ' ON (' . $join [1] . ')';
            }
        }
        if ($where && count($where) > 0) {
            $sql [] = 'WHERE ' . $where->getWhereCondition($this, $values);
        }
        if ($group) {
            $sql [] = 'GROUP BY ' . implode(' , ', $group);
        }
        if ($having) {
            $sql [] = 'HAVING ' . implode(' AND ', $having);
        }
    }

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


Question: open the modal window

function() {

    // make sure the modal viewer and other options are off just in case
    modalViewer.close();

    // note it's turned on in the viewer
    DataSaver.updateValue('modalActive', 'true');
    modalViewer.active = true;

    // add an active class to the button that matches this template
    $('#sg-t-'+modalViewer.template+' .sg-checkbox').addClass('active');

    //Add active class to modal
    $('#sg-modal-container').addClass('active');

    // show the modal
    modalViewer.show();

  }

protected function addMutatorClose(&$script, Column $column)
    {
        $this->addMutatorCloseBody($script, $column);
        $this->addMutatorCloseClose($script, $column);
    }

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


Question: // interpolationFuncPow returns base x exponential of y.

func interpolationFuncPow() ast.Function {
	return ast.Function{
		ArgTypes:   []ast.Type{ast.TypeFloat, ast.TypeFloat},
		ReturnType: ast.TypeFloat,
		Callback: func(args []interface{}) (interface{}, error) {
			return math.Pow(args[0].(float64), args[1].(float64)), nil
		},
	}
}

function overrideTasks() {
    function noop() {
        Elixir.log.heading.error('Quorra don\'t have php tests!')
    }

    Elixir.extend('phpSpec', noop);
    Elixir.extend('phpunit', noop);
    Elixir.extend('babel', function () {
        new Elixir.Task('babel', function () {
            Elixir.log.heading('Alert!').heading("'mix.babel()' is not supported in Quorra Elixir. " +
            "You'll want to instead call 'mix.rollup().'");

            process.exit(1);
        });
    });
}

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


Question:
Returns True if this URI names a file or
        if URI represents input/output stream.

def names_singleton(self):

        if self.stream:
            return True
        else:
            return os.path.isfile(self.object_name)

public Route produces(String... types) {
        Preconditions.checkNotNull(types);
        final ImmutableSet.Builder<MediaType> builder = new ImmutableSet.Builder<>();
        builder.addAll(this.producedMediaTypes);
        for (String s : types) {
            final MediaType mt = MediaType.parse(s);
            if (mt.hasWildcard()) {
                throw new RoutingException("A route cannot `produce` a mime type with a wildcard: " + mt);
            }
            builder.add(mt);
        }
        this.producedMediaTypes = builder.build();
        return this;
    }

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


Question: Implementation of get_ntp_stats for IOS.

def get_ntp_stats(self):
        """"""
        ntp_stats = []

        command = "show ntp associations"
        output = self._send_command(command)

        for line in output.splitlines():
            # Skip first two lines and last line of command output
            if line == "" or "address" in line or "sys.peer" in line:
                continue

            if "%NTP is not enabled" in line:
                return []

            elif len(line.split()) == 9:
                address, ref_clock, st, when, poll, reach, delay, offset, disp = (
                    line.split()
                )
                address_regex = re.match(r"(\W*)([0-9.*]*)", address)
            try:
                ntp_stats.append(
                    {
                        "remote": py23_compat.text_type(address_regex.group(2)),
                        "synchronized": ("*" in address_regex.group(1)),
                        "referenceid": py23_compat.text_type(ref_clock),
                        "stratum": int(st),
                        "type": "-",
                        "when": py23_compat.text_type(when),
                        "hostpoll": int(poll),
                        "reachability": int(reach),
                        "delay": float(delay),
                        "offset": float(offset),
                        "jitter": float(disp),
                    }
                )
            except Exception:
                continue

        return ntp_stats

private function checkIssuedAt()
    {
        if (isset($this->payload['iat']) && (int) $this->payload['iat'] - $this->clockSkew > time()) {
            return $this->state = self::INVALID;
        }
    }

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


Question:
Returns the 32bit dotted format of the provided long ip.

@param ip the long ip
@return the 32bit dotted format of ip
@throws IllegalArgumentException if ip is invalid

public String ipToString(long ip) {
        // if ip is bigger than 255.255.255.255 or smaller than 0.0.0.0
        if (ip > 4294967295l || ip < 0) {
            throw new IllegalArgumentException("invalid ip");
        }

        val ipAddress = new StringBuilder();
        for (int i = 3; i >= 0; i--) {
            int shift = i * 8;
            ipAddress.append((ip & (0xff << shift)) >> shift);
            if (i > 0) {
                ipAddress.append(".");
            }
        }
        return ipAddress.toString();
    }

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            log.severe("Binary content has been requested");

        String repository = request.getParameter("repository");
        String workspace = request.getParameter("workspace");
        String path = request.getParameter("path");
        String property = request.getParameter("property");

        Connector connector = (Connector) request.getSession().getAttribute("connector");
        try {
            Session session = connector.find(repository).session(workspace);
            Node node = session.getNode(path);

            Property p;
            try {
                p = node.getProperty(property);
            } catch (PathNotFoundException e) {
                response.setContentType("text/html");
                PrintWriter writer = response.getWriter();
                writer.write("");
                writer.write("
Content not found or recently removed
");
                writer.write("");
                return;
            }

            Binary binary = p.getBinary();

            InputStream in = binary.getStream();
            String contentType = node.getProperty("jcr:mimeType").getString();

            response.setContentType(contentType);

            int b;
            while ((b = in.read()) != -1) {
                response.getOutputStream().write(b);
            }

            log.severe("Sent binary content");
            binary.dispose();

        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

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


Question: Remove a listening callback on the specified channel.

async def remove_listener(self, channel, callback):
        """"""
        if self.is_closed():
            return
        if channel not in self._listeners:
            return
        if callback not in self._listeners[channel]:
            return
        self._listeners[channel].remove(callback)
        if not self._listeners[channel]:
            del self._listeners[channel]
            await self.fetch('UNLISTEN {}'.format(utils._quote_ident(channel)))

func (d *transportDemuxer) unregisterEndpoint(netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint) {
	for _, n := range netProtos {
		if eps, ok := d.protocol[protocolIDs{n, protocol}]; ok {
			eps.unregisterEndpoint(id, ep)
		}
	}
}

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


Question: Returns a hash of options based on dynamic views defined for the object's ancestry. If no config is found returns nil.

def dynamic_options(obj)
      view_methods.each do |meth|
        if obj.class.ancestors.map {|e| e.to_s }.include?(method_to_class(meth))
          begin
            return send(meth, obj)
          rescue
            raise "View failed to generate for '#{method_to_class(meth)}' "+
              "while in '#{meth}' with error:\n#{$!.message}"
          end
        end
      end
      nil
    end

public function process(ContainerBuilder $container)
    {
        $bundles         = $container->getParameter('kernel.bundles');
        $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container');
        $configuration   = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles'));

        foreach ($configuration as $bundleName => $data) {
            if (!isset($bundles[$bundleName])) {
                throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName));
            }

            $rc        = new \ReflectionClass($bundles[$bundleName]);
            $directory = dirname($rc->getFileName());

            $directories = array_map(
                function ($v) use ($directory) {
                    return $directory.'/'.$v;
                },
                $data['directories']
            );

            $definition = new Definition(
                $container->getParameter('atoum.configuration.bundle.class'),
                array($bundleName, $directories)
            );

            $bundleContainer->addMethodCall('add', array($definition));
        }
    }

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


public void removeTarget(T target) {
    Iterator<Pattern<T>> it = patterns.iterator();
    while (it.hasNext()) {
      Pattern<T> pattern = it.next();
      if (pattern.target().equals(target)) it.remove();
    }

    reverse.remove(target);
  }

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
Reduce absolute path with relative parts to real path.
@return Coast\Path

public function toReal()
    {
        if (!$this->isAbsolute()) {
            throw new \Exception("Path '{$this}' is not absolute");
        }

        $target = explode('/', $this->_name);

        $name = [];
        foreach ($target as $part) {
            if ($part == '..') {
                array_pop($name);
            } else if ($part != '.') {
                $name[] = $part;
            }
        }
        $name = implode('/', $name);

        $class = get_class($this);
        return new $class($name);
    }

void findNodes(List<RBBINode> dest, int kind) {
        if (fType == kind) {
            dest.add(this);
        }
        if (fLeftChild != null) {
            fLeftChild.findNodes(dest, kind);
        }
        if (fRightChild != null) {
            fRightChild.findNodes(dest, kind);
        }
    }

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


Question: // isMember makes sure that the user is in one of the required organizations.

func isMember(requiredOrgs []string, userOrgs []*github.Organization) bool {
	for _, requiredOrg := range requiredOrgs {
		for _, userOrg := range userOrgs {
			if userOrg.Login != nil && *userOrg.Login == requiredOrg {
				return true
			}
		}
	}
	return false
}

func (u *UpdateCheckRunOptions) GetHeadBranch() string {
	if u == nil || u.HeadBranch == nil {
		return ""
	}
	return *u.HeadBranch
}

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


Question: Details of a specific model resource.

def model_resource(self, resource_name):

        resource = first(
            [resource for resource in self.api._registry.values()
             if resource.get_api_name() == resource_name])

        data = {
            'apiVersion': '0.1',
            'swaggerVersion': '1.1',
            'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),
            'resourcePath': '/meta/%s' % resource.get_api_name(),
            'apis': self.get_model_apis(resource),
            'models': self.get_model(resource)
        }
        response = jsonify(data)
        response.headers.add('Cache-Control', 'max-age=0')
        return response

public VersionResource getVersion(String name) throws RepositoryException, IllegalResourceTypeException
   {
      return new VersionResource(versionURI(name), versionedResource, versionHistory.getVersion(name), namespaceContext);
   }

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


Question:
Returns the next constraint of a given type

@param  from
@param  type

int getNextConstraintIndex(int from, int type) {

        for (int i = from, size = constraintList.length; i < size; i++) {
            Constraint c = constraintList[i];

            if (c.getConstraintType() == type) {
                return i;
            }
        }

        return -1;
    }

protected function substituteImplicitBindings( $route )
	{
		$parameters = $route->parameters();

		foreach ( $route->signatureParameters( Model::class ) as $parameter )
		{
			$class = $parameter->getClass();

			if ( array_key_exists( $parameter->name, $parameters ) && !$route->getParameter( $parameter->name ) instanceof Model )
			{
				$method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail';

				$model = $class->newInstance();

				$route->setParameter( $parameter->name, $model->where( $model->getRouteKeyName(), $parameters[$parameter->name] )->{$method()} );
			}
		}
	}

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


Question: // Non blocking way to try to acquire a shared lock.

func (f *FileLock) TryRLock() error {
	return f.performLock(syscall.LOCK_SH | syscall.LOCK_NB)
}

func (g *Graph) getVertex_rlocked(vertexType vertexType, namespace, name string) (*namedVertex, bool) {
	vertex, exists := g.vertices[vertexType][namespace][name]
	return vertex, exists
}

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


Question:
Leave a room. For internal use by the Games SDK only. Calling this method directly is
unsupported. (rooms.leave)

@param string $roomId The ID of the room.
@param RoomLeaveRequest $postBody
@param array $optParams Optional parameters.
@return Room

public function leave($roomId, RoomLeaveRequest $postBody, $optParams = array()) {
      $params = array('roomId' => $roomId, 'postBody' => $postBody);
      $params = array_merge($params, $optParams);
      $data = $this->__call('leave', array($params));
      if ($this->useObjects()) {
        return new Room($data);
      } else {
        return $data;
      }
    }

def update
      @payment_method = PaymentMethod.find params[:payment_method_id]
      data = JSON.parse Base64.strict_decode64 params[:data]
      render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature]
      @order = Order.find data['order_id']

      raise ArgumentError unless @order.payments.completed.empty? &&
        data['currency'] == @order.currency &&
        BigDecimal(data['amount']) == @order.total &&
        data['type'] == 'buy' &&
        (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox'))

      payment = @order.payments.create amount: @order.total, payment_method: @payment_method
      payment.complete!

      render text: "Thank you.\n"
    end

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


Question:
Initialize editor for each file opened
@param {String} themeId
@param {String} folderName
@param {String} fileName
@param {String} text
@param {String} mode

function initAceEditor(themeId, folderName, fileName, text, mode) {
        hideImageHolder();
        $("#" + editorId).show();
        var doc = new Document(text);
        var session = new EditSession(doc, "ace/mode/" + mode);
        session.setUndoManager(new UndoManager());
        editor.setSession(session);

        //bind change event for text changes in opened file and save them.
        doc.on('change', function (e) {
            // e.type, etc
            console.log(e);
            saveFileChanges(themeId, folderName, fileName, doc.getValue());
        });
    }

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

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


Question:
@param string $path

@return string

private function getDownloadUrlForFile($path)
    {
        $metadataRaw = $this->getMetadata($path)->getBody()->getContents();
        $metadata = json_decode($metadataRaw);

        return $metadata->{'@content.downloadUrl'};
    }

func (s *GetParametersByPathInput) SetWithDecryption(v bool) *GetParametersByPathInput {
	s.WithDecryption = &v
	return s
}

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


Question:
@param null $productCode
@param null $optionName
@param null $optionValue
@param string $method
@param bool $output
@param bool $urlEncode

@return null|string

public static function getGeneratedValue(
        $productCode = null,
        $optionName = null,
        $optionValue = null,
        $method = 'name',
        $output = false,
        $urlEncode = false
    ) {
        $optionName = ($optionName !== null) ? preg_replace('/\s/', '_', $optionName) : $optionName;

        return (FoxyStripeSetting::current_foxystripe_setting()->CartValidation)
            ? \FoxyCart_Helper::fc_hash_value($productCode, $optionName, $optionValue, $method, $output, $urlEncode) :
            $optionValue;
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question:
Sets the factory for this instance.

@since [*next-version*]

@param FactoryInterface|null $factory The factory instance to set, if any.

protected function _setFactory($factory)
    {
        if ($factory !== null && !($factory instanceof FactoryInterface)) {
            throw $this->_createInvalidArgumentException(
                $this->__('Argument is not a valid factory instance'),
                null,
                null,
                $factory
            );
        }
        $this->factory = $factory;
    }

private function generateProxyMethod(\ReflectionMethod $method): string
    {
        if ($method->isConstructor()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for constructor in class "%s".',
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isStatic()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for static method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isPrivate()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy for private method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $proxyMethodParameters = [];
        $methodParameters = [];

        foreach ($method->getParameters() as $methodParameter) {
            $methodParameters[] = '$'.$methodParameter->getName();

            if ($methodParameter->getClass()) {
                $proxyMethodParameter = sprintf(
                    '\\%s %s',
                    $methodParameter->getClass()->getName(),
                    '$'.$methodParameter->getName()
                );
            } else if ($methodParameter->getType()) {
                $proxyMethodParameter = \sprintf(
                    '%s%s $%s',
                    $methodParameter->getType()->allowsNull() ? '?' : '',
                    $methodParameter->getType()->getName(),
                    $methodParameter->getName()
                );
            } else {
                $proxyMethodParameter = '$'.$methodParameter->getName();
            }

            if ($methodParameter->isOptional()) {
                $proxyMethodParameter .= ' = '.\var_export($methodParameter->getDefaultValue(), true);
            }

            $proxyMethodParameters[] = $proxyMethodParameter;
        }

        if ($method->isPublic()) {
            $availability = 'public';
        } else if ($method->isProtected()) {
            $availability = 'protected';
        } else {
            throw new \RuntimeException(sprintf(
                'Not support availability for method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $docComment = "/**\n * {@inheritdoc}\n */";
        $returnTypeHint = '';
        $returnResult = "\n\n    return \$result;";

        if ($method->getReturnType()) {
            $returnTypeHint = sprintf(
                ': %s%s%s',
                \class_exists($method->getReturnType()->getName()) ? '\\' : '',
                $method->getReturnType()->allowsNull() ? '?' : '',
                $method->getReturnType()->getName()
            );
        }

        if ($method->getReturnType() && 'void' === $method->getReturnType()->getName()) {
            $returnResult = '';
        }

        $templateVariables = [
            'docComment'            => $docComment,
            'availability'          => $availability,
            'name'                  => $method->getName(),
            'proxyMethodParameters' => \implode(', ', $proxyMethodParameters),
            'parameters'            => \implode(', ', $methodParameters),
            'beginArguments'        => null,
            'rollbackArguments'     => null,
            'commitArguments'       => null,
            'return_type_hint'      => $returnTypeHint,
            'return_result'         => $returnResult,
        ];

        $methodTemplate = $this->getTemplateForProxyMethod();
        $methodCode = $this->replaceVariables($methodTemplate, $templateVariables);
        $methodCode = $this->appendTabulationCharacter($methodCode, 1);

        return $methodCode;
    }

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


Question: returns the partitioner used by this cluster

def describe_partitioner(self, ):

    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_describe_partitioner()
    return d

public void configure(OStorage iStorage, int iId, String iClusterName, String iLocation, int iDataSegmentId,
      Object... iParameters) throws IOException {
    id = iId;
    name = iClusterName;
    dataSegmentId = iDataSegmentId;
  }

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


Question: // Subtasks gets all tasks for all lists.

func (c oauthClient) Subtasks() ([]wl.Subtask, error) {
	lists, err := c.Lists()
	if err != nil {
		return nil, err
	}

	listCount := len(lists)
	c.logger.Debug(
		"subtasks",
		map[string]interface{}{"listCount": listCount},
	)

	subtasksChan := make(chan []wl.Subtask, listCount)
	idErrChan := make(chan idErr, listCount)
	for _, l := range lists {
		go func(list wl.List) {
			c.logger.Debug(
				"subtasks - getting subtasks for list",
				map[string]interface{}{"listID": list.ID},
			)
			subtasks, err := c.SubtasksForListID(list.ID)
			idErrChan <- idErr{idType: "list", id: list.ID, err: err}
			subtasksChan <- subtasks
		}(l)
	}

	e := multiIDErr{}
	for i := 0; i < listCount; i++ {
		idErr := <-idErrChan
		if idErr.err != nil {
			c.logger.Debug(
				"subtasks - error received getting subtasks for list",
				map[string]interface{}{"listID": idErr.id, "err": err},
			)
			e.addError(idErr)
		}
	}

	totalSubtasks := []wl.Subtask{}
	for i := 0; i < listCount; i++ {
		subtasks := <-subtasksChan
		totalSubtasks = append(totalSubtasks, subtasks...)
	}

	if len(e.errors()) > 0 {
		return totalSubtasks, e
	}

	return totalSubtasks, nil
}

func (m *Manager) AddIncludeSubOrgOf(globalId, orgMemberId string) error {
	return m.collection.Update(
		bson.M{"globalid": globalId},
		bson.M{"$addToSet": bson.M{"includesuborgsof": orgMemberId}})
}

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


Question:
// mainHashArgs returns the args for the main hash for this model. Typically
// these args should part of an HMSET command.

func (mr *modelRef) mainHashArgs() (redis.Args, error) {
	return mr.mainHashArgsForFields(mr.spec.fieldNames())
}

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

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