Question:
Gets attribute repository.

@return the attribute repository

@JsonIgnore
    protected static IPersonAttributeDao getAttributeRepository() {
        val repositories = ApplicationContextProvider.getAttributeRepository();
        return repositories.orElse(null);
    }

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

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

        $generator->startList('Tag');

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

        $generator->endList('Tag');

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

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


Question:
Use `mime` v1.x to get type.

@param {String} filename can be a full path
@returns {String} mime type

function getFromFileNameV1 (filename) {
	var result = mime.lookup(filename);

	// Add charset just in case for some buggy browsers.
	if (result === 'application/javascript' || result === 'application/json' || result === 'text/plain') {
		result += '; charset=UTF-8';
	}

	return result;
}

private static ReuseResult loadBitmapReuseExact(ImageSource source, Bitmap dest) throws ImageLoadException {
        ImageMetadata metadata = source.getImageMetadata();
        boolean tryReuse = false;
        if (dest.isMutable()
                && dest.getWidth() == metadata.getW()
                && dest.getHeight() == metadata.getH()) {
            if (Build.VERSION.SDK_INT >= 19) {
                tryReuse = true;
            } else if (Build.VERSION.SDK_INT >= 11) {
                if (metadata.getFormat() == ImageFormat.JPEG || metadata.getFormat() == ImageFormat.PNG) {
                    tryReuse = true;
                }
            }
        }

        if (tryReuse) {
            return source.loadBitmap(dest);
        } else {
            return new ReuseResult(loadBitmap(source), false);
        }
    }

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


Question: Get per-instance subscribers from the signal.

def get_subscribers(self):

        data = self.signal.instance_subscribers
        if self.instance not in data:
            data[self.instance] = MethodAwareWeakList()
        return data[self.instance]

func (connector *Forwarder) AddSpans(ctx context.Context, spans []*trace.Span) error {
	atomic.AddInt64(&connector.stats.pipeline, int64(len(spans)))
	defer atomic.AddInt64(&connector.stats.pipeline, -int64(len(spans)))
	atomic.AddInt64(&connector.stats.totalSpansForwarded, int64(len(spans)))
	// could filter here
	if len(spans) == 0 {
		return nil
	}
	return connector.sampler.AddSpans(ctx, spans, connector.sink)
}

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


Question: // BindingAuthorized returns true if the user associated with the context is explicitly authorized to bind the specified roleRef

func BindingAuthorized(ctx context.Context, roleRef rbac.RoleRef, bindingNamespace string, a authorizer.Authorizer) bool {
	if a == nil {
		return false
	}

	user, ok := genericapirequest.UserFrom(ctx)
	if !ok {
		return false
	}

	attrs := authorizer.AttributesRecord{
		User: user,
		Verb: "bind",
		// check against the namespace where the binding is being created (or the empty namespace for clusterrolebindings).
		// this allows delegation to bind particular clusterroles in rolebindings within particular namespaces,
		// and to authorize binding a clusterrole across all namespaces in a clusterrolebinding.
		Namespace:       bindingNamespace,
		ResourceRequest: true,
	}

	// This occurs after defaulting and conversion, so values pulled from the roleRef won't change
	// Invalid APIGroup or Name values will fail validation
	switch roleRef.Kind {
	case "ClusterRole":
		attrs.APIGroup = roleRef.APIGroup
		attrs.Resource = "clusterroles"
		attrs.Name = roleRef.Name
	case "Role":
		attrs.APIGroup = roleRef.APIGroup
		attrs.Resource = "roles"
		attrs.Name = roleRef.Name
	default:
		return false
	}

	decision, _, err := a.Authorize(attrs)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf(
			"error authorizing user %#v to bind %#v in namespace %s: %v",
			user, roleRef, bindingNamespace, err,
		))
	}
	return decision == authorizer.DecisionAllow
}

public function getUploadResult($token)
    {
        $jwt = new Jwt();

        $claims = $jwt->decode($token, false);

        if (!isset($claims['scope'])) {
            throw new AuthenticationException('scope is not exists');
        }

        if ($claims['scope'] !== 'bos.object.create.response') {
            throw new AuthenticationException(['`:scope` scope is not valid', 'scope' => $claims['scope']]);
        }

        if (!isset($claims['bucket'])) {
            throw new AuthenticationException('bucket is not exists');
        }

        $bucket = $claims['bucket'];

        $this->logger->info($token, 'bosClient.getUploadResult');

        $jwt->verify($token, is_string($this->_access_key) ? $this->_access_key : $this->_access_key[$bucket]);

        return array_except($claims, ['scope', 'iat', 'exp']);
    }

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


Question:
// setRootMetadata sets the current head metadata for the
// corresponding folder-branch.

func (fbsk *folderBranchStatusKeeper) setRootMetadata(md ImmutableRootMetadata) {
	fbsk.dataMutex.Lock()
	defer fbsk.dataMutex.Unlock()
	if fbsk.md.MdID() == md.MdID() {
		return
	}
	fbsk.md = md
	fbsk.signalChangeLocked()
}

def commit_to(self, db: BaseDB) -> None:

        self.logger.debug2('persist storage root to data store')
        if self._trie_nodes_batch is None:
            raise ValidationError(
                "It is invalid to commit an account's storage if it has no pending changes. "
                "Always check storage_lookup.has_changed_root before attempting to commit."
            )
        self._trie_nodes_batch.commit_to(db, apply_deletes=False)
        self._clear_changed_root()

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


Question: // GetAllHosts returns a list of all hosts based on the internal cache.

func (c *Cluster) GetAllHosts() []*Host {
	hosts := make([]*Host, 0, len(c.hostsCache))

	if err := c.Update(); err != nil {
		c.logger.Log("level", "error", "message", "error getting the list of hosts based on the internal cache: %#v", "stack", err)
		return hosts
	}

	for _, cachedHost := range c.hostsCache {
		hosts = append(hosts, cachedHost.get())
	}
	return hosts
}

func (c *Client) MGet(keys ...string) ([]string, error) {
	tmp := make([]interface{}, len(keys)+1)
	tmp[0] = "MGET"
	for n, k := range keys {
		tmp[n+1] = k
	}
	v, err := c.execOnFirst(true, tmp...)
	if err != nil {
		return nil, err
	}
	switch v.(type) {
	case []interface{}:
		items := v.([]interface{})
		resp := make([]string, len(items))
		for n, item := range items {
			switch item.(type) {
			case string:
				resp[n] = item.(string)
			}
		}
		return resp, nil
	}
	return nil, ErrServerError
}

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


Question:
// findPackageParentTree finds any parent tree package that would
// include the given canonical path.

func (ctx *Context) findPackageParentTree(ck *Package) []string {
	out := make([]string, 0, 1)
	for _, pkg := range ctx.Package {
		if !pkg.inVendor {
			continue
		}
		if !pkg.IncludeTree || pkg == ck {
			continue
		}
		// pkg.Path = github.com/usera/pkg, tree = true
		// ck.Path = github.com/usera/pkg/dance
		if strings.HasPrefix(ck.Path, pkg.Path+"/") {
			out = append(out, pkg.Local)
		}
	}
	return out
}

def childByNodeName(self, nodeName):

        assert '/' not in nodeName, "nodeName can not contain slashes"
        for child in self.childItems:
            if child.nodeName == nodeName:
                return child

        raise IndexError("No child item found having nodeName: {}".format(nodeName))

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


Question:
Finish the {Span}
 @param end_time [Time] custom end time, if not now

def finish(end_time: Time.now)
      if end_micros.nil?
        self.end_micros = LightStep.micros(end_time)
      end
      tracer.finish_span(self)
      self
    end

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question:
@param $request
@param Closure $next
@param null $strategy

@return mixed
@throws AuthenticationException
@throws \RandomState\LaravelAuth\Exceptions\UnknownStrategyException

public function handle($request, Closure $next, $strategy = null, $sessions = true)
    {
        if ( ! ($user = $this->manager->login($strategy, $request))) {
            throw new AuthenticationException('Unauthenticated.');
        };

        if($sessions) {
            Auth::login($user);
        } else {
            Auth::setUser($user);
        }

        return $next($request);
    }

protected function make($ctx)
    {
      // ENV or raw args
      if (!is_object($ctx)) {
        $this->user_id = $ctx['BANDWIDTH_USER_ID'];
        $this->token = $ctx['BANDWIDTH_API_TOKEN'];
        $this->secret = $ctx['BANDWIDTH_API_SECRET'];
        $this->application_id = $ctx->get('BANDWIDTH_APPLICATION_ID');
      } else {
        $this->user_id = $ctx->get('BANDWIDTH_USER_ID');
        $this->token = $ctx->get('BANDWIDTH_API_TOKEN');
        $this->secret = $ctx->get('BANDWIDTH_API_SECRET');
        $this->application_id = $ctx->get('BANDWIDTH_APPLICATION_ID');
      }

      if (!isset($this->user_id)
         ||!isset($this->token)
         ||!isset($this->secret))
              throw new \CatapultApiException("Credentials were improperly configured");

      $this->started = TRUE;

      return (self::$CLIENT = new RESTClient($this->user_id, array($this->token, $this->secret), $this->application_id));
    }

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


Question:
// AddResult adds a new query result for processing.
// Put the result into the list of pending results. If the number of pending results exceeds `maxDegree`,
// consume the results for incrementally update the merkle tree

func (helper *RangeQueryResultsHelper) AddResult(kvRead *kvrwset.KVRead) error {
	logger.Debug("Adding a result")
	helper.pendingResults = append(helper.pendingResults, kvRead)
	if helper.hashingEnabled && uint32(len(helper.pendingResults)) > helper.maxDegree {
		logger.Debug("Processing the accumulated results")
		if err := helper.processPendingResults(); err != nil {
			return err
		}
	}
	return nil
}

func (mvcc *MVCCLevelDB) Prewrite(mutations []*kvrpcpb.Mutation, primary []byte, startTS uint64, ttl uint64) []error {
	mvcc.mu.Lock()
	defer mvcc.mu.Unlock()

	anyError := false
	batch := &leveldb.Batch{}
	errs := make([]error, 0, len(mutations))
	for _, m := range mutations {
		// If the operation is Insert, check if key is exists at first.
		var err error
		if m.GetOp() == kvrpcpb.Op_Insert {
			v, err := mvcc.getValue(m.Key, startTS, kvrpcpb.IsolationLevel_SI)
			if err != nil {
				errs = append(errs, err)
				anyError = true
				continue
			}
			if v != nil {
				err = &ErrKeyAlreadyExist{
					Key: m.Key,
				}
				errs = append(errs, err)
				anyError = true
				continue
			}
		}
		err = prewriteMutation(mvcc.db, batch, m, startTS, primary, ttl)
		errs = append(errs, err)
		if err != nil {
			anyError = true
		}
	}
	if anyError {
		return errs
	}
	if err := mvcc.db.Write(batch, nil); err != nil {
		return nil
	}

	return errs
}

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


Question: // SetDataStorage sets the DataStorage field's value.

func (s *IdentityUsage) SetDataStorage(v int64) *IdentityUsage {
	s.DataStorage = &v
	return s
}

def bind_name(self, name):
        """"""
        if self.name:
            raise errors.Error('Already bound "{0}" with name "{1}" could not '
                               'be rebound'.format(self, self.name))
        self.name = name
        self.storage_name = ''.join(('_', self.name))
        return self

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


Question: rubocop:disable Metrics/AbcSize

def setup_ssl_context(config) # :nodoc:
      unless config[:SSLCertificate]
        cn = config[:SSLCertName]
        comment = config[:SSLCertComment]
        cert, key = Utils.create_self_signed_cert(1024, cn, comment)
        config[:SSLCertificate] = cert
        config[:SSLPrivateKey] = key
      end
      ctx = OpenSSL::SSL::SSLContext.new
      ctx.set_params
      ctx.ciphers = (CIPHERS - SmartProxyDynflowCore::Settings.instance.ssl_disabled_ciphers).join(':')
      ctx.key = config[:SSLPrivateKey]
      ctx.cert = config[:SSLCertificate]
      ctx.client_ca = config[:SSLClientCA]
      ctx.extra_chain_cert = config[:SSLExtraChainCert]
      ctx.ca_file = config[:SSLCACertificateFile]
      ctx.ca_path = config[:SSLCACertificatePath]
      ctx.cert_store = config[:SSLCertificateStore]
      ctx.tmp_dh_callback = config[:SSLTmpDhCallback]
      ctx.verify_mode = config[:SSLVerifyClient]
      ctx.verify_depth = config[:SSLVerifyDepth]
      ctx.verify_callback = config[:SSLVerifyCallback]
      ctx.timeout = config[:SSLTimeout]
      ctx.options |= config[:SSLOptions] unless config[:SSLOptions].nil?
      ctx
    end

def imode_browser_version
      case @request.env['HTTP_USER_AGENT']
      when %r{^DoCoMo/1.0/}
        ver = '1.0'
      when %r{^DoCoMo/2.0 }
        @request.env['HTTP_USER_AGENT'] =~ / (\w+)\(c(\d+);/
        model = Regexp.last_match(1)
        cache_size = Regexp.last_match(2).to_i

        ver = if cache_size >= 500
                (%w[P03B P05B L01B].member?(model) ? '2.0LE' : '2.0')
              else
                '1.0'
              end
      else
        # DoCoMo/3.0以降等は、とりあえず非v1.0扱い
        ver = '2.0'
      end

      ver
    end

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


Question:
Activates the user or returns an error message

@access protected
@param string $uuid
@param string $activationToken
@return array

protected function activateUser($uuid, $activationToken)
    {
        // Check the uuid
        if (!$this->userManager->hasUserForUuid($uuid)) {
            return array('result' => false, 'message' => $this->translate('Account with the given UUID does not exist.', '\\Zepi\\Web\\AccessControl'));
        }

        // Compare the activation token
        $user = $this->userManager->getUserForUuid($uuid);
        if ($user->getMetaData('activationToken') !== $activationToken) {
            return array('result' => false, 'message' => $this->translate('The given activation token is not valid.', '\\Zepi\\Web\\AccessControl'));
        }

        // Remove the disabled access level
        $this->accessControlManager->revokePermission($uuid, get_class($user), '\\Global\\Disabled');
        $this->accessControlManager->grantPermission($uuid, get_class($user), '\\Global\\Active', 'Activation');

        return array('result' => true, 'message' => $this->translate('Your account was activated successfully.', '\\Zepi\\Web\\AccessControl'));
    }

public function getAuthorizationUrl()
    {
        // Check for required items
        if (!$this->clientId) {
            throw new Exception('Client ID is required');
        }
        if (!$this->scope) {
            throw new Exception('Scope is required');
        }
        if (!$this->redirectUri) {
            throw new Exception('Redirect URI is required');
        }

        // Start building url (enpoint is the same for public and member APIs)
        $url  = 'https://';
        $url .= (!empty($this->environment)) ? $this->environment . '.' : '';
        $url .= self::HOSTNAME . '/' . self::AUTHORIZE;
        $url .= '?client_id='    . $this->clientId;
        $url .= '&scope='        . $this->scope;
        $url .= '&redirect_uri=' . urlencode($this->redirectUri);
        $url .= '&response_type=code';

        // Process non-required fields
        $url .= ($this->showLogin)          ? '&show_login=true'                    : '';
        $url .= (isset($this->state))       ? '&state=' . $this->state              : '';
        $url .= (isset($this->familyNames)) ? '&family_names=' . $this->familyNames : '';
        $url .= (isset($this->givenNames))  ? '&given_names=' . $this->givenNames   : '';
        $url .= (isset($this->email))       ? '&email=' . urlencode($this->email)   : '';

        return $url;
    }

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


Question:
Called when a relationship of this combinedType is instantiated. Please note that
a relationship can (and will) be instantiated several times during a
normal rendering turn.

@Override
	public void onRelationshipInstantiation() {

		try {

			if (dbRelationship != null) {

				Node startNode = dbRelationship.getStartNode();
				Node endNode   = dbRelationship.getEndNode();

				if ((startNode != null) && (endNode != null) && startNode.hasProperty(GraphObject.id.dbName()) && endNode.hasProperty(GraphObject.id.dbName())) {

					cachedStartNodeId = (String) startNode.getProperty(GraphObject.id.dbName());
					cachedEndNodeId   = (String) endNode.getProperty(GraphObject.id.dbName());

				}

			}

		} catch (Throwable t) {
		}
	}

def load_contexts_and_renderers(events, mediums):

    sources = {event.source for event in events}
    rendering_styles = {medium.rendering_style for medium in mediums if medium.rendering_style}

    # Fetch the default rendering style and add it to the set of rendering styles
    default_rendering_style = get_default_rendering_style()
    if default_rendering_style:
        rendering_styles.add(default_rendering_style)

    context_renderers = ContextRenderer.objects.filter(
        Q(source__in=sources, rendering_style__in=rendering_styles) |
        Q(source_group_id__in=[s.group_id for s in sources], rendering_style__in=rendering_styles)).select_related(
            'source', 'rendering_style').prefetch_related('source_group__source_set')

    context_hints_per_source = get_context_hints_per_source(context_renderers)
    model_querysets = get_querysets_for_context_hints(context_hints_per_source)
    model_ids_to_fetch = get_model_ids_to_fetch(events, context_hints_per_source)
    model_data = fetch_model_data(model_querysets, model_ids_to_fetch)
    load_fetched_objects_into_contexts(events, model_data, context_hints_per_source)
    load_renderers_into_events(events, mediums, context_renderers, default_rendering_style)

    return events

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


Question: Define the values

public function setValues($values, array $files = array())
    {
        foreach ($this->getFields() as $name => $field) {
            $name = $field->getBaseName();
            $index = $field->getIndex();

            if ($index === null) {
                if ($present = isset($values[$name])) {
                    $value =& $values[$name];
                }
            } else {
                if ($index) {
                    $present = true;
                    $tmp = &$values[$name];
                    foreach ($index as $part) {
                        if (isset($tmp[$part])) {
                            $tmp = &$tmp[$part];
                        } else {
                            $present = false;
                        }
                    }

                    if ($present) {
                        $value = $tmp;
                    }
                } else {
                    if ($present = isset($values[$name]) && is_array($values[$name])) {
                        $value = in_array($field->getValue(), $values[$name]);
                    }
                }
            }

            if ($field instanceof Fields\Multiple) {
                if (!$present) {
                    $value = array();
                }
                $field->setValues($value, (isset($files[$name])?$files[$name]:array()));
            } else {
                if ($present) {
                    $field->setValue($value, $files);
                } else {
                    if ($field instanceof Fields\FileField && isset($files[$name])) {
                        $field->setValue($files[$name]);
                    } else {
                        $field->setValue('');
                    }
                }
            }
        }
    }

func IsValue(node Expr) bool {
	switch v := node.(type) {
	case *SQLVal:
		switch v.Type {
		case StrVal, HexVal, IntVal, ValArg:
			return true
		}
	}
	return false
}

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


Question:
Get the node at the given location
@param {location}

function nodeAtLocation(location) {
        return exports.root.find(function each(n) {
            return n.isAtLocation(location, false);
        });
    }

function(feature) {
        var geometry = feature.geometry;
            geometry = geometry.clone();
        if (this.internalProjection && this.externalProjection) {
            geometry.transform(this.internalProjection,
                               this.externalProjection);
        }
        if (geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
            var wpt = this.buildWptNode(geometry);
            this.appendAttributesNode(wpt, feature);
            return wpt;
        } else {
            var trkNode = this.createElementNS(this.namespaces.gpx, "trk");
            this.appendAttributesNode(trkNode, feature);
            var trkSegNodes = this.buildTrkSegNode(geometry);
            trkSegNodes = OpenLayers.Util.isArray(trkSegNodes) ?
                trkSegNodes : [trkSegNodes];
            for (var i = 0, len = trkSegNodes.length; i < len; i++) {
                trkNode.appendChild(trkSegNodes[i]);
            }
            return trkNode;
        }
    }

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


Question:
get mcrypt options

@param array $options passed  options

@return array

protected static function mcryptOptions($options)
	{
		$options_default = array(
			'cipher'	=> MCRYPT_RIJNDAEL_128,
			'mode'		=> MCRYPT_MODE_CBC,
			// encryption options
			'return_base64' => true,		// return cryptText base64_encoded
			'rand_src'	=> MCRYPT_RAND,
			'padding'	=> 'PKCS5',			// only applies with MCRYPT_MODE_CBC, see $padding_methods for values
			'iv'		=> null,			// usually randomly generated
			'iv_return'	=> true,			// can only be disabled when passing iv
		);
		$options = array_merge($options_default, $options);
		$options['iv_size']= mcrypt_get_iv_size($options['cipher'], $options['mode']);
		$options['key_size'] = mcrypt_get_key_size($options['cipher'], $options['mode']);
		$options['block_size'] = mcrypt_get_block_size($options['cipher'], $options['mode']);
		#$debug->log('iv_size', $options['iv_size']);
		#$debug->log('key_size', $options['key_size']);
		#$debug->log('block_size', $options['block_size']);
		return $options;
	}

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:
Generate a HMAC for the given data
@param {String} data
@param {String} key
@param {String} encoding
@returns {String|Buffer} will return a Buffer if no encoding given

function generateHmac(data, key, encoding) {
    var hmac = crypto.createHmac(HMAC_SHA256_ALGORITHM, key);
    hmac.update(data);
    return hmac.digest(encoding);
}

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:
Return multiplication of two quaternions.
    >>> q = quat_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
    >>> np.allclose(q, [-44, -14, 48, 28])
    True

def quat_multiply(quaternion1, quaternion0):

    x0, y0, z0, w0 = quaternion0
    x1, y1, z1, w1 = quaternion1
    return np.array(
        (
            x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
            -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
            x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0,
            -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
        ),
        dtype=np.float32,
    )

def translate(self, pos):

        self.matrix = np.dot(self.matrix, transforms.translate(pos[0, :3]))

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


Question:
/*var FileStatus = function() {
this.filename = null;
this.fragmented = null;
this.deadBytes = null;
this.totalBytes = null;
this.oldestTimestamp = null;
this.newestTimestamp = null;
};

function(options) {
  if (!(this instanceof Medea))
    return new Medea(options);

  EventEmitter.call(this);

  this.active = null;
  this.keydir = new Map();

  options = options || {};

  this.maxFileSize = options.hasOwnProperty('maxFileSize')
    ? options.maxFileSize : 2147483648; //2GB

  this.mergeWindow = options.hasOwnProperty('mergeWindow')
    ? options.mergeWindow : 'always';

  this.fragMergeTrigger = options.hasOwnProperty('fragMergeTrigger')
    ? options.fragMergeTrigger : 60; // fragmentation >= 60%

  this.deadBytesMergeTrigger = options.hasOwnProperty('deadBytesMergeTrigger')
    ? options.deadBytesMergeTrigger : 536870912; // dead bytes > 512MB

  this.fragThreshold = options.hasOwnProperty('fragThreshold')
    ? options.fragThreshold : 40; // fragmentation >= 40%

  this.deadBytesThreshold = options.hasOwnProperty('deadBytesThreshold')
    ? options.deadBytesThreshold : 134217728; // dead bytes > 128MB

  this.smallFileThreshold = options.hasOwnProperty('smallFileThreshold')
    ? options.smallFileThreshold : 10485760 // file < 10MB

  this.maxFoldAge = options.hasOwnProperty('maxFoldAge') ? options.maxFoldAge : -1;
  this.maxFoldPuts = options.hasOwnProperty('maxFoldPuts') ? options.maxFoldPuts : 0;
  this.expirySecs = options.hasOwnProperty('expirySecs') ? options.expirySecs : -1;
  this.dirname = options.hasOwnProperty('dirname') ? options.dirname: null;
  this.readOnly = false;
  this.bytesToBeWritten = 0;
  this.readableFiles = [];
  this.fileReferences = {};
  this.compactor = new Compactor(this);
  this.setMaxListeners(Infinity);
}

func (i IndexFile) Has(name, version string) bool {
	_, err := i.Get(name, version)
	return err == nil
}

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


Question:
Create a multi dimension array.

If you got a array like array('foo.bar.baz'=>'foobar') we will create an array like:
array('foo'=>array('bar'=>array('baz'=>'foobar')))

@param array $translations

@return array

protected function createMultiArray(array $translations)
    {
        $res = array();

        foreach ($translations as $keyString => $value) {
            $keys = explode('.', $keyString);

            //$keyString might be "Hello world."
            $keyLength = count($keys);
            if ($keys[$keyLength - 1] == '') {
                unset($keys[$keyLength - 1]);
                $keys[$keyLength - 2] .= '.';
            }

            $this->addValueToMultiArray($res, $value, $keys);
        }

        return $res;
    }

public static function validate($genres)
    {
        $data = array();
        if (\is_string($genres)) {
            $genres = \str_replace(',', ' ', $genres);
            $genres = \explode(' ', $genres);
            $genres = \array_filter($genres);
        }

        if (\is_array($genres)) {
            foreach ($genres as $genre) {
                if (\in_array($genre, self::$genres, true)) {
                    $data[] = $genre;
                }
            }
        }

        $data = \implode(', ', $data);

        return (\strlen($data) > 0) ? $data : false;
    }

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


Question: Returns a list of package contents (for Data Packages).

public static ArrayList<String> listPackageContents(Map<String, Object> m) {
        ArrayList<String> acc = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : m.entrySet()) {
            if (isValidPackageContent(entry.getValue())) {
                acc.add(entry.getKey());
            }
        }
        return acc;
    }

protected function getZipImporter()
    {
        if (!$this->zipImporter) {
            $this->zipImporter = new SharedStimulusPackageImporter();
            $this->zipImporter->setServiceLocator($this->getServiceLocator());
        }
        return $this->zipImporter;
    }

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


Question:
Returns the currently requested sort information.
@return array sort directions indexed by attribute names.
Sort direction can be either CSort::SORT_ASC for ascending order or
CSort::SORT_DESC for descending order.

public function getDirections()
	{
		if($this->_directions===null)
		{
			$this->_directions=array();
			if(isset($_GET[$this->sortVar]) && is_string($_GET[$this->sortVar]))
			{
				$attributes=explode($this->separators[0],$_GET[$this->sortVar]);
				foreach($attributes as $attribute)
				{
					if(($pos=strrpos($attribute,$this->separators[1]))!==false)
					{
						$descending=substr($attribute,$pos+1)===$this->descTag;
						if($descending)
							$attribute=substr($attribute,0,$pos);
					}
					else
						$descending=false;

					if(($this->resolveAttribute($attribute))!==false)
					{
						$this->_directions[$attribute]=$descending;
						if(!$this->multiSort)
							return $this->_directions;
					}
				}
			}
			if($this->_directions===array() && is_array($this->defaultOrder))
				$this->_directions=$this->defaultOrder;
		}
		return $this->_directions;
	}

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question:
Get a OmekaCollection class representation of an Omeka collection
 @param  id  [Integer] The ID of the collection to return. No value gets
 an array of all the items.
 @return  [OmekaCollection] An OmekaCollection object
 @since 1.0.0

def get_collection(id)
      response = self.get('collections', id).body
      return OmekaClient::OmekaCollection.new(self, JSON.parse(response))
    end

public static Result convert(final Object res) throws QConnectorException {
		if (res == null) {
			return new EmptyResult();
		}
		// table
		if (res instanceof c.Flip) {
			return new FlipResult("", (c.Flip) res);
		}
		// dict
		if (res instanceof c.Dict) {
			final c.Dict dict = (c.Dict) res;
			if ((dict.x instanceof c.Flip) && (dict.y instanceof c.Flip)) {
				final c.Flip key = (c.Flip) dict.x;
				final c.Flip data = (c.Flip) dict.y;
				return new FlipFlipResult("", key, data);
			}
		}
		if (res instanceof Object[]) {
			final Object[] oa = (Object[]) res;
			if ((oa.length == 2) && (oa[0] instanceof String) && (oa[1] instanceof c.Flip)) {
				final String table = (String) oa[0];
				final c.Flip flip = (c.Flip) oa[1];
				return new FlipResult(table, flip);
			} else if ((oa.length == 3) && (oa[1] instanceof String) && (oa[2] instanceof c.Flip)) {
				final String table = (String) oa[1];
				final c.Flip flip = (c.Flip) oa[2];
				return new FlipResult(table, flip);
			} else {
				return new ListResult<Object>(oa);
			}
		}
		// list
		if (res instanceof byte[]) {
			return new ListResult<Byte>(ArrayUtils.toObject((byte[]) res));
		}

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


Question: // Handle executing the request and returning a response

func (fn UpdateTaskHandlerFunc) Handle(params UpdateTaskParams, principal interface{}) middleware.Responder {
	return fn(params, principal)
}

public function end($exitCode = 0, $exit = true)
    {
        if ($this->hasEventHandler('endRequest')) {
            $this->onEndRequest(new Event($this));
        }
        if ($exit) {
            exit($exitCode);
        }
    }

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


Question: Called before a batch of entities is prepped for rendering

function() {
        var gl = this.context;
        gl.useProgram(this.shader);
        gl.bindBuffer(gl.ARRAY_BUFFER, this._attributeBuffer);
        var a,
            attributes = this.attributes;
        // Process every attribute
        for (var i = 0; i < attributes.length; i++) {
            a = attributes[i];
            gl.vertexAttribPointer(
                a.location,
                a.width,
                a.type,
                false,
                this.stride * a.bytes,
                a.offset * a.bytes
            );
        }

        // For now, special case the need for texture objects
        var t = this.texture_obj;
        if (t && t.unit === null) {
            this.layer.texture_manager.bindTexture(t);
        }

        this.index_pointer = 0;
    }

protected function handleBlockRendering($blocks)
    {
        foreach ($blocks as &$block) {
            $type        = resolve($block->type->handler);
            $block->view = $type->handle($block, $this->languageService->getCurrent());
        }
    }

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


Question:
Returns true if the current token is the specified keyword.

@param keyword
the keyword string
@return true if that keyword is the current token

public boolean matchKeyword(String keyword) {
		return tok.ttype == StreamTokenizer.TT_WORD && tok.sval.equals(keyword)
				&& keywords.contains(tok.sval);
	}

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

      :ok # passes
    end

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


Question:
Sets the message UUID.

The message UUID is optional application-specific identifier for
book-keeping and associate it with the response.

@param messageId notification message ID
@return  this

public A messageId(String messageId) {
        this.headers.add(Pair.of("X-MessageId", messageId));
        return (A)this;
    }

def on_data(self, raw_data):

        try:
            data = json.loads(raw_data)
        except ValueError:
            logger.error('value error: %s' % raw_data)
            return

        unique_id = data.get('id')

        if self._error_handler(data, unique_id):
            return False

        operation = data['op']
        if operation == 'connection':
            self._on_connection(data, unique_id)
        elif operation == 'status':
            self._on_status(data, unique_id)
        elif operation in ['mcm', 'ocm']:
            # historic data does not contain unique_id
            if self.stream_unique_id not in [unique_id, 'HISTORICAL']:
                logger.warning('Unwanted data received from uniqueId: %s, expecting: %s' %
                               (unique_id, self.stream_unique_id))
                return
            self._on_change_message(data, unique_id)

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


Question: // does this ctx permit msg support?

func (pc parseCtx) permitsMsg() bool {
	return pc.ctxType == fileCtx || pc.ctxType == msgCtx
}

func (c *TCP) Subscribe(tags []string) error {

	if len(tags) == 0 {
		return fmt.Errorf("Unable to subscribe - missing tags")
	}

	return c.encoder.Encode(&mist.Message{Command: "subscribe", Tags: tags})
}

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


Question: Push the new user and password into the registry's configuration.

@Modified
    protected synchronized void modify(QuickStartSecurityConfig config) {
        this.config = config;

        validateConfigurationProperties();

        if (urConfigReg == null) {
            registerQuickStartSecurityRegistryConfiguration();
        } else {
            updateQuickStartSecurityRegistryConfiguration();
        }

        unregisterQuickStartSecurityAdministratorRole();
        registerQuickStartSecurityAdministratorRole();
    }

func (m *MetaClient) CreateUser(ctx context.Context, name, passwd string) error {
	return m.CreateUpdateUser(ctx, "create", name, passwd)
}

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


Question: OP_MSG implementation entry point.

def _batched_op_msg(
        operation, command, docs, check_keys, ack, opts, ctx):
    """"""
    buf = StringIO()

    # Save space for message length and request id
    buf.write(_ZERO_64)
    # responseTo, opCode
    buf.write(b"\x00\x00\x00\x00\xdd\x07\x00\x00")

    to_send, length = _batched_op_msg_impl(
        operation, command, docs, check_keys, ack, opts, ctx, buf)

    # Header - request id and message length
    buf.seek(4)
    request_id = _randint()
    buf.write(_pack_int(request_id))
    buf.seek(0)
    buf.write(_pack_int(length))

    return request_id, buf.getvalue(), to_send

func (client *QueryClient) MessageStream(name string, callback func(*sqltypes.Result) error) (err error) {
	return client.server.MessageStream(client.ctx, &client.target, name, callback)
}

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


Question: // NewSendMessageToTargetArgs initializes SendMessageToTargetArgs with the required arguments.

func NewSendMessageToTargetArgs(message string) *SendMessageToTargetArgs {
	args := new(SendMessageToTargetArgs)
	args.Message = message
	return args
}

func (mig *modelMigration) TargetInfo() (*migration.TargetInfo, error) {
	authTag, err := names.ParseUserTag(mig.doc.TargetAuthTag)
	if err != nil {
		return nil, errors.Trace(err)
	}
	macs, err := jsonToMacaroons(mig.doc.TargetMacaroons)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &migration.TargetInfo{
		ControllerTag:   names.NewControllerTag(mig.doc.TargetController),
		ControllerAlias: mig.doc.TargetControllerAlias,
		Addrs:           mig.doc.TargetAddrs,
		CACert:          mig.doc.TargetCACert,
		AuthTag:         authTag,
		Password:        mig.doc.TargetPassword,
		Macaroons:       macs,
	}, nil
}

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


Question: // AgentStatus implements Connections.

func (c *connections) AgentStatus(agent string) (Status, error) {
	if c.model == "" {
		return Unknown, errors.New("connections not limited to a model, agent ambiguous")
	}
	result := Unknown
	for _, value := range c.values {
		if value.Agent == agent && !value.ControllerAgent {
			if value.Status > result {
				result = value.Status
			}
		}
	}
	return result, nil
}

public void statusMessage(String text) throws IOException {
		Map<String, Object> m = JSONProtocol.cmd("message");
		m.put("text", text);
		pipe.send(m);
		if (!JSONProtocol.check(m, pipe.recv())) {
			throw new IOException("Could not display status");
		}
	}

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


Question: // Size returns the estimated current memory usage of LruCache.

func (c *LruCache) Size() int64 {
	c.mu.Lock()
	size := c.size
	c.mu.Unlock()

	return size
}

def info
      return @info if defined? @info

      # Try to fetch from cache first.
      key = HeapInfo::Cache.key_libc_info(name)
      @info = HeapInfo::Cache.read(key)
      @info ||= execute_libc_info.tap { |i| HeapInfo::Cache.write(key, i) }
    end

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


Question:
// GetInt takes a given key and checks the config for both
// that the key exists, and that it is of type int64.
// Returns an error if either of these is false.

func (c Config) GetInt(key string) (int64, error) {
	var (
		iout int64
		val  interface{}
		ok   bool
	)

	if val, ok = c[key]; !ok {
		return iout, ErrConfigNotFound
	}

	if iout, ok = val.(int64); !ok {
		return iout, ErrNotAnInt
	}

	return iout, nil
}

func (num Number) Int() (int, bool) {
	i, err := json.Number(num).Int64()
	if err != nil {
		return 0, false
	}
	return int(i), true
}

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


Question:
Add an issue to current context
@param IssueInterface $issue
@return void

public function addIssue (IssueInterface $issue)
	{
		$length = count($this->stack);
		$this->stack[$length-1]->addIssue ($issue);
	}

public function register() {
		if ( ! $this->vendor ) {
			throw new VendorNotSetException;
		}

		if ( ! $this->version ) {
			throw new VersionNotSetException;
		}

		foreach ( $this->endpoints as $endpoint ) {
			register_rest_route(
				$this->get_namespace(),
				$endpoint->get_route(),
				$endpoint->get_options()
			);
		}
	}

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


Question:
track expression

        Display a graph showing which objects are referred by the
        value of the expression.  This command requires pypy to be in
        the current PYTHONPATH.

def do_track(self, arg):

        try:
            from rpython.translator.tool.reftracker import track
        except ImportError:
            print('** cannot import pypy.translator.tool.reftracker **',
                  file=self.stdout)
            return
        try:
            val = self._getval(arg)
        except:
            pass
        else:
            track(val)

def explain_features():
    '''
    '''
    from ape import tasks
    import featuremonkey
    import os

    featurenames = featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_EQUATION_FILENAME'])

    for featurename in featurenames:
        tasks.explain_feature(featurename)

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


Question:
Take the provided criterion and store it as an option in the query
 options.

 @api private

 @example Store the option.
   optional.option({ skip: 10 })

 @param [ Array ] args The options.

 @return [ Queryable ] The cloned queryable.

 @since 1.0.0

def option(*args)
      clone.tap do |query|
        unless args.compact.empty?
          yield(query.options, query)
        end
      end
    end

def clone(cls, model, use_json=True, use_lp=False):

        model.update()
        interface = sys.modules[cls.__module__]

        if use_lp:
            warnings.warn("Cloning with LP formats can change variable and constraint ID's.")
            new_model = cls.from_lp(model.to_lp())
            new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)
            return new_model

        if use_json:
            new_model = cls.from_json(model.to_json())
            new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)
            return new_model

        new_model = cls()
        for variable in model.variables:
            new_variable = interface.Variable.clone(variable)
            new_model._add_variable(new_variable)
        for constraint in model.constraints:
            new_constraint = interface.Constraint.clone(constraint, model=new_model)
            new_model._add_constraint(new_constraint)
        if model.objective is not None:
            new_model.objective = interface.Objective.clone(model.objective, model=new_model)
        new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)
        return new_model

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


Question: // Convert_v1_JenkinsPipelineBuildStrategy_To_build_JenkinsPipelineBuildStrategy is an autogenerated conversion function.

func Convert_v1_JenkinsPipelineBuildStrategy_To_build_JenkinsPipelineBuildStrategy(in *v1.JenkinsPipelineBuildStrategy, out *build.JenkinsPipelineBuildStrategy, s conversion.Scope) error {
	return autoConvert_v1_JenkinsPipelineBuildStrategy_To_build_JenkinsPipelineBuildStrategy(in, out, s)
}

func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) {
	var repository, tag string
	if options.Reference != "" {
		ref, err := reference.ParseNormalizedNamed(options.Reference)
		if err != nil {
			return types.IDResponse{}, err
		}

		if _, isCanonical := ref.(reference.Canonical); isCanonical {
			return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference")
		}
		ref = reference.TagNameOnly(ref)

		if tagged, ok := ref.(reference.Tagged); ok {
			tag = tagged.Tag()
		}
		repository = reference.FamiliarName(ref)
	}

	query := url.Values{}
	query.Set("container", container)
	query.Set("repo", repository)
	query.Set("tag", tag)
	query.Set("comment", options.Comment)
	query.Set("author", options.Author)
	for _, change := range options.Changes {
		query.Add("changes", change)
	}
	if !options.Pause {
		query.Set("pause", "0")
	}

	var response types.IDResponse
	resp, err := cli.post(ctx, "/commit", query, options.Config, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return response, err
	}

	err = json.NewDecoder(resp.body).Decode(&response)
	return response, err
}

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


Question:
Allocate a Scsd object (a Sulmage-Mendelsohn decomposition).

@param m
number of rows of the matrix A to be analyzed
@param n
number of columns of the matrix A to be analyzed
@return Sulmage-Mendelsohn decomposition

public static Scsd cs_dalloc(int m, int n) {
        Scsd S;
        S = new Scsd();
        S.p = new int[m];
        S.r = new int[m + 6];
        S.q = new int[n];
        S.s = new int[n + 6];
        S.cc = new int[5];
        S.rr = new int[5];
        return S;
    }

def initialize_means_weights(data, clusters, init_means=None, init_weights=None, initialization='tsvd', max_assign_weight=0.75):

    genes, cells = data.shape
    if init_means is None:
        if init_weights is not None:
            if len(init_weights.shape)==1:
                means = initialize_means(data, init_weights, clusters)
            else:
                means = initialize_means(data, init_weights.argmax(0),
                        clusters, max_assign_weight=max_assign_weight)
        elif initialization=='cluster':
            assignments, means = poisson_cluster(data, clusters)
            if init_weights is None:
                init_weights = initialize_from_assignments(assignments, clusters,
                        max_assign_weight=max_assign_weight)
        elif initialization=='kmpp':
            means, assignments = kmeans_pp(data, clusters)
        elif initialization=='km':
            km = KMeans(clusters)
            assignments = km.fit_predict(log1p(cell_normalize(data)).T)
            init_weights = initialize_from_assignments(assignments, clusters,
                    max_assign_weight)
            means = initialize_means(data, assignments, clusters)
        elif initialization=='tsvd':
            n_components = min(50, genes-1)
            #tsvd = TruncatedSVD(min(50, genes-1))
            km = KMeans(clusters)
            # remove dependence on sklearn tsvd b/c it has a bug that
            # prevents it from working properly on long inputs
            # if num elements > 2**31
            #data_reduced = tsvd.fit_transform(log1p(cell_normalize(data)).T)
            U, Sigma, VT = randomized_svd(log1p(cell_normalize(data)).T,
                    n_components)
            data_reduced = U*Sigma
            assignments = km.fit_predict(data_reduced)
            init_weights = initialize_from_assignments(assignments, clusters,
                    max_assign_weight)
            means = initialize_means(data, assignments, clusters)
        elif initialization == 'random' or initialization == 'rand':
            # choose k random cells and set means to those
            selected_cells = np.random.choice(range(cells), size=clusters,
                    replace=False)
            means = data[:, selected_cells]
            if sparse.issparse(means):
                means = means.toarray()
    else:
        means = init_means.copy()
    means = means.astype(float)
    if init_weights is None:
        if init_means is not None:
            if initialization == 'cluster':
                assignments, means = poisson_cluster(data, clusters,
                        init=init_means, max_iters=1)
                w_init = initialize_from_assignments(assignments, clusters,
                        max_assign_weight)
            elif initialization == 'km':
                km = KMeans(clusters, init=log1p(init_means.T), max_iter=1)
                assignments = km.fit_predict(log1p(cell_normalize(data)).T)
                w_init = initialize_from_assignments(assignments, clusters,
                        max_assign_weight)
            else:
                w_init = np.random.random((clusters, cells))
                w_init = w_init/w_init.sum(0)
        else:
            w_init = np.random.random((clusters, cells))
            w_init = w_init/w_init.sum(0)
    else:
        if len(init_weights.shape)==1:
            init_weights = initialize_from_assignments(init_weights, clusters,
                    max_assign_weight)
        w_init = init_weights.copy()
    return means, w_init

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


Question: creates L3 classes and sets IDs

private Level3Element mapClass(BioPAXElement bpe) {
		Level3Element newElement = null;

		if(bpe instanceof physicalEntityParticipant)
		{
			String id = pep2PE.get(bpe.getUri());

			if(id == null) {
				log.warn("No mapping possible for " + bpe.getUri());
				return null;
			}
			else if (id.equals(bpe.getUri()))
			{
				// create a new simplePhysicalEntity
				//(excluding Complex and basic PhysicalEntity that map directly and have no ERs)
				newElement = createSimplePhysicalEntity((physicalEntityParticipant)bpe);
			}
		}
		else if(!(bpe instanceof openControlledVocabulary)) // skip oCVs
		{
			// using classesmap.properties to map other types
			String type = bpe.getModelInterface().getSimpleName();
			String newType = classesmap.getProperty(type).trim();
			if (newType != null && factory.canInstantiate(factory.getLevel().getInterfaceForName(newType)))
            {
				newElement = (Level3Element) factory.create(newType, bpe.getUri());
			} else {
				if(log.isDebugEnabled())
					log.debug("No mapping found for " + type);
				return null;
			}
		}

		return newElement;
	}

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.PEC__TRIPLETS:
				return triplets != null && !triplets.isEmpty();
		}
		return super.eIsSet(featureID);
	}

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


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

public IfcStructuralSurfaceTypeEnum createIfcStructuralSurfaceTypeEnumFromString(EDataType eDataType,
			String initialValue) {
		IfcStructuralSurfaceTypeEnum result = IfcStructuralSurfaceTypeEnum.get(initialValue);
		if (result == null)
			throw new IllegalArgumentException(
					"The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
		return result;
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question:
Get prototype name.

@return prototype name

public String getPrototypeName() {
		String name = getClass().getName();
		if (name.startsWith(ORG_GEOMAJAS)) {
			name = name.substring(ORG_GEOMAJAS.length());
		}
		name = name.replace(".dto.", ".impl.");
		return name.substring(0, name.length() - 4) + "Impl";
	}

func (m *MockGauge) Describe(arg0 chan<- *prometheus.Desc) {
	m.ctrl.Call(m, "Describe", arg0)
}

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


Question: Interpolated flux at a given wavelength (calls np.interp).

def get_line_flux(line_wave, wave, flux, **kwargs):
    """"""
    return np.interp(line_wave, wave, flux, **kwargs)

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

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


Question:
Remove a DAO from the cache. This is necessary if we've registered it already but it throws an exception during
configuration.

public static synchronized void unregisterDao(ConnectionSource connectionSource, Dao<?, ?> dao) {
		if (connectionSource == null) {
			throw new IllegalArgumentException("connectionSource argument cannot be null");
		}
		removeDaoToClassMap(new ClassConnectionSource(connectionSource, dao.getDataClass()));
	}

public function persistProfile(Varien_Event_Observer $event) {
        if (!method_exists('Varien_Profiler', 'isEnabled')) {
            Mage::log('Looks like the wrong Profiler class is being loaded at this point.');
            return;
        }
        if (Varien_Profiler::isEnabled() && Varien_Profiler::checkThresholds()) {
            $run = Mage::getModel('aoe_profiler/run'); /* @var $run Aoe_Profiler_Model_Run */
            $run->loadStackLogFromProfiler();
            $run->populateMetadata();
            try {
                $run->save();
            } catch (Exception $e) {
                Mage::log('Error while saving Aoe_Profiler data: '. $e->getMessage());
            }
        }
    }

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


Question:
/*
create_field()

Create the HTML interface for your field

@type	action
@since	3.6
@date	23/01/13

@param	$field - an array holding all the field's data

function create_field( $field )
	{
		// vars
		$single_name = $field['name'];

		// multi select?
		if( $field['field_type'] == 'multi_select' )
		{
			$field['multiple'] = 1;
			$field['field_type'] = 'select';
			$field['name'] .= '[]';
		}
		elseif( $field['field_type'] == 'checkbox' )
		{
			$field['name'] .= '[]';
		}

		// value must be array!
		if( !is_array($field['value']) )
		{
			$field['value'] = array( $field['value'] );
		}

		// vars
		$args = array(
			'taxonomy'     => $field['taxonomy'],
			'hide_empty'   => false,
			'style'        => 'none',
			'walker'       => new acf_taxonomy_field_walker( $field ),
		);

		$args = apply_filters('acf/fields/taxonomy/wp_list_categories', $args, $field );

		?>
<div class="acf-taxonomy-field" data-load_save="<?php echo $field['load_save_terms']; ?>">
	<input type="hidden" name="<?php echo $single_name; ?>" value="" />

	<?php if( $field['field_type'] == 'select' ): ?>

		<select id="<?php echo $field['id']; ?>" name="<?php echo $field['name']; ?>" <?php if( $field['multiple'] ): ?>multiple="multiple" size="5"<?php endif; ?>>
			<?php if( $field['allow_null'] ): ?>
				<option value=""><?php _e("None", 'acf'); ?></option>
			<?php endif; ?>

	<?php else: ?>

			<?php if( $field['allow_null'] ): ?>

						<input type="<?php echo $field['field_type']; ?>" name="<?php echo $field['name']; ?>" value="" /> <?php _e("None", 'acf'); ?>

			<?php endif; ?>

	<?php endif; ?>

			<?php wp_list_categories( $args ); ?>

	<?php if( $field['field_type'] == 'select' ): ?>

		</select>

	<?php else: ?>

	<?php endif; ?>

	<?php

	}

protected function init_shortcode_ui( $tag ) {
		$shortcode_ui_class = $this->get_shortcode_ui_class( $tag );

		$this->shortcode_uis[] = $this->instantiate(
			ShortcodeUIInterface::class,
			$shortcode_ui_class,
			[
				'shortcode_tag' => $tag,
				'config'        => $this->config->getSubConfig( $tag, self::KEY_UI ),
				'dependencies'  => $this->dependencies,
			]
		);
	}

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


Question:
@param array $tags

@return Tag|null

private function getTransformerTag(array $tags)
    {
        $transFormerTags = array_values(
            array_filter($tags, function ($tag) {
                return ($tag instanceof Tag) && in_array(strtolower($tag->getName()), ['transformer', 'transformercollection']);
            })
        );

        return array_first($transFormerTags);
    }

func (m *MockLambdaAPI) ListTagsRequest(arg0 *lambda.ListTagsInput) (*request.Request, *lambda.ListTagsOutput) {
	ret := m.ctrl.Call(m, "ListTagsRequest", arg0)
	ret0, _ := ret[0].(*request.Request)
	ret1, _ := ret[1].(*lambda.ListTagsOutput)
	return ret0, ret1
}

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


Question: // GetAllAWSApplicationAutoScalingScalingPolicyResources retrieves all AWSApplicationAutoScalingScalingPolicy items from an AWS CloudFormation template

func (t *Template) GetAllAWSApplicationAutoScalingScalingPolicyResources() map[string]*resources.AWSApplicationAutoScalingScalingPolicy {
	results := map[string]*resources.AWSApplicationAutoScalingScalingPolicy{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSApplicationAutoScalingScalingPolicy:
			results[name] = resource
		}
	}
	return results
}

def build_role(self, name, policies=False):

        # Build role template
        if policies:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                    ManagedPolicyArns=policies,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))
        else:
            role = self.__template.add_resource(
                Role(
                    self.name_strip(name),
                    AssumeRolePolicyDocument=Policy(
                        Version=self.VERSION_IAM,
                        Statement=[
                            Statement(
                                Effect=Allow,
                                Principal=Principal(
                                    "Service", self.__role_principals
                                ),
                                Action=[AssumeRole],
                            )
                        ]
                    ),
                    Path=self.__role_path,
                ))
            # Add role to list for default policy
            self.__roles_list.append(troposphere.Ref(role))

        return role

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


Question:
Converts body into a pattern i.e. a point in the features space.

    Applies features to the body lines and sums up the results.
    Elements of the pattern indicate how many times a certain feature occurred
    in the last lines of the body.

def build_pattern(body, features):
    '''
    '''
    line_patterns = apply_features(body, features)
    return reduce(lambda x, y: [i + j for i, j in zip(x, y)], line_patterns)

def run_postdecode_hooks(decode_hook_args, dataset_split):
  """"""
  hooks = decode_hook_args.problem.decode_hooks
  if not hooks:
    return
  global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir)
  if global_step is None:
    tf.logging.info(
        "Skipping decode hooks because no checkpoint yet available.")
    return
  tf.logging.info("Running decode hooks.")
  parent_dir = os.path.join(decode_hook_args.output_dirs[0], os.pardir)
  child_dir = decode_hook_args.decode_hparams.summaries_log_dir
  if dataset_split is not None:
    child_dir += "_{}".format(dataset_split)
  final_dir = os.path.join(parent_dir, child_dir)
  summary_writer = tf.summary.FileWriter(final_dir)

  for hook in hooks:
    # Isolate each hook in case it creates TF ops
    with tf.Graph().as_default():
      summaries = hook(decode_hook_args)
    if summaries:
      summary = tf.Summary(value=list(summaries))
      summary_writer.add_summary(summary, global_step)
  summary_writer.close()
  tf.logging.info("Decode hooks done.")

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


Question:
Clear the entire database. This should be used when logging out of a client
to prevent mixing data between accounts.
@return {Promise} Resolved when the database is cleared.

function() {
        return new Promise((resolve, reject) => {
            console.log(`Removing indexeddb instance: ${this._dbName}`);
            const req = this.indexedDB.deleteDatabase(this._dbName);

            req.onblocked = () => {
                console.log(
                    `can't yet delete indexeddb ${this._dbName}` +
                    ` because it is open elsewhere`,
                );
            };

            req.onerror = (ev) => {
                // in firefox, with indexedDB disabled, this fails with a
                // DOMError. We treat this as non-fatal, so that we can still
                // use the app.
                console.warn(
                    `unable to delete js-sdk store indexeddb: ${ev.target.error}`,
                );
                resolve();
            };

            req.onsuccess = () => {
                console.log(`Removed indexeddb instance: ${this._dbName}`);
                resolve();
            };
        });
    }

def _cleanup(self) -> None:
        """"""
        if self._cleanup_handle:
            self._cleanup_handle.cancel()

        now = self._loop.time()
        timeout = self._keepalive_timeout

        if self._conns:
            connections = {}
            deadline = now - timeout
            for key, conns in self._conns.items():
                alive = []
                for proto, use_time in conns:
                    if proto.is_connected():
                        if use_time - deadline < 0:
                            transport = proto.transport
                            proto.close()
                            if (key.is_ssl and
                                    not self._cleanup_closed_disabled):
                                self._cleanup_closed_transports.append(
                                    transport)
                        else:
                            alive.append((proto, use_time))

                if alive:
                    connections[key] = alive

            self._conns = connections

        if self._conns:
            self._cleanup_handle = helpers.weakref_handle(
                self, '_cleanup', timeout, self._loop)

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


Question: this = this AND other

public void intersect(OpenBitSet other) {
        int newLen= Math.min(this.wlen,other.wlen);
        long[] thisArr = this.bits;
        long[] otherArr = other.bits;
        // testing against zero can be more efficient
        int pos=newLen;
        while(--pos>=0) {
            thisArr[pos] &= otherArr[pos];
        }
        if (this.wlen > newLen) {
            // fill zeros from the new shorter length to the old length
            Arrays.fill(bits,newLen,this.wlen,0);
        }
        this.wlen = newLen;
    }

func neq(lhs Expression, rhs interface{}) BooleanExpression {
	return checkBoolExpType(EQ_OP, lhs, rhs, true)
}

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


Question:
Reads characters until the 'end' character is encountered.

@param out
The StringBuilder to write to.
@param in
The Input String.
@param start
Starting position.
@param end
End characters.
@return The new position or -1 if no 'end' char was found.

public final static int readUntil(final StringBuilder out, final String in, final int start, final char end)
    {
        int pos = start;
        while (pos < in.length())
        {
            final char ch = in.charAt(pos);
            if (ch == '\\' && pos + 1 < in.length())
            {
                pos = escape(out, in.charAt(pos + 1), pos);
            }
            else
            {
                if (ch == end)
                {
                    break;
                }
                out.append(ch);
            }
            pos++;
        }

        return (pos == in.length()) ? -1 : pos;
    }

public double getSolution(double targetValue, double initGuess) {
    double rMax = 1.0;
    double oldValue = -1;
    for (int i = 0; i < MAXIMUM_ITERATION; ++i) {
      double value = targetFunction(rMax);
      if (value >= targetValue) {
        break;
      }
      if (equals(value, oldValue)) {
        return rMax; // Target value is not feasible. Just return rMax
      }
      rMax *= 2;
    }
    double left = 0;
    double right = rMax;
    double mid = initGuess > left && initGuess < right ?
        initGuess : (left + right) / 2.0;
    for (int i = 0; i < MAXIMUM_ITERATION; ++i) {
      double value = targetFunction(mid);
      if (equals(value, targetValue)) {
        return mid;
      }
      if (value < targetValue) {
        left = mid;
      } else {
        right = mid;
      }
      mid = (left + right) / 2.0;
    }
    return right;
  }

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


Question:
生成用户签名
@param string $identifier 用户名
@param int $expireTime 签名有效期默认3600秒
@return string 生成的UserSig 失败时为false
@throws InvalidConfigException

public function make($identifier, $expireTime = 3600)
    {
        $json = [
            'TLS.account_type' => $this->accountType,
            'TLS.identifier' => (string)$identifier,
            'TLS.appid_at_3rd' => (string)$this->appId,
            'TLS.sdk_appid' => (string)$this->appId,
            'TLS.expire_after' => (string)$expireTime,
            'TLS.version' => '201512300000',
            'TLS.time' => (string)time()
        ];

        $content = $this->genSignatureContent($json);
        $signature = $this->makeSignature($content);
        $json['TLS.sig'] = base64_encode($signature);
        if ($json['TLS.sig'] === false) {
            throw new SignatureException('base64_encode error.');
        }
        $json_text = json_encode($json);
        if ($json_text === false) {
            throw new SignatureException('json_encode error.');
        }
        $compressed = gzcompress($json_text);
        if ($compressed === false) {
            throw new SignatureException('gzcompress error.');
        }
        return $this->base64Encode($compressed);

    }

func (cli *HyperClient) HyperCmdPush(args ...string) error {
	var parser = gflag.NewParser(nil, gflag.Default)
	parser.Usage = "push NAME[:TAG]\n\nPush an image to a Docker registry server"
	args, err := parser.ParseArgs(args)
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	// we need to get the image name which will be used to create a container
	if len(args) == 0 {
		return fmt.Errorf("\"push\" requires a minimum of 1 argument, please provide the image name.")
	}
	name := args[0]

	ref, err := reference.ParseNamed(name)
	if err != nil {
		return err
	}

	var tag string
	switch x := ref.(type) {
	case reference.Canonical:
		return fmt.Errorf("cannot push a digest reference")
	case reference.NamedTagged:
		tag = x.Tag()
	}

	// Resolve the Repository name from fqn to RepositoryInfo
	repoInfo, err := registry.ParseRepositoryInfo(ref)
	if err != nil {
		return err
	}
	// Resolve the Auth config relevant for this server
	authConfig := registry.ResolveAuthConfig(cli.configFile.AuthConfigs, repoInfo.Index)
	// If we're not using a custom registry, we know the restrictions
	// applied to repository names and can warn the user in advance.
	// Custom repositories can have different rules, and we must also
	// allow pushing by image ID.
	if repoInfo.Official {
		username := authConfig.Username
		if username == "" {
			username = "<user>"
		}
		return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository to <user>/<repo> (ex: %s/%s)", username, ref.Name())
	}

	push := func(auth types.AuthConfig) (io.ReadCloser, string, int, error) {
		return cli.client.Push(tag, repoInfo.String(), auth)
	}

	body, ctype, _, err := cli.requestWithLogin(repoInfo.Index, push, "push")
	if err != nil {
		return err
	}

	return cli.readStreamOutput(body, ctype, cli.isTerminalOut, cli.out, cli.err)
}

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


Question:
/*
(non-Javadoc)

@see com.ibm.ws.sib.processor.impl.interfaces.ControllableResource#deregisterControlAdapterMBean()

@Override
    public void deregisterControlAdapterMBean()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "deregisterControlAdapterAsMBean");
        subscriptionControlAdaptor.dereferenceControllable();
        subscriptionControlAdaptor = null;
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "deregisterControlAdapterAsMBean");
    }

public void free() {
        if (handle != 0L) {
            Log.d(LogDomain.REPLICATOR, "handle: " + handle);
            Log.d(
                LogDomain.REPLICATOR,
                "replicatorContext: " + replicatorContext + " $" + replicatorContext.getClass());
            Log.d(
                LogDomain.REPLICATOR,
                "socketFactoryContext: " + socketFactoryContext + " $" + socketFactoryContext.getClass());
            free(handle, replicatorContext, socketFactoryContext);
            handle = 0L;
        }

        if (replicatorContext != null) {
            CONTEXT_TO_C4_REPLICATOR_MAP.remove(this.replicatorContext);
            replicatorContext = null;
        }
    }

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


Question:
Shows a list of languages.

@return void

public function index()
    {
        $this->loadModel('Locale.Languages');
        $languages = $this->Languages
            ->find()
            ->order(['ordering' => 'ASC'])
            ->all();

        $this->title(__d('locale', 'Languages List'));
        $this->set('languages', $languages);
        $this->Breadcrumb->push('/admin/locale');
    }

public function langChooser()
    {
        $homepage = $this->repository->findBy('is_home', 1);
        if (!$homepage) {
            app('log')->error('No homepage found.');
            abort(404);
        }
        $locales = TypiCMS::enabledLocales();

        return view('core::public.lang-chooser')
            ->with(compact('homepage', 'locales'));
    }

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


Question:
/*
(non-Javadoc)

@see javax.el.FunctionMapper#resolveFunction(java.lang.String, java.lang.String)

public Method resolveFunction(String prefix, String localName)
    {
        if (_functions != null)
        {
            Function f = (Function) _functions.get(prefix + ":" + localName);
            return f.getMethod();
        }

        return null;
    }

def from_string(cls, xml_string, validate=True):

        return xmlmap.load_xmlobject_from_string(xml_string, xmlclass=cls, validate=validate)

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


Question:
Collect relations for saving.

@param $field
@param $name

protected function collectRelations($field, $name)
    {
        if ($field instanceof HasOne && $field->hasRelation()) {
            $relation = $field->getRelation();
            $this->relations[$relation][$name] = $this->input($name);
        }

        if ($field->hasRelation()) {
            $relation = $field->getRelation();

            // register relation
            if (!array_has($this->relations, $relation)) {
                $this->relations[$relation] = [];
            }

            if (!$field->getTranslatable()) {
                $this->relations[$relation][$name] = $this->input("{$relation}.{$name}");
            }
        }
    }

public function format(ParameterBag $trackingParameters)
    {
        $cu = null;

        if (
            $trackingParameters->has('c')
            && $trackingParameters->has('u')
        ) {
            $cu = sprintf(
                '%s~%s',
                $trackingParameters->get('c'),
                $trackingParameters->get('u')
            );
        }

        return [
            'cu' => $cu,
        ];
    }

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


Question:
splits arguments into parameters and files (if any).

@param array $params

@return array

private function splitParams(array $params)
    {
        $parameters = [];
        $files      = [];

        foreach ($params as $name => $value) {
            if (is_readable($value)) { //file
                $files[$name] = $value;
            } else {
                $parameters[$name] = $value;
            }
        }

        return [$parameters, $files];
    }

public function main()
    {
        $this->out('Welcome to the Proffer shell.');
        $this->out('This shell can be used to regenerate thumbnails and cleanup unlinked images.');
        $this->hr();
        $this->out($this->OptionParser->help());
    }

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


Question:
Handle the insert action type.

        Creates new document to be created in this collection.
        This allows you to stage a creation of an object

        :param dict revision: The revision dictionary

def __insert_action(self, revision):

        revision["patch"]["_id"] = ObjectId(revision.get("master_id"))

        insert_response = yield self.collection.insert(revision.get("patch"))

        if not isinstance(insert_response, str):
            raise DocumentRevisionInsertFailed()

func AddActionPruneSettings(pool *StatePool) error {
	st := pool.SystemState()
	err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
		settingsChanged :=
			maybeUpdateSettings(doc.Settings, config.MaxActionResultsAge, config.DefaultActionResultsAge)
		settingsChanged =
			maybeUpdateSettings(doc.Settings, config.MaxActionResultsSize, config.DefaultActionResultsSize) || settingsChanged
		return settingsChanged, nil
	})
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}

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


Question:
Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}

@param value
Java instance representing xml element's value.
@return
the new instance of {@link JAXBElement }{@code <}{@link Object }{@code >}

@XmlElementDecl(namespace = "http://www.opengis.net/citygml/cityfurniture/1.0", name = "_GenericApplicationPropertyOfCityFurniture")
    public JAXBElement<Object> create_GenericApplicationPropertyOfCityFurniture(Object value) {
        return new JAXBElement<Object>(__GenericApplicationPropertyOfCityFurniture_QNAME, Object.class, null, value);
    }

public static MethodInstance getGetter(Class clazz, String prop) throws PageException, NoSuchMethodException {
	String getterName = "get" + StringUtil.ucFirst(prop);
	MethodInstance mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(getterName), ArrayUtil.OBJECT_EMPTY);

	if (mi == null) {
	    String isName = "is" + StringUtil.ucFirst(prop);
	    mi = getMethodInstanceEL(null, clazz, KeyImpl.getInstance(isName), ArrayUtil.OBJECT_EMPTY);
	    if (mi != null) {
		Method m = mi.getMethod();
		Class rtn = m.getReturnType();
		if (rtn != Boolean.class && rtn != boolean.class) mi = null;
	    }
	}

	if (mi == null) throw new ExpressionException("No matching property [" + prop + "] found in [" + Caster.toTypeName(clazz) + "]");
	Method m = mi.getMethod();

	if (m.getReturnType() == void.class)
	    throw new NoSuchMethodException("invalid return Type, method [" + m.getName() + "] for Property [" + getterName + "] must have return type not void");

	return mi;
    }

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


Question:
写入文件流

@param string $path
@param resource $resource
@param array $config

public function writeStream($path, $resource, Config $config)
    {
        try{
            //获得一个临时文件
            $tmpfname       = FileFunction::getTmpFile();

            file_put_contents($tmpfname, $resource);

            $this->getOss()->uploadFile($this->bucket, $path, $tmpfname, $option = []);

            //删除临时文件
            FileFunction::deleteTmpFile($tmpfname);

            return true;
        }
        catch (OssException $e){

        }
        return false;
    }

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

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

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


Question:
A collection of {@link WebLink} instances.

@constructor

function() {
  var coll = Object.create(Array.prototype);
  coll = (Array.apply(coll, arguments) || coll);

  LinkCollection.injectClassMethods(coll);
  return (coll);
}

protected void init(Object target, PropertyInfo propInfo, PropertyGrid propGrid) {
        this.target = target;
        this.propInfo = propInfo;
        this.propGrid = propGrid;
        this.index = propGrid.getEditorCount();
        wireController();
    }

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


Question:
Gets the post counts for each supplied post type.

@param array $post_types Post types to fetch counts for.
@return array Associative array of post counts keyed by post type.

protected function get_counts( $post_types ) {
		global $wpdb;

		if ( count( $post_types ) <= 0 ) {
			return [];
		}

		$query = $wpdb->prepare(
			"SELECT `post_type`, COUNT(*) AS `count`
			FROM $wpdb->posts
			WHERE `post_type` IN (" . implode( ',', array_fill( 0, count( $post_types ), '%s' ) ) . ')
			GROUP BY `post_type`',
			$post_types
		);
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $query is already prepared above.
		$counts = $wpdb->get_results( $query );

		// Make sure there's a count for every item.
		$counts = array_merge(
			array_fill_keys( $post_types, 0 ),
			wp_list_pluck( $counts, 'count', 'post_type' )
		);

		return $counts;
	}

static public function httpPost($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, self::_buildPost($data));
        list($content, $status) = array(curl_exec($curl), curl_getinfo($curl), curl_close($curl));
        return (intval($status["http_code"]) === 200) ? $content : false;
    }

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


Question:
Remove an item from the grid (and DOM) and re-render.

@param {jQuery} item

function(item) {
        item = $(item);

        // Using event `remove` will cause the DOM element to delete itself
        this.fireEvent('removing', [item]);

        this.items.filter(item).remove();

        this.refresh();
    }

function Resolve(context, model) {
        if (model == null) {
            // 清空context
            for (var prop in context) {
                var target = context[prop];
                if (target instanceof view_4.View) {
                    var propName = target.PropertyName();
                    if (propName) {
                        if (target instanceof text_3.TextView || target instanceof choice_1.ChoiceView) {
                            target.Clear();
                        }
                        else if (target instanceof list_2.ListView) {
                            target.SetData([]);
                        }
                        else {
                            console.warn(propName + " clear failed, missing clear method!");
                        }
                    }
                }
            }
            return;
        }
        for (var prop in context) {
            var target = context[prop];
            if (target instanceof view_4.View) {
                var propName = target.PropertyName();
                if (propName) {
                    var value = model[propName];
                    if (value) {
                        // 注入
                        if (target instanceof text_3.TextView || target instanceof choice_1.ChoiceView) {
                            target.SetValue(value);
                        }
                        else if (target instanceof list_2.ListView && $.isArray(value)) {
                            target.SetData(value);
                        }
                        else {
                            console.warn(propName + " resolve failed, control type is mismatching!");
                        }
                    }
                    else {
                        console.warn(propName + " resolve failed, value invalid!");
                    }
                }
            }
        }
    }

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


Question:
Adds a modifier to the find operation

@param key the modifier name
@param value the modifier value
@return this

public FindOptions modifier(final String key, final Object value) {
        options.getModifiers().put(key, value);
        return this;
    }

protected function filter()
	{
		foreach ($this->filters as $attribute => $filters) {
			// Check if the attribute is present in the input data
			if (!array_key_exists($attribute, $this->data)) {
				continue;
			}

			$data = $this->data[$attribute];

			foreach ($filters as $filter) {
				// The format for specifying filter and parameters follows an
				// easy {filter}:{parameters} formatting convention.
				if (strpos($filter, ':') !== false) {
					list($filter, $parameterList) = explode(':', $filter, 2);
					$parameters = explode(',', $parameterList);
				} else {
					$parameters = [];
				}

				if (method_exists($this, $this->camelCase($filter))) {
					$data = $this->filterWalker($filter, $data, $parameters);
				} elseif (isset($this->extensions[$filter])) {
					$data = $this->filterExtensionWalker($filter, $data, $parameters);
				} else {
					throw new \Exception("'$filter' is not a valid filter.");
				}
			}

			$this->filteredData[$attribute] = $data;
		}

		return $this->filteredData;
	}

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


Question:
Execute the console command.

@return void

public function handle()
    {
        $this->resource = $this->getResourceOnly();
        $this->settings = config('generators.defaults');

        $this->callModel();
        $this->callView();
        $this->callRepository();
        $this->callController();
        $this->callMigration();
        $this->callSeed();
        $this->callMigrate();

        // confirm dump autoload
        if ($this->confirm("Run 'composer dump-autoload'?")) {
            $this->composer->dumpAutoloads();
        }

        $this->info('All Done!');
        $this->info('Remember to add ' . "`Route::resource('" . str_replace('_', '-',
                $this->getCollectionName()) . "', '" . $this->getResourceControllerName() . "');`" . ' in `routes\\web.php`');
    }

function run(cmd){

        var proc = require('child_process'),
            done = grunt.task.current.async(); // Tells Grunt that an async task is complete

        proc.exec(cmd,
            function(error, stdout, stderr){
                if(stderr){
                    grunt.log.writeln('ERROR: ' + stderr).error();
                }
                grunt.log.writeln(stdout);
                done(error);
            }
        );
    }

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


Question:
// MailParticipants sends new issue thread created emails to repository watchers
// and mentioned people.

func (issue *Issue) MailParticipants() (err error) {
	mentions := markup.FindAllMentions(issue.Content)
	if err = updateIssueMentions(x, issue.ID, mentions); err != nil {
		return fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
	}

	if err = mailIssueCommentToParticipants(issue, issue.Poster, mentions); err != nil {
		log.Error(2, "mailIssueCommentToParticipants: %v", err)
	}

	return nil
}

def handle_action(self, channel, nick, msg):
		""

		messages = ()
		for handler in Handler.find_matching(msg, channel):
			exception_handler = functools.partial(
				self._handle_exception,
				handler=handler,
			)
			rest = handler.process(msg)
			client = connection = event = None
			# for regexp handlers
			match = rest
			f = handler.attach(locals())
			results = pmxbot.itertools.generate_results(f)
			clean_results = pmxbot.itertools.trap_exceptions(results, exception_handler)
			messages = itertools.chain(messages, clean_results)
			if not handler.allow_chain:
				break
		self._handle_output(channel, messages)

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


Question:
Заменяет псевдонимы в пути на их значения.

@param string $path

@return string

protected function replaceAliases($path)
    {
        $toSearch = array_map(function ($item) {
            return "@{$item}";
        }, array_keys($this->aliases));

        $toReplace = array_values($this->aliases);

        return str_replace($toSearch, $toReplace, $path);
    }

private function getViewPath($name)
    {

        $module = $this->module_name !== NULL ? ($this->module_name) . DSC : '';
        return $this->getRealPath('views' . DSC . $module . $name);
    }

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


Question:
Delete multiple files or folders

@param LibraryType $library Library object
@param array       $paths   Array with file and folder paths (they must be in the same folder)

@return bool
@throws \GuzzleHttp\Exception\GuzzleException

public function delete(LibraryType $library, array $paths): bool
    {
        // do not allow empty paths
        if (empty($paths)) {
            return false;
        }

        // get the folder path
        // this path must be the same for all files!
        $folderPath = dirname($paths[0]);

        $fileNames = $this->preparePaths($folderPath, $paths);

        if (empty($fileNames)) {
            return false;
        }

        $folderPath = str_replace("\\", "/", $folderPath); // windows compatibility

        $uri = sprintf(
            '%s/repos/%s/fileops/delete/?p=%s',
            $this->clipUri($this->client->getConfig('base_uri')),
            $library->id,
            $folderPath
        );

        $response = $this->client->request(
            'POST',
            $uri,
            [
                'headers'   => ['Accept' => 'application/json'],
                'multipart' => [
                    [
                        'name'     => 'file_names',
                        'contents' => $fileNames,
                    ],
                ],
            ]
        );

        return $response->getStatusCode() === 200;
    }

public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/config/config.php', 'requester');

        $this->app['requester'] = $this->app->share(function ($app) {
            return new Requester(new GuzzleClient(), config('requester'));
        });
    }

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


Question:
Sets the contraction constant, which must be in the range (0, 1)
@param contraction the contraction constant

public void setContraction(double contraction)
    {
        if(contraction >= 1 || contraction <= 0 || Double.isNaN(contraction) || Double.isInfinite(contraction) )
            throw new ArithmeticException("Contraction constant must be > 0 and < 1, not " + contraction);
        this.contraction = contraction;
    }

func SetOrdererEnv(cmd *cobra.Command, args []string) {
	// read in the legacy logging level settings and, if set,
	// notify users of the FABRIC_LOGGING_SPEC env variable
	var loggingLevel string
	if viper.GetString("logging_level") != "" {
		loggingLevel = viper.GetString("logging_level")
	} else {
		loggingLevel = viper.GetString("logging.level")
	}
	if loggingLevel != "" {
		mainLogger.Warning("CORE_LOGGING_LEVEL is no longer supported, please use the FABRIC_LOGGING_SPEC environment variable")
	}
	// need to init logging here as cobra does not currently support
	// chaining PersistentPreRun functions
	loggingSpec := os.Getenv("FABRIC_LOGGING_SPEC")
	flogging.InitFromSpec(loggingSpec)
	// set the orderer environment from flags
	viper.Set("orderer.tls.rootcert.file", caFile)
	viper.Set("orderer.tls.clientKey.file", keyFile)
	viper.Set("orderer.tls.clientCert.file", certFile)
	viper.Set("orderer.address", OrderingEndpoint)
	viper.Set("orderer.tls.serverhostoverride", ordererTLSHostnameOverride)
	viper.Set("orderer.tls.enabled", tlsEnabled)
	viper.Set("orderer.tls.clientAuthRequired", clientAuth)
	viper.Set("orderer.client.connTimeout", connTimeout)
}

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