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: file_manager.go path of file: ./repos/kubeedge/vendor/github.com/vmware/govmomi/object the code of the file until where you have to start completion: /* Copyright (c) 2015 VMware, Inc. All Rights Reserved. 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 t
func (f FileManager) MakeDirectory(ctx context.Context, name string, dc *Datacenter, createParentDirectories bool) error { req := types.MakeDirectory{ This: f.Reference(), Name: name, CreateParentDirectories: types.NewBool(createParentDirectories), } if dc != nil { ref := dc.Reference() req.Datacenter = &ref } _, err := methods.MakeDirectory(ctx, f.c, &req) return err }
415,116
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: headers.rs path of file: ./repos/nushell/crates/nu-command/tests/commands the code of the file until where you have to start completion: use nu_test_support::{nu, pipeline}; #[test] fn headers_uses_first_row_as_header() { let actual = nu!( cwd: "tests/fixtures/formats", pipeline(
fn headers_invalid_column_type_array() { let actual = nu!(pipeline( " [[a b]; [[f,g], 2], [3,4] ] | headers" )); assert!(actual .err .contains("needs compatible type: Null, String, Bool, Float, Int")); }
327,706
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: order.rs path of file: ./repos/cube/rust/cubesql/cubesql/src/compile/rewrite/rules/wrapper the code of the file until where you have to start completion: use crate::compile::rewrite::{ analysis::LogicalPlanAnalysis, cube_scan_wrapper, rewrite, rules::wrapper::WrapperRules, sort, wrapped_select, wrapped_select_order_expr_empty_tail, wrapper_pullup_replacer, wrapper_pushdown_replacer, LogicalPlanLanguage, }; use egg::Rewrite; impl WrapperRules { pub fn order_rules(&self, rules: &mut Vec<Rewrite<LogicalPlanLanguage, LogicalPlanAnalysis>>) { rules.extend(vec![rewrite( "wrapper-push-down-order-to-cube-scan", sort( "?order_expr", cube_scan_wrapper( wrapper_pullup_replacer( wrapped_select( "?select_type", "?projection_expr", "?group_expr", "?aggr_expr", "?window_expr", "?cube_scan_input", "?joins", "?filter_expr", "?having_expr", "?limit", "?offset", wrapped_select_order_expr_empty_tail(), "?select_alias", "?select_ungrouped", "?select_ungrouped_scan", ), "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), "CubeScanWrapperFinalized:false", ), ), cube_scan_wrapper( wrapped_select( "?select_type", wrapper_pullup_replacer( "?projection_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?group_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?aggr_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?window_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?cube_scan_input", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), "?joins", wrapper_pullup_replacer( "?filter_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), "?having_expr", "?limit", "?offset", wrapper_pushdown_replacer( "?order_expr", "?alias_to_cube", "?ungrouped",
pub fn order_rules(&self, rules: &mut Vec<Rewrite<LogicalPlanLanguage, LogicalPlanAnalysis>>) { rules.extend(vec![rewrite( "wrapper-push-down-order-to-cube-scan", sort( "?order_expr", cube_scan_wrapper( wrapper_pullup_replacer( wrapped_select( "?select_type", "?projection_expr", "?group_expr", "?aggr_expr", "?window_expr", "?cube_scan_input", "?joins", "?filter_expr", "?having_expr", "?limit", "?offset", wrapped_select_order_expr_empty_tail(), "?select_alias", "?select_ungrouped", "?select_ungrouped_scan", ), "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), "CubeScanWrapperFinalized:false", ), ), cube_scan_wrapper( wrapped_select( "?select_type", wrapper_pullup_replacer( "?projection_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?group_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?aggr_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?window_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), wrapper_pullup_replacer( "?cube_scan_input", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), "?joins", wrapper_pullup_replacer( "?filter_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), "?having_expr", "?limit", "?offset", wrapper_pushdown_replacer( "?order_expr", "?alias_to_cube", "?ungrouped", "?in_projection", "?cube_members", ), "?select_alias", "?select_ungrouped", "?select_ungrouped_scan", ), "CubeScanWrapperFinalized:false", ), )]); Self::list_pushdown_pullup_rules( rules, "wrapper-order-expr", "SortExp", "WrappedSelectOrderExpr", ); }
693,674
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: operator.go path of file: ./repos/meshery/server/internal/graphql/resolver the code of the file until where you have to start completion: package resolver import ( "context" "github.com/gofrs/uuid" "github.com/layer5io/meshery/server/handlers" "github.com/layer5io/meshery/server/i
func (r *Resolver) getOperatorStatus(ctx context.Context, _ models.Provider, connectionID string) (*model.MesheryControllersStatusListItem, error) { unknowStatus := &model.MesheryControllersStatusListItem{ ConnectionID: connectionID, Status: model.MesheryControllerStatusUnkown, Controller: model.GetInternalController(models.MesheryOperator), } handler, ok := ctx.Value(models.HandlerKey).(*handlers.Handler) if !ok { return unknowStatus, nil } inst, ok := handler.ConnectionToStateMachineInstanceTracker.Get(uuid.FromStringOrNil(connectionID)) // If machine instance is not present or points to nil, return unknown status if !ok || inst == nil { return unknowStatus, nil } machinectx, err := utils.Cast[*kubernetes.MachineCtx](inst.Context) if err != nil { r.Log.Error(model.ErrMesheryControllersStatusSubscription(err)) return unknowStatus, nil } controllerhandler := machinectx.MesheryCtrlsHelper.GetControllerHandlersForEachContext() if !ok { return unknowStatus, nil } status := controllerhandler[models.MesheryOperator].GetStatus() return &model.MesheryControllersStatusListItem{ ConnectionID: connectionID, Status: model.GetInternalControllerStatus(status), Controller: model.GetInternalController(models.MesheryOperator), }, nil }
179,690
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: snippets_actions.rb path of file: ./repos/gitlabhq/app/controllers/concerns the code of the file until where you have to start completion: # frozen_string_literal: true module SnippetsActions extend ActiveSupport::Concern include RendersNotes include RendersBlob include PaginatedCollection include Gitlab::NoteableMetadata include Snippets::SendBlob include SnippetsSort include ProductAnalyticsTracking included do skip_before_action :verify_authenticity_token, if: -> { action_name == 'show' && js_request? } track_event :show, name: 'i_snippets_show' respond_to :html end def edit; end # This endpoint is being replaced by Snippets::BlobController#raw # Support for old raw links will be maintainted via this action but # it will only return the first blob found, # see: https://gitlab.com/gitlab-org/gitlab/-/issues/217775 def raw workhorse_set_content_type! # Until we don't migrate all snippets to version # snippets we need to support old `Snippet
def edit; end # This endpoint is being replaced by Snippets::BlobController#raw # Support for old raw links will be maintainted via this action but # it will only return the first blob found, # see: https://gitlab.com/gitlab-org/gitlab/-/issues/217775 def raw workhorse_set_content_type! # Until we don't migrate all snippets to version # snippets we need to support old `SnippetBlob` # blobs if defined?(blob.snippet) send_data( convert_line_endings(blob.data), type: 'text/plain; charset=utf-8', disposition: content_disposition, filename: Snippet.sanitized_file_name(blob.name) ) else send_snippet_blob(snippet, blob) end end def js_request? request.format.js? end # rubocop:disable Gitlab/ModuleWithInstanceVariables def show respond_to do |format| format.html do @note = Note.new(noteable: @snippet, project: @snippet.project) @noteable = @snippet @discussions = @snippet.discussions @notes = prepare_notes_for_rendering(@discussions.flat_map(&:notes)) render 'show' end format.js do if @snippet.embeddable? conditionally_expand_blobs(blobs) render 'shared/snippets/show' else head :not_found end end end end
300,511
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.setGlobalPrivacySettings_handler.go path of file: ./repos/teamgram-server/app/service/biz/user/internal/core the code of the file until where you have to start completion: /* * Created from 'scheme.tl' by 'mtprotoc' * * Copyright (c) 2021-present, Teamgram Studio (https://teamgram.io). * All rights reserved. * * Author: teamgramio (teamgram.io@gmail.com) */ package core import ( "github.com/teamgram/proto/mtproto" "github.com/teamgram/teamgram-server/app/service/biz/user/internal/dal/dataobject" "github.com/teamgram/teamgram-server/app/service/biz/user/user" ) // UserSetGlobalPrivacySettings // user.setGlobalPrivacySettings user_id:int settings:GlobalPrivacySettings = Bool; func (c *UserCore) UserSetGlobalPrivacySettings(in *user.TLUserSetGlobalPrivacySettings)
func (c *UserCore) UserSetGlobalPrivacySettings(in *user.TLUserSetGlobalPrivacySettings) (*mtproto.Bool, error) { var archiveAndMuteNewNoncontactPeers bool if in.GetSettings().GetArchiveAndMuteNewNoncontactPeers_FLAGBOOL() != nil { archiveAndMuteNewNoncontactPeers = mtproto.FromBool(in.GetSettings().GetArchiveAndMuteNewNoncontactPeers_FLAGBOOL()) } else { archiveAndMuteNewNoncontactPeers = in.GetSettings().GetArchiveAndMuteNewNoncontactPeers_FLAGBOOLEAN() } // TODO: globalPrivacySettings#734c4ccb flags:# // archive_and_mute_new_noncontact_peers:flags.0?true // keep_archived_unmuted:flags.1?true // keep_archived_folders:flags.2?true = GlobalPrivacySettings; c.svcCtx.Dao.UserGlobalPrivacySettingsDAO.InsertOrUpdate(c.ctx, &dataobject.UserGlobalPrivacySettingsDO{ UserId: in.UserId, ArchiveAndMuteNewNoncontactPeers: archiveAndMuteNewNoncontactPeers, }) return mtproto.BoolTrue, nil }
83,700
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: OptimalSuperEllipsePrinter.m path of file: ./repos/Swan/Topology Optimization/Homogenization/Sources/VadamecumCalculator the code of the file until where you have to start completion: classdef OptimalSuperEllipseP
function createLevelSet(obj) sM.coord = obj.meshBackground.coord; sM.connec = obj.meshBackground.connec; s.mesh = Mesh_Total(sM); s.widthH = obj.mxV(obj.iter); s.widthV = obj.myV(obj.iter); %s.pnorm = obj.computeSmoothingExponent(); s.pnorm = 2; s.type = 'smoothRectangle'; s.levelSetCreatorSettings = s; s.type = 'LevelSet'; s.scalarProductSettings.epsilon = 1; obj.levelSet = LevelSet(s); end
307,823
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: dapp.rs path of file: ./repos/CYFS/src/service/app-manager/src the code of the file until where you have to start completion: use cyfs_base::{BuckyError, BuckyErrorCode, BuckyResult}; use cyfs_util::{get_app_dir}; use log::*; use serde::Deserialize; use serde_json::Value; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitStatus}; use std::sync::Mutex; use std::time::Duration; use wait_timeout::ChildExt; use crate::process_util::{run, try_stop_process_by_pid}; const STATUS_CMD_TIME_OUT_IN_SECS: u64 = 15; const STOP_CMD_TIME_OUT_IN_SECS: u64 = 60; const START_CMD_TIME_OUT_IN_SECS: u64 = 5 * 60; pub(crate) const INSTALL_CMD_TIME_OUT_IN_SECS: u64 = 15 * 60; #[derive(Deserialize, Clone)] pub struct DAppInfo { id: String, version: String, start: String, status: String, stop: String, install: Vec<String>, executable: Vec<String>, }
pub fn status(&self) -> BuckyResult<bool> { let mut proc = self.process.lock().unwrap(); if proc.is_none() { info!("process obj not exist, check by cmd"); self.status_by_cmd() } else { // app是这个进程起的,通过Child对象来判断状态,也能阻止僵尸进程 info!("process obj exist, try wait"); match proc.as_mut().unwrap().try_wait() { Ok(Some(status)) => { info!("app exited, name={}, status={}", self.info.id, status); let mut process = proc.take().unwrap(); match process.wait() { Ok(_) => { info!("wait app process complete! name={}", self.info.id); } Err(e) => { info!("wait app process error! name={}, err={}", self.info.id, e); } } Ok(false) } Ok(None) => { info!("app running, name={}", self.info.id); Ok(true) } Err(e) => { error!("update app state error, name={}, err={}", self.info.id, e); self.status_by_cmd() } } } }
125,184
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_SEM_gen.m path of file: ./repos/spm/toolbox/SPEM_and_DCM the code of the file until where you have to start completion: function [y,DEM] = spm_SEM_gen(P,MM,U) % Slow/saccadic eye movement prediction scheme % FORMAT [y,DEM] = spm_SEM_gen(P,M,U) % % P - parameters % M - (meta) model structure % U - trial-specific parameter deviates % % y - {[ns,nx];...} - predictions for nx states {trials} % - for ns samples (normalised lag) %
function [y,DEM] = spm_SEM_gen(P,MM,U) % Slow/saccadic eye movement prediction scheme % FORMAT [y,DEM] = spm_SEM_gen(P,M,U) % % P - parameters % M - (meta) model structure % U - trial-specific parameter deviates % % y - {[ns,nx];...} - predictions for nx states {trials} % - for ns samples (normalised lag) % % This smooth pursuit eye movement routine generates one cycle of motion % under prior beliefs about a sinusoidal trajectory with variable phase. % % see also: spm_SEM_gen_full %__________________________________________________________________________ % Karl Friston % Copyright (C) 2013-2022 Wellcome Centre for Human Neuroimaging % trial-specific initial states and parameters %========================================================================== if nargin > 2 % cycle over different conditions %---------------------------------------------------------------------- M = MM; x = M.x; [nu,nc] = size(U); y = cell(1,nc); DEM = cell(1,nc); for i = 1:nc % target location %------------------------------------------------------------------ M.C = M.u{i}; % initial states %------------------------------------------------------------------ M.x = x(i); % condition-specific parameters (encoded in U) %------------------------------------------------------------------ Q = spm_vec(P.A); for j = 1:nu Q = Q + U(j,i)*spm_vec(P.B{j}); end
717,796
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: extensions.rb path of file: ./repos/active_record_replica/lib/active_record_replica the code of the file until where you have to start completion: require 'active_support/concern' module ActiveRecordReplica module Extensions extend ActiveSupport::Concern [:se
def #{select_method}(sql, name = nil, *args) return super if active_record_replica_read_from_primary? ActiveRecordReplica.read_from_primary do reader_connection.#{select_method}(sql, "Replica: \#{name || 'SQL'}", *args) end end
470,484
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: restkeys_test.go path of file: ./repos/storj/satellite/admin the code of the file until where you have to start completion: // Copyright (C) 2020 Storj Labs, Inc. // See LICENSE for copying information. package admin_test import ( "encoding/json" "fmt" "io" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/require" "go.uber.org/zap" "storj.io/common/testcontext" "storj.io/common/testrand" "storj.io/storj/private/testplanet" "storj.io/storj/satellite" "storj.io/storj/satellite/oidc" ) func TestRESTKeys(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 0, UplinkCount: 1, Reconfigure: testplanet.Reconfigure{ Satellite: func(_ *zap.Logger, _ int, config *satellite.Config) { config.Admin.Address = "127.0.0.1:0" }, }, }, func(t *testing.T, ctx *testcontext.Context, planet *testplanet.Planet) { address := planet.Satellites[0].Admin.Admin.Listener.Addr() satellite := planet.Satellites[0] keyService := satellite.API.REST.Keys user, err := planet.Satellites[0].DB.Console().Users().GetByEmail(ctx, planet.Uplinks[0].Projects[0].Owner.Email) require.NoError(t, err) t.Run("create with default expiration", func(t *testing.T) { body := strings.NewReader(`{"expiration":""}`) req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://"+address.String()+"/api/restkeys/%s", user.Email), body) require.NoError(t, err) req.Header.Set("Authorization", satellite.Config.Console.AuthToken) // get current time to check against ExpiresAt now := time.Now() response, err := http.DefaultClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusOK, response.StatusCode) require.Equal(t, "application/json", response.Header.Get("Content-Type")) responseBody, err := io.ReadAll(response.Body) require.NoError(t, err) require.NoError(t, response.Body.Close()) var output struct { APIKey string `json:"apikey"` ExpiresAt time.Time `json:"expiresAt"` } err = json.Unmarshal(responseBody, &output) require.NoError(t, err) userID, exp, err := keyService.GetUserAndExpirationFromKey(ctx, output.APIKey) require.NoError(t, err) require.Equal(t, user.ID, userID) require.False(t, exp.IsZero()) require.False(t, exp.Before(now)) // check the expiration is around the time we expect defaultExpiration := satellite.Config.RESTKeys.DefaultExpiration require.True(t, output.ExpiresAt.After(now.Add(defaultExpiration))) require.True(t, output.ExpiresAt.Before(now.Add(defaultExpiration+time.Hour))) }) t.Run("create with custom expiration", func(t *testing.T) { durationString := "3h" body := strings.NewReader(fmt.Sprintf(`{"expiration":"%s"}`, durationString)) req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://"+address.String()+"/api/restkeys/%s", user.Email), body) require.NoError(t, err) req.Header.Set("Authorization", satellite.Config.Console.AuthToken) // get current time to check against ExpiresAt now := time.Now() response, err := http.DefaultClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusOK, response.StatusCode) require.Equal(t, "application/json", response.Header.Get("Content-Type")) responseBody, err := io.ReadAll(response.Body) require.NoError(t, err) require.NoError(t, response.Body.Close()) var output struct { APIKey string `json:"apikey"` ExpiresAt time.Time `json:"expiresAt"` } err = json.Unmarshal(responseBody, &output) require.NoError(t, err) userID, exp, err := keyService.GetUserAndExpirationFromKey(ctx, output.APIKey) require.NoError(t, err) require.Equal(t, user.ID, userID) require.False(t, exp.IsZero()) require.False(t, exp.Before(now)) // check the expiration is around the time we expect durationTime, err := time.ParseDuration(durationString) require.NoError(t, err) require.True(t, output.ExpiresAt.After(now.Add(durationTime))) require.True(t, output.ExpiresAt.Before(now.Add(durationTime+time.Hour))) }) t.Run("revoke key", func(t *testing.T) { apiKey := testrand.UUID().String() hash, err := keyService.HashKey(ctx, apiKey) require.NoError(t, err) expiresAt, err := keyService.InsertIntoDB(ctx, oidc.OAuthToken{ UserID: user.ID, Kind: oidc.KindRESTTokenV0,
func TestRESTKeys(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 0, UplinkCount: 1, Reconfigure: testplanet.Reconfigure{ Satellite: func(_ *zap.Logger, _ int, config *satellite.Config) { config.Admin.Address = "127.0.0.1:0" }, }, }, func(t *testing.T, ctx *testcontext.Context, planet *testplanet.Planet) { address := planet.Satellites[0].Admin.Admin.Listener.Addr() satellite := planet.Satellites[0] keyService := satellite.API.REST.Keys user, err := planet.Satellites[0].DB.Console().Users().GetByEmail(ctx, planet.Uplinks[0].Projects[0].Owner.Email) require.NoError(t, err) t.Run("create with default expiration", func(t *testing.T) { body := strings.NewReader(`{"expiration":""}`) req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://"+address.String()+"/api/restkeys/%s", user.Email), body) require.NoError(t, err) req.Header.Set("Authorization", satellite.Config.Console.AuthToken) // get current time to check against ExpiresAt now := time.Now() response, err := http.DefaultClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusOK, response.StatusCode) require.Equal(t, "application/json", response.Header.Get("Content-Type")) responseBody, err := io.ReadAll(response.Body) require.NoError(t, err) require.NoError(t, response.Body.Close()) var output struct { APIKey string `json:"apikey"` ExpiresAt time.Time `json:"expiresAt"` } err = json.Unmarshal(responseBody, &output) require.NoError(t, err) userID, exp, err := keyService.GetUserAndExpirationFromKey(ctx, output.APIKey) require.NoError(t, err) require.Equal(t, user.ID, userID) require.False(t, exp.IsZero()) require.False(t, exp.Before(now)) // check the expiration is around the time we expect defaultExpiration := satellite.Config.RESTKeys.DefaultExpiration require.True(t, output.ExpiresAt.After(now.Add(defaultExpiration))) require.True(t, output.ExpiresAt.Before(now.Add(defaultExpiration+time.Hour))) }) t.Run("create with custom expiration", func(t *testing.T) { durationString := "3h" body := strings.NewReader(fmt.Sprintf(`{"expiration":"%s"}`, durationString)) req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://"+address.String()+"/api/restkeys/%s", user.Email), body) require.NoError(t, err) req.Header.Set("Authorization", satellite.Config.Console.AuthToken) // get current time to check against ExpiresAt now := time.Now() response, err := http.DefaultClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusOK, response.StatusCode) require.Equal(t, "application/json", response.Header.Get("Content-Type")) responseBody, err := io.ReadAll(response.Body) require.NoError(t, err) require.NoError(t, response.Body.Close()) var output struct { APIKey string `json:"apikey"` ExpiresAt time.Time `json:"expiresAt"` } err = json.Unmarshal(responseBody, &output) require.NoError(t, err) userID, exp, err := keyService.GetUserAndExpirationFromKey(ctx, output.APIKey) require.NoError(t, err) require.Equal(t, user.ID, userID) require.False(t, exp.IsZero()) require.False(t, exp.Before(now)) // check the expiration is around the time we expect durationTime, err := time.ParseDuration(durationString) require.NoError(t, err) require.True(t, output.ExpiresAt.After(now.Add(durationTime))) require.True(t, output.ExpiresAt.Before(now.Add(durationTime+time.Hour))) }) t.Run("revoke key", func(t *testing.T) { apiKey := testrand.UUID().String() hash, err := keyService.HashKey(ctx, apiKey) require.NoError(t, err) expiresAt, err := keyService.InsertIntoDB(ctx, oidc.OAuthToken{ UserID: user.ID, Kind: oidc.KindRESTTokenV0, Token: hash, }, time.Now(), time.Hour) require.NoError(t, err) require.False(t, expiresAt.IsZero()) req, err := http.NewRequestWithContext(ctx, http.MethodPut, fmt.Sprintf("http://"+address.String()+"/api/restkeys/%s/revoke", apiKey), nil) require.NoError(t, err) req.Header.Set("Authorization", satellite.Config.Console.AuthToken) response, err := http.DefaultClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusOK, response.StatusCode) require.NoError(t, response.Body.Close()) _, _, err = keyService.GetUserAndExpirationFromKey(ctx, apiKey) require.Error(t, err) }) }) }
635,482
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: admGetNDD.m path of file: ./repos/d2d/arFramework3/ThirdParty/StrucID/adimat/opt_sp_derivclass the code of the file until where you have to start completion: function num= admGetNDD(g_obj)
function num= admGetNDD(g_obj) % GETNDD -- Get the (current) number directional derivatives. % % Copyright 2010 Johannes Willkomm, Institute for Scientific Computing % RWTH Aachen University. % Copyright 2001-2004 Andre Vehreschild, Institute for Scientific Computing % RWTH Aachen University % This code is under development! Use at your own risk! Duplication, % modification and distribution FORBIDDEN! if nargin < 1 g_obj = adderiv([],[],'empty'); end
632,432
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: contract_validator.rb path of file: ./repos/rails-api-boilerplate/test/supports the code of the file until where you have to start completion: # frozen_string_literal: true # rubocop:disable Metrics/ModuleLength module Supports module ContractValidator include Suppo
def contract_error_messages(result, contract) errors = contract_errors_parser(contract_error_parser(result, contract)) check_i18n_translations(errors) errors end
46,118
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: dict.go path of file: ./repos/k6/vendor/github.com/klauspost/compress/s2 the code of the file until where you have to start completion: // Copyright (c) 2022+ Klaus Post. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package s2 import ( "bytes" "encoding/binary" "sync" ) const ( // MinDictSize is the minimum dictionary size when repeat has been read.
func MakeDictManual(data []byte, firstIdx uint16) *Dict { if len(data) < MinDictSize || int(firstIdx) >= len(data)-8 || len(data) > MaxDictSize { return nil } var d Dict dict := data d.dict = dict if cap(d.dict) < len(d.dict)+16 { d.dict = append(make([]byte, 0, len(d.dict)+16), d.dict...) } d.repeat = int(firstIdx) return &d }
735,972
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: cat_main_registration1173.m path of file: ./repos/ExploreASL/External/SPMmodified/toolbox/cat12/cat_run1173 the code of the file until where you have to start completion: function [trans,reg] = cat_main_registration1173(job,res
function x = rgrid(d) x = zeros([d(1:3) 3],'single'); [x1,x2] = ndgrid(single(1:d(1)),single(1:d(2))); for i=1:d(3), x(:,:,i,1) = x1; x(:,:,i,2) = x2; x(:,:,i,3) = single(i); end
173,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: builders.rs path of file: ./repos/aws-sdk-rust/sdk/migrationhubrefactorspaces/src/operation/get_environment 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(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
756,211
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: members.rb path of file: ./repos/openproject/db/migrate/tables the code of the file until where you have to start completion: #-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2024 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3
def self.table(migration) create_table migration do |t| t.integer :user_id, default: 0, null: false t.integer :project_id, default: 0, null: false t.datetime :created_on t.boolean :mail_notification, default: false, null: false t.index :project_id, name: 'index_members_on_project_id' t.index %i[user_id project_id], name: 'index_members_on_user_id_and_project_id', unique: true t.index :user_id, name: 'index_members_on_user_id' end end
666,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: settemplate.go path of file: ./repos/bk-cmdb/src/common/index/collections the code of the file until where you have to start completion: /* * Tencent
func init() { // 先注册未规范化的索引,如果索引出现冲突旧,删除未规范化的索引 registerIndexes(common.BKTableNameSetTemplate, deprecatedSetTemplateIndexes) registerIndexes(common.BKTableNameSetTemplate, commSetTemplateIndexes) }
372,488
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: outline_item.rb path of file: ./repos/hexapdf/lib/hexapdf/type the code of the file until where you have to start completion: # -*- encoding: utf-8; frozen_string_literal: true -*- # #-- # This file is part of HexaPDF. # # HexaPDF - A Versatile PDF Creation and Manipulation
def add_item(title, destination: nil, action: nil, position: :last, open: true, text_color: nil, flags: nil) # :yield: item if title.kind_of?(HexaPDF::Object) && title.type == :XXOutlineItem item = title item.delete(:Prev) item.delete(:Next) item.delete(:First) item.delete(:Last) if item[:Count] && item[:Count] >= 0 item[:Count] = 0 else item.delete(:Count) end
362,847
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: circular_focus.rs path of file: ./repos/cursive/cursive-core/src/views the code of the file until where you have to start completion: use crate::{ direction::Direction, event::{Event, EventResult, Key}, view::{View, ViewWrapper}, With, }; /// Adds circular focus to a wrapped view. /// /// Wrap a view in `CircularFocus` to enable wrap-around focus /// (when the focus exits this view, it will come back the other side). /// /// It can be configured to wrap Tab (and Shift+Tab) keys, and/or Arrow keys. pub struct CircularFocus<T: View> { view: T, wrap_tab: bool, wrap_up_down: bool, wrap_left_right: bool, } impl<T: View> CircularFocus<T> { /// Creates a new `CircularFocus` around the given view. /// /// Does not wrap anything by default, /// so you'll want to call one of the setters. pub fn new(view: T) -> Self { CircularFocus { view, wrap_tab: false, wrap_left_right: false, wrap_up_down: false, } } /// Returns `true` if Tab key cause focus to wrap around. pub fn wraps_tab(&self) -> bool { self.wrap_tab } /// Returns `true` if Arrow keys cause focus to wrap around. pub fn wraps_arrows(&self) -> bool { self.wrap_left_right && self.wrap_up_down } /// Return `true` if left/right keys cause focus to wrap around. pub fn wraps_left_right(&self) -> bool { self.wrap_left_right } /// Return `true` if up/down keys cause focus to wrap around. pub fn wraps_up_down(&self) -> bool {
fn wrap_on_event(&mut self, event: Event) -> EventResult { match (self.view.on_event(event.clone()), event) { (EventResult::Ignored, Event::Key(Key::Tab)) if self.wrap_tab => { // Focus comes back! self.view .take_focus(Direction::front()) .unwrap_or(EventResult::Ignored) } (EventResult::Ignored, Event::Shift(Key::Tab)) if self.wrap_tab => { // Focus comes back! self.view .take_focus(Direction::back()) .unwrap_or(EventResult::Ignored) } (EventResult::Ignored, Event::Key(Key::Right)) if self.wrap_left_right => { // Focus comes back! self.view .take_focus(Direction::left()) .unwrap_or(EventResult::Ignored) } (EventResult::Ignored, Event::Key(Key::Left)) if self.wrap_left_right => { // Focus comes back! self.view .take_focus(Direction::right()) .unwrap_or(EventResult::Ignored) } (EventResult::Ignored, Event::Key(Key::Up)) if self.wrap_up_down => { // Focus comes back! self.view .take_focus(Direction::down()) .unwrap_or(EventResult::Ignored) } (EventResult::Ignored, Event::Key(Key::Down)) if self.wrap_up_down => { // Focus comes back! self.view .take_focus(Direction::up()) .unwrap_or(EventResult::Ignored) } (other, _) => other, } }
578,426
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: printed_text.go path of file: ./repos/weapp/ocr the code of the file until where you have to start completion: package ocr import "github.com/medivhzhan/weapp/v3/request" const apiPrintedText = "/cv/ocr/comm" type PrintedTextResponse struct { request.CommonError Items []struct { Text string `json:"text
func (cli *OCR) PrintedTextByFile(filename string, mode RecognizeMode) (*PrintedTextResponse, error) { res := new(PrintedTextResponse) err := cli.ocrByFile(apiPrintedText, filename, mode, res) if err != nil { return nil, err } return res, err }
295,037
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: channel_get_headpoints.m path of file: ./repos/brainstorm3/toolbox/sensors the code of the file until where you have to start completion: function HeadPoints = channel_get_headpoints(ChannelFile, MinHeadPoints, UseEeg) % Get digitized head points in a Brainstorm channel file. % % USAGE: HeadPoints = channel_get_headpoints(ChannelFile, MinHeadPoints=20, UseEeg=1) % HeadPoints = channel_get_headpoints(ChannelMat, MinHeadPoints=20, UseEeg=1) % @============================================================================= % This function is part of the Brainstorm software: % https://neuroimage.usc.edu/brainstorm % % Copyright (c) University of Southern California & McGill University
function HeadPoints = channel_get_headpoints(ChannelFile, MinHeadPoints, UseEeg) % Get digitized head points in a Brainstorm channel file. % % USAGE: HeadPoints = channel_get_headpoints(ChannelFile, MinHeadPoints=20, UseEeg=1) % HeadPoints = channel_get_headpoints(ChannelMat, MinHeadPoints=20, UseEeg=1) % @============================================================================= % This function is part of the Brainstorm software: % https://neuroimage.usc.edu/brainstorm % % Copyright (c) University of Southern California & McGill University % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPLv3 % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % % Authors: Francois Tadel, 2010 % Parse inputs if (nargin < 3) || isempty(UseEeg) UseEeg = 1; end
152,018
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: instrumented_subscriptions.rb path of file: ./repos/rails_event_store/ruby_event_store/lib/ruby_event_store the code of the file until where you have to start completion: # frozen_string_literal:
def instrument(args) instrumentation.instrument("add.subscriptions.rails_event_store", args) do unsubscribe = yield ->() { instrumentation.instrument("remove.subscriptions.rails_event_store", args) do unsubscribe.call end } end end
402,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: headlessexperimental.go path of file: ./repos/k6/vendor/github.com/chromedp/cdproto/headlessexperimental the code of the file until where you have to start completion: // Package headlessexperimental provides the Chrome DevTools Protocol // commands, types, and events for the HeadlessExperimental domain. // // This domain provides experimental commands only supported in headless // mode. // // Generated by the cdproto-gen command. package headlessexperimental // Code generated by cdproto-gen. DO NOT EDIT. impo
func (p *BeginFrameParams) Do(ctx context.Context) (hasDamage bool, screenshotData []byte, err error) { // execute var res BeginFrameReturns err = cdp.Execute(ctx, CommandBeginFrame, p, &res) if err != nil { return false, nil, err } // decode var dec []byte dec, err = base64.StdEncoding.DecodeString(res.ScreenshotData) if err != nil { return false, nil, err } return res.HasDamage, dec, nil }
735,715
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: 1355E_test.go path of file: ./repos/codeforces-go/main/1300-1399 the code of the file until where you have to start completion: package main import ( "github.com/EndlessCheng/codeforces-go/main/testutil" "testing" ) func TestCF1355E(t *testing.T) { // just copy from website rawText := ` inputCopy 3 1 100 100 1 3 8 outp
func TestCF1355E(t *testing.T) { // just copy from website rawText := ` inputCopy 3 1 100 100 1 3 8 outputCopy 12 inputCopy 3 100 1 100 1 3 8 outputCopy 9 inputCopy 3 100 100 1 1 3 8 outputCopy 4 inputCopy 5 1 2 4 5 5 3 6 5 outputCopy 4 inputCopy 5 1 2 2 5 5 3 6 5 outputCopy 3` testutil.AssertEqualCase(t, rawText, 0, CF1355E) }
135,596
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: veteran_device_records_controller.rb path of file: ./repos/vets-api/modules/dhp_connected_devices/app/controllers/dhp_connected_devices the code of the file until where you have to start completion: # frozen_string_literal: true module DhpConnectedDevices class VeteranDeviceRecordsController < ApplicationController service_tag 'connected-devices' def index if @current_user&.icn.blank? render json: { connectionAvailable: false } else device_reco
def index if @current_user&.icn.blank? render json: { connectionAvailable: false } else device_records = Device.veteran_device_records(@current_user) device_records_json = VeteranDeviceRecordSerializer.serialize( device_records[:active], device_records[:inactive] ) device_records_json[:connectionAvailable] = true render json: device_records_json end
576,359
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: summarization.go path of file: ./repos/langchaingo/chains the code of the file until where you have to start completion: package chains import ( "github.com/tmc/langchaingo/llms" "github.
func LoadMapReduceSummarization(llm llms.Model) MapReduceDocuments { mapChain := NewLLMChain(llm, prompts.NewPromptTemplate( _stuffSummarizationTemplate, []string{"context"}, )) combineChain := LoadStuffSummarization(llm) return NewMapReduceDocuments(mapChain, combineChain) }
476,720
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: snapshot.go path of file: ./repos/syft/syft/format/internal/testutil the code of the file until where you have to start completion: package testutil import ( "bytes" "testing" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/an
func AssertEncoderAgainstGoldenSnapshot(t *testing.T, cfg EncoderSnapshotTestConfig) { t.Helper() var buffer bytes.Buffer err := cfg.Format.Encode(&buffer, cfg.Subject) assert.NoError(t, err) actual := buffer.Bytes() if cfg.UpdateSnapshot && !cfg.PersistRedactionsInSnapshot { // replace the expected snapshot contents with the current (unredacted) encoder contents testutils.UpdateGoldenFileContents(t, actual) return } if cfg.Redactor != nil { actual = cfg.Redactor.Redact(actual) } if cfg.UpdateSnapshot && cfg.PersistRedactionsInSnapshot { // replace the expected snapshot contents with the current (redacted) encoder contents testutils.UpdateGoldenFileContents(t, actual) return } var expected []byte if cfg.Redactor != nil { expected = cfg.Redactor.Redact(testutils.GetGoldenFileContents(t)) } else { expected = testutils.GetGoldenFileContents(t) } if cfg.IsJSON { require.JSONEq(t, string(expected), string(actual)) } else { requireEqual(t, expected, actual) } }
117,370
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: utc2posixtime.m path of file: ./repos/glider_toolbox/m/common_tools the code of the file until where you have to start completion: function s = utc2posixtime(d) %UTC2POSIXTIME Convert serial date number in UTC to POSIX time. % % Syntax: % S = UTC2POSIXTIME(D) % % Description: % S = UTC2POSIXTIME(D) returns the POSIX times S corresponding to the serial % date numbers in scalar, vector or array D, using the straight forward % method (see note below). % % Notes: % This function provides a compatibility interface for MATLAB and Octave, % computing the conversion using a straight forward linear scaling: % S = 86400 * (D - 719529) % This is consistent with the POSIX specification (not counting leap seconds, % using the same value for a leap second and its successor). % % Examples: % % Compare the conversion of current time to the default shell current time. % tz_offset = -1;
function s = utc2posixtime(d) %UTC2POSIXTIME Convert serial date number in UTC to POSIX time. % % Syntax: % S = UTC2POSIXTIME(D) % % Description: % S = UTC2POSIXTIME(D) returns the POSIX times S corresponding to the serial % date numbers in scalar, vector or array D, using the straight forward % method (see note below). % % Notes: % This function provides a compatibility interface for MATLAB and Octave, % computing the conversion using a straight forward linear scaling: % S = 86400 * (D - 719529) % This is consistent with the POSIX specification (not counting leap seconds, % using the same value for a leap second and its successor). % % Examples: % % Compare the conversion of current time to the default shell current time. % tz_offset = -1; % s = utc2posixtime(now()+tz_offset/24) % ! date +%s%N % fprintf('%.0f\n',fix(1e+9*s)) % % See also: % POSIXTIME % POSIXTIME2UTC % % Authors: % Joan Pau Beltran <joanpau.beltran@socib.cat> % Copyright (C) 2013-2016 % ICTS SOCIB - Servei d'observacio i prediccio costaner de les Illes Balears % <http://www.socib.es> % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU 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 WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. narginchk(1, 1); s = 86400 * (d - 719529); end
403,204
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: specialist_pool_client.go path of file: ./repos/google-cloud-go/aiplatform/apiv1beta1 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
func (c *specialistPoolGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))} hds = append(c.xGoogHeaders, hds...) ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...) opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.iamPolicyClient.TestIamPermissions(ctx, req, settings.GRPC...) return err }, opts...) if err != nil { return nil, err } return resp, nil }
284,050
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: log10.go path of file: ./repos/goscript/std/math the code of the file until where you have to start completion: // Copyright 2009 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 math // Log10 returns
func Log2(x float64) float64 { frac, exp := Frexp(x) // Make sure exact powers of two give an exact answer. // Don't depend on Log(0.5)*(1/Ln2)+exp being exactly exp-1. if frac == 0.5 { return float64(exp - 1) } return Log(frac)*(1/Ln2) + float64(exp) }
442,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: cat_long_multi_run1445.m path of file: ./repos/ExploreASL/External/SPMmodified/toolbox/cat12/cat_run1445 the code of the file until where you have to start completion: function out = cat_long_multi_run(job) % Call cat_long_main for multiple subjects % % Christian Gaser % $Id: cat_long_multi_run1445.m 1470 2019-05-29 11:49:16Z gaser $ global opts extopts output modulate dartel delete_temp ROImenu surfaces warning off; % use some options from GUI or default file opts = job.opts; extopts = job.extopts; output = job.output; modulate = job.modulate; dartel = job.dartel; ROImenu = job.ROImenu; surfaces = job.output.surface;
function out = cat_long_multi_run(job) % Call cat_long_main for multiple subjects % % Christian Gaser % $Id: cat_long_multi_run1445.m 1470 2019-05-29 11:49:16Z gaser $ global opts extopts output modulate dartel delete_temp ROImenu surfaces warning off; % use some options from GUI or default file opts = job.opts; extopts = job.extopts; output = job.output; modulate = job.modulate; dartel = job.dartel; ROImenu = job.ROImenu; surfaces = job.output.surface; if isfield(job,'delete_temp') delete_temp = job.delete_temp; else delete_temp = 1; end
173,255
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: focus.rs path of file: ./repos/zed/crates/storybook/src/stories the code of the file until where you have to start completion: use gpui::{ actions, div, prelude::*, FocusHandle, KeyBinding, Render, Subscription, View, WindowContext, }; use ui::prelude::*; actions!(focus, [ActionA,
fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> impl IntoElement { let theme = cx.theme(); let color_1 = theme.status().created; let color_2 = theme.status().modified; let color_4 = theme.status().conflict; let color_5 = theme.status().ignored; let color_6 = theme.status().renamed; let color_7 = theme.status().hint; div() .id("parent") .active(|style| style.bg(color_7)) .track_focus(&self.parent_focus) .key_context("parent") .on_action(cx.listener(|_, _action: &ActionA, _cx| { println!("Action A dispatched on parent"); })) .on_action(cx.listener(|_, _action: &ActionB, _cx| { println!("Action B dispatched on parent"); })) .on_key_down(cx.listener(|_, event, _| println!("Key down on parent {:?}", event))) .on_key_up(cx.listener(|_, event, _| println!("Key up on parent {:?}", event))) .size_full() .bg(color_1) .focus(|style| style.bg(color_2)) .child( div() .track_focus(&self.child_1_focus) .key_context("child-1") .on_action(cx.listener(|_, _action: &ActionB, _cx| { println!("Action B dispatched on child 1 during"); })) .w_full() .h_6() .bg(color_4) .focus(|style| style.bg(color_5)) .in_focus(|style| style.bg(color_6)) .on_key_down( cx.listener(|_, event, _| println!("Key down on child 1 {:?}", event)), ) .on_key_up(cx.listener(|_, event, _| println!("Key up on child 1 {:?}", event))) .child("Child 1"), ) .child( div() .track_focus(&self.child_2_focus) .key_context("child-2") .on_action(cx.listener(|_, _action: &ActionC, _cx| { println!("Action C dispatched on child 2"); })) .w_full() .h_6() .bg(color_4) .on_key_down( cx.listener(|_, event, _| println!("Key down on child 2 {:?}", event)), ) .on_key_up(cx.listener(|_, event, _| println!("Key up on child 2 {:?}", event))) .child("Child 2"), ) }
108,379
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: translation_service.rb path of file: ./repos/mastodon/app/lib the code of the file until where you have to start completion: # frozen_string_literal: true class TranslationService c
def self.configured if ENV['DEEPL_API_KEY'].present? TranslationService::DeepL.new(ENV.fetch('DEEPL_PLAN', 'free'), ENV['DEEPL_API_KEY']) elsif ENV['LIBRE_TRANSLATE_ENDPOINT'].present? TranslationService::LibreTranslate.new(ENV['LIBRE_TRANSLATE_ENDPOINT'], ENV['LIBRE_TRANSLATE_API_KEY']) else raise NotConfiguredError end
731,507
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: server_test.go path of file: ./repos/go-zero/rest the code of the file until where you have to start completion: package rest import ( "crypto/tls" "fmt" "io" "net/http"
func TestWithCustomCors(t *testing.T) { const configYaml = ` Name: foo Port: 54321 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) rt := router.NewRouter() svr, err := NewServer(cnf, WithRouter(rt)) assert.Nil(t, err) opt := WithCustomCors(func(header http.Header) { header.Set("foo", "bar") }, func(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) }, "local") opt(svr) }
258,539
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: 20190322152347_force_rebake_on_posts_with_lightboxes.rb path of file: ./repos/discourse/db/migrate the code of the file until where you have to start completion: # frozen_
def up # Picking up changes to lightbox HTML in cooked_post_processor execute <<~SQL UPDATE posts SET baked_version = 0 WHERE cooked LIKE '%lightbox-wrapper%' SQL end
615,775
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: fs_file_create.rs path of file: ./repos/wasmer/tests/wasi-fyi the code of the file until where you have to start completion: use std::fs;
fn main() { assert!(fs::File::create("/fyi/fs_file_create.dir/new_file").is_ok()); assert!(fs::metadata("/fyi/fs_file_create.dir/new_file") .unwrap() .is_file()); assert!(fs::remove_file("/fyi/fs_file_create.dir/new_file").is_ok()); }
442,765
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: parserfilegenerator.rb path of file: ./repos/powerstation/powerstation/lib/compiled-jruby/lib/ruby/stdlib/racc the code of the file until where you have to start completion: # # $Id: f2d2788af2323ada1913f1dad5fea8aae4cc6830 $ # #
def generate_parser string_io = StringIO.new init_line_conversion_system @f = string_io parser_file string_io.rewind string_io.read end
129,471
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: schedulers.rs path of file: ./repos/LibAFL/libafl_libfuzzer/libafl_libfuzzer_runtime/src the code of the file until where you have to start completion: use std::{ collections::{BTreeSet, HashMap}, marker::PhantomData, }; use l
pub fn new() -> Self { Self { mapping: HashMap::default(), all: BTreeSet::default(), phantom: PhantomData, } }
59,384
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: hll-gnuplot-graph.rb path of file: ./repos/codis/extern/deprecated/redis-2.8.21/utils/hyperloglog the code of the file until where you have to start completion: # hll-err.rb - Copyright (C) 2014 Salvatore Sanfilippo # BSD l
def filter_samples(numsets,max,step,filter) r = Redis.new dataset = {} (0...numsets).each{|i| dataset[i] = run_experiment(r,i,max,step) STDERR.puts "Set #{i}" } dataset[0].each_with_index{|ele,index| if filter == :max card=ele[0] err=ele[1].abs (1...numsets).each{|i| err = dataset[i][index][1] if err < dataset[i][index][1] } puts "#{card} #{err}" elsif filter == :avg card=ele[0] err = 0 (0...numsets).each{|i| err += dataset[i][index][1] } err /= numsets puts "#{card} #{err}" elsif filter == :absavg card=ele[0] err = 0 (0...numsets).each{|i| err += dataset[i][index][1].abs } err /= numsets puts "#{card} #{err}" elsif filter == :all (0...numsets).each{|i| card,err = dataset[i][index] puts "#{card} #{err}" } else raise "Unknown filter #{filter}" end
664,790
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: holiday.rs path of file: ./repos/RustQuant/src/time the code of the file until where you have to start completion: // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // RustQuant: A
pub const fn new(name: &'static str, date: Date) -> Self { Self { name, date, description: None, } }
483,803
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/chimesdkvoice/src/operation/put_voice_connector_streaming_configuration 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(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
815,972
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: spawner.rs path of file: ./repos/rustrogueliketutorial/chapter-71-logging/src the code of the file until where you have to start completion: use rltk::{ RGB, RandomNumberGenerator }; use specs::prelude::*; use super::{Pools, Pool, Player, Renderable, Name, Position, Viewshed, Rect, Se
pub fn spawn_town_portal(ecs: &mut World) { // Get current position & depth let map = ecs.fetch::<Map>(); let player_depth = map.depth; let player_pos = ecs.fetch::<rltk::Point>(); let player_x = player_pos.x; let player_y = player_pos.y; std::mem::drop(player_pos); std::mem::drop(map); // Find part of the town for the portal let dm = ecs.fetch::<MasterDungeonMap>(); let town_map = dm.get_map(1).unwrap(); let mut stairs_idx = 0; for (idx, tt) in town_map.tiles.iter().enumerate() { if *tt == TileType::DownStairs { stairs_idx = idx; } } let portal_x = (stairs_idx as i32 % town_map.width)-2; let portal_y = stairs_idx as i32 / town_map.width; std::mem::drop(dm); // Spawn the portal itself ecs.create_entity() .with(OtherLevelPosition { x: portal_x, y: portal_y, depth: 1 }) .with(Renderable { glyph: rltk::to_cp437('♥'), fg: RGB::named(rltk::CYAN), bg: RGB::named(rltk::BLACK), render_order: 0 }) .with(EntryTrigger{}) .with(TeleportTo{ x: player_x, y: player_y, depth: player_depth, player_only: true }) .with(SingleActivation{}) .with(Name{ name : "Town Portal".to_string() }) .build(); }
38,813
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: 20130311192846_remove_unnecessary_user_indexes.rb path of file: ./repos/catarse/db/migrate the code of the file until where you have to start completion: class Rem
def up execute " DROP INDEX IF EXISTS users_email; DROP INDEX IF EXISTS index_users_on_primary_user_id_and_provider; DROP INDEX IF EXISTS index_users_on_uid; ALTER TABLE users DROP CONSTRAINT IF EXISTS users_provider_not_blank; ALTER TABLE users DROP CONSTRAINT IF EXISTS users_uid_not_blank; " end
91,051
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.rs path of file: ./repos/nebulet/src/abi the code of the file until where you have to start completion: use object::{EventDispatcher, HandleRights}; use nabi::{Result, Error}; use wasm::UserData; use nebulet_
// pub fn event_rearm(event_handle: UserHandle<EventDispatcher>, user_data: &UserData) -> Result<u32> { // let event = { // let handle_table = user_data.process.handle_table().read(); // let handle = handle_table // .get(event_handle)?; // handle.check_rights(HandleRights::WRITE)?; // handle // }; // match event.rearm() { // true => Ok(0), // false => Err(Error::BAD_STATE) // } // }
623,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: file.go path of file: ./repos/rosedb/utils the code of the file until where you have to start completion: package utils import ( "io/fs" "path/filepath" ) // DirSize get directory size func DirSize(dirPath string) (int64, error) { var size int64 er
func DirSize(dirPath string) (int64, error) { var size int64 err := filepath.Walk(dirPath, func(path string, info fs.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() { size += info.Size() } return nil }) return size, err }
641,841
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: unwrap_test.go path of file: ./repos/vault/command the code of the file until where you have to start completion: // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: BUSL-1.1 package command import ( "strings" "testing" "github.com/hashicorp/cli" "github.com/hashicorp/vault/api" ) func testUnwrapCommand(tb testing.TB) (*cli.MockUi, *UnwrapCommand) { tb.Helper() ui := cli.NewMockUi() retur
func testUnwrapWrappedToken(tb testing.TB, client *api.Client, data map[string]interface{}) string { tb.Helper() wrapped, err := client.Logical().Write("sys/wrapping/wrap", data) if err != nil { tb.Fatal(err) } if wrapped == nil || wrapped.WrapInfo == nil || wrapped.WrapInfo.Token == "" { tb.Fatalf("missing wrap info: %v", wrapped) } return wrapped.WrapInfo.Token }
314,488
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: delegates.go path of file: ./repos/plumber/vendor/github.com/nsqio/go-nsq the code of the file until where you have to start completion: package nsq import "time" type logger interface {
func (lvl LogLevel) String() string { switch lvl { case LogLevelInfo: return "INF" case LogLevelWarning: return "WRN" case LogLevelError: return "ERR" } return "DBG" }
457,797
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: customize.rs path of file: ./repos/aws-sdk-rust/sdk/codecommit/src/client the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. D
pub(crate) fn new(customizable_send: B) -> Self { Self { customizable_send, config_override: ::std::option::Option::None, interceptors: vec![], runtime_plugins: vec![], _output: ::std::marker::PhantomData, _error: ::std::marker::PhantomData, } }
787,669
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: glass.rs path of file: ./repos/rs_pbrt/src/materials the code of the file until where you have to start completion: //std use std::sync::Arc; // pbrt use crate::core::interaction::SurfaceInteraction; use crate::core::material::{Material, TransportMode}; use crate::core::microfacet::{MicrofacetDistribution, TrowbridgeReitzDistribution}; use crate::core::paramset::TextureParams; use crate::core::pbrt::{Float, Spectrum}; use crate::core::reflection::{ Bsdf, Bxdf, Fresnel, FresnelDielectric, FresnelSpecular, MicrofacetReflection, MicrofacetTransmission, SpecularReflection, SpecularTransmission, }; use crate::core::texture::Texture; // see glass.h /// Perfect or glossy specular reflection and transmission, weighted /// by Fresnel terms for accurate angular-dependent variation. pub struct GlassMaterial { pub kr: Arc<dyn Texture<Spectrum> + Sync + Send>, // default: 1.0 pub kt: Arc<dyn Texture<Spectrum> + Sync + Send>, // default: 1.0 pub u_roughness: Arc<dyn Texture<Float> + Sync + Send>, // default: 0.0
pub fn create(mp: &mut TextureParams) -> Arc<Material> { let kr = mp.get_spectrum_texture("Kr", Spectrum::new(1.0 as Float)); let kt = mp.get_spectrum_texture("Kt", Spectrum::new(1.0 as Float)); let roughu = mp.get_float_texture("uroughness", 0.0 as Float); let roughv = mp.get_float_texture("vroughness", 0.0 as Float); let bump_map = mp.get_float_texture_or_null("bumpmap"); let remap_roughness: bool = mp.find_bool("remaproughness", true); let eta_option: Option<Arc<dyn Texture<Float> + Send + Sync>> = mp.get_float_texture_or_null("eta"); if let Some(ref eta) = eta_option { Arc::new(Material::Glass(Box::new(GlassMaterial::new( kr, kt, roughu, roughv, eta.clone(), bump_map, remap_roughness, )))) } else { let eta: Arc<dyn Texture<Float> + Send + Sync> = mp.get_float_texture("index", 1.5 as Float); Arc::new(Material::Glass(Box::new(GlassMaterial::new( kr, kt, roughu, roughv, eta, bump_map, remap_roughness, )))) } }
2,889
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: eul2jac.m path of file: ./repos/Robotics-Toolbox/rvctools/release10.3.1/robot the code of the file until where you have to start completion: %EUL2JAC Euler angle rate Jacobian % %
function J = eul2jac(phi, theta, psi) if length(phi) == 3 % eul2jac([phi theta psi]) theta = phi(2); psi = phi(3); phi = phi(1); elseif nargin ~= 3 error('RTB:eul2jac:badarg', 'bad arguments'); end
78,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: mongo.go path of file: ./repos/easeprobe/probe/client/mongo the code of the file until where you have to start completion: /* * Copyright (c) 2022, MegaEase * All rights reserved. * * 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 mongo implements a probe client for the MongoDB database. pack
func New(opt conf.Options) (*Mongo, error) { var conn string if len(opt.Password) > 0 { conn = fmt.Sprintf("mongodb://%s:%s@%s/?connectTimeoutMS=%d", opt.Username, opt.Password, opt.Host, opt.Timeout().Milliseconds()) } else { conn = fmt.Sprintf("mongodb://%s/?connectTimeoutMS=%d", opt.Host, opt.Timeout().Milliseconds()) } log.Debugf("[%s / %s / %s] - Connection - %s", opt.ProbeKind, opt.ProbeName, opt.ProbeTag, conn) var maxConn uint64 = 1 client := options.Client().ApplyURI(conn) client.ServerSelectionTimeout = &opt.ProbeTimeout client.ConnectTimeout = &opt.ProbeTimeout client.MaxConnecting = &maxConn client.MaxPoolSize = &maxConn client.MinPoolSize = &maxConn tls, err := opt.TLS.Config() if err != nil { log.Errorf("[%s / %s / %s] - TLS Config Error - %v", opt.ProbeKind, opt.ProbeName, opt.ProbeTag, err) return nil, fmt.Errorf("TLS Config Error - %v", err) } else if tls != nil { client.TLSConfig = tls client.SetAuth(options.Credential{AuthMechanism: "MONGODB-X509"}) } mongo := &Mongo{ Options: opt, ConnStr: conn, ClientOpt: client, Context: context.Background(), } if err := mongo.checkData(); err != nil { return nil, err } return mongo, nil }
648,765
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_job_input.rs path of file: ./repos/aws-sdk-rust/sdk/amplify/src/operation/get_job 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. /// <p>The request structure for the get job request.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct GetJob
pub fn build(self) -> ::std::result::Result<crate::operation::get_job::GetJobInput, ::aws_smithy_types::error::operation::BuildError> { ::std::result::Result::Ok(crate::operation::get_job::GetJobInput { app_id: self.app_id, branch_name: self.branch_name, job_id: self.job_id, }) }
814,001
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: bulk_insert_commit.go path of file: ./repos/vald/hack/benchmark/core/benchmark/strategy the code of the file until where you have to start completion: // // Copyright (C) 2019-2024 vdaas.org vald team <vald@vdaas.org> // // 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. // // Package strategy provides benchmark strategy package strategy import ( "context" "testing" "github.com/vdaas/vald/hack/benchmark/core/benchmark" "github.com/vdaas/vald/hack/benchmark/internal/assets" "github.com/vdaas/vald/hack/benchmark/internal/core/algorithm" ) func NewBulkInsertCommit(poolSize uint32, opts ...StrategyOption) benchmark.Strategy { return newStrategy(append([]StrategyOption{ WithPropName("BulkInsertCommit"), WithProp32( func(ctx context.Context, b *test
func NewBulkInsertCommit(poolSize uint32, opts ...StrategyOption) benchmark.Strategy { return newStrategy(append([]StrategyOption{ WithPropName("BulkInsertCommit"), WithProp32( func(ctx context.Context, b *testing.B, c algorithm.Bit32, dataset assets.Dataset, ids []uint, cnt *uint64) (interface{}, error) { size := func() int { if maxBulkSize < dataset.TrainSize() { return maxBulkSize } else { return dataset.TrainSize() } }() v := make([][]float32, 0, size) for i := 0; i < size; i++ { arr, err := dataset.Train(i) if err != nil { b.Fatal(err) } v = append(v, arr.([]float32)) } b.StopTimer() b.ReportAllocs() b.ResetTimer() b.StartTimer() ids, errs := c.BulkInsertCommit(v, poolSize) return ids, wrapErrors(errs) }, ), WithProp64( func(ctx context.Context, b *testing.B, c algorithm.Bit64, dataset assets.Dataset, ids []uint, cnt *uint64) (interface{}, error) { size := func() int { if maxBulkSize < dataset.TrainSize() { return maxBulkSize } else { return dataset.TrainSize() } }() v := make([][]float64, 0, size) for i := 0; i < size; i++ { arr, err := dataset.Train(i) if err != nil { b.Fatal(err) } v = append(v, float32To64(arr.([]float32))) } b.StopTimer() b.ReportAllocs() b.ResetTimer() b.StartTimer() ids, errs := c.BulkInsertCommit(v, poolSize) return ids, wrapErrors(errs) }, ), }, opts...)...) }
708,202
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: protocol_serde.rs path of file: ./repos/aws-sdk-rust/sdk/robomaker/src the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.co
pub(crate) fn or_empty_doc(data: &[u8]) -> &[u8] { if data.is_empty() { b"{}" } else { data } }
774,028
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: 1774E.go path of file: ./repos/codeforces-go/main/1700-1799 the code of the file until where you have to start completion: package main import ( "bufio" . "fmt" "i
func CF1774E(_r io.Reader, out io.Writer) { in := bufio.NewReader(_r) var n, d, v, w, m, ans int Fscan(in, &n, &d) g := make([][]int, n) for i := 1; i < n; i++ { Fscan(in, &v, &w) v-- w-- g[v] = append(g[v], w) g[w] = append(g[w], v) } tp := make([]int, n) for msk := 1; msk < 3; msk <<= 1 { for Fscan(in, &m); m > 0; m-- { Fscan(in, &v) tp[v-1] |= msk } } st := []int{-1} var f func(int) f = func(v int) { st = append(st, v) for _, w := range g[v] { if w != st[len(st)-2] { f(w) tp[v] |= tp[w] } } if len(st) > d+1 && tp[v] > 0 { tp[st[len(st)-d-1]] = 3 } st = st[:len(st)-1] } f(0) for _, v := range tp[1:] { ans += v>>1 + v&1 } Fprint(out, ans*2) }
134,359
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: cve_2020_0668_service_tracing.rb path of file: ./repos/metasploit-framework/modules/exploits/windows/local the code of the file until where you have to start completion: ## # This module requires Metasploit: https://metasploit.com/downlo
def ensure_clean_destination(path) return unless file?(path) print_status("#{path} already exists on the target. Deleting...") begin file_rm(path) print_status("Deleted #{path}") rescue Rex::Post::Meterpreter::RequestError => e elog(e) print_error("Unable to delete #{path}") end
743,508
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: type_alias_regularity.rb path of file: ./repos/rbs/lib/rbs the code of the file until where you have to start completion: # frozen_string_literal: true module RBS class TypeAliasRegularity class Diagnostic attr_reader :type_name, :nonregular_type def initialize(type_name:, nonregular_type:) @ty
def validate_alias_type(alias_type, names, types) alias_name = env.normalize_type_name?(alias_type.name) or return if names.include?(alias_name) if ex_type = types[alias_name] unless compatible_args?(ex_type.args, alias_type.args) diagnostics[alias_name] ||= Diagnostic.new(type_name: alias_type.name, nonregular_type: alias_type) end
663,356
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: provider.go path of file: ./repos/erda/internal/apps/msp/apm/service/components/transaction-cache-slow/metric_table_filter 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 comp
func init() { name := "component-protocol.components.transaction-cache-slow.metricTableFilter" cpregister.AllExplicitProviderCreatorMap[name] = nil base.InitProviderWithCreator("transaction-cache-slow", "metricTableFilter", func() servicehub.Provider { return &ComponentFilter{} }, ) }
709,596
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_Fpdf.m path of file: ./repos/bspm/thirdparty/spm8 the code of the file until where you have to start completion: function f = spm_Fpdf(x,v,w) % Probability Density Function (PDF) of F (Fisher-Snedecor) distribution % FORMAT f = spm_Fpdf(x,df) % FORMAT f = spm_Fpdf(x,v,w) % % x - F-variate (F has range [0,Inf) ) % df - Degrees of freedom, concatenated along last dimension % Eg. Scalar (or column vector) v & w. Then df=[v,w]; % v - Shape parameter 1 / numerator degrees of freedom (v>0) % w - Shape parameter 2 / denominator degrees of freedom (w>0) % f - PDF of F-distribution with [v,w] degrees of freedom at points x %__________________________________________________________________________ % % spm_Fpdf implements the Probability Density Function of the F-distribution. % % Definition: %-------------------------------------------------------------------------- % The PDF of the F-distribution with degrees of freedom v & w, defined % for positive integer degrees of freedom v>0 & w>0, and for x in % [0,Inf) by: (See Evans et al., Ch16) % % gamma((v+w)/2) * (v/w)^(v/2) x^(v/2-1) % f(x) = -------------------------------------------- % gamma(v/2)*gamma(w/2) * (1+(v/w)x)^((v+w)/2) % % Variate relationships: (Evans et al., Ch16 & 37) %-------------------------------------------------------------------------- % The square of a Student's t variate with w degrees of freedom is % distributed as an F-distribution with [1,w] degrees of freedom. % % For X an F-variate with v,w degrees of freedom, w/(w+v*X^2) has % distributed related to a Beta random variable with shape parameters % w/2 & v/2. % % Algorithm: %-------------------------------------------------------------------------- % Direct computation using the beta function for % gamma(v/2)*gamma(w/2) / gamma((v+w)/2) = beta(v/2,w/2) % % References: %-------------------------------------------------------------------------- % Evans M, Hastings N, Peacock B (1993) % "Statistical Distributions" % 2nd Ed. Wiley, New York % % Abramowitz M, Stegun IA, (1964) % "Handbook of Mathematical Functions"
function f = spm_Fpdf(x,v,w) % Probability Density Function (PDF) of F (Fisher-Snedecor) distribution % FORMAT f = spm_Fpdf(x,df) % FORMAT f = spm_Fpdf(x,v,w) % % x - F-variate (F has range [0,Inf) ) % df - Degrees of freedom, concatenated along last dimension % Eg. Scalar (or column vector) v & w. Then df=[v,w]; % v - Shape parameter 1 / numerator degrees of freedom (v>0) % w - Shape parameter 2 / denominator degrees of freedom (w>0) % f - PDF of F-distribution with [v,w] degrees of freedom at points x %__________________________________________________________________________ % % spm_Fpdf implements the Probability Density Function of the F-distribution. % % Definition: %-------------------------------------------------------------------------- % The PDF of the F-distribution with degrees of freedom v & w, defined % for positive integer degrees of freedom v>0 & w>0, and for x in % [0,Inf) by: (See Evans et al., Ch16) % % gamma((v+w)/2) * (v/w)^(v/2) x^(v/2-1) % f(x) = -------------------------------------------- % gamma(v/2)*gamma(w/2) * (1+(v/w)x)^((v+w)/2) % % Variate relationships: (Evans et al., Ch16 & 37) %-------------------------------------------------------------------------- % The square of a Student's t variate with w degrees of freedom is % distributed as an F-distribution with [1,w] degrees of freedom. % % For X an F-variate with v,w degrees of freedom, w/(w+v*X^2) has % distributed related to a Beta random variable with shape parameters % w/2 & v/2. % % Algorithm: %-------------------------------------------------------------------------- % Direct computation using the beta function for % gamma(v/2)*gamma(w/2) / gamma((v+w)/2) = beta(v/2,w/2) % % References: %-------------------------------------------------------------------------- % Evans M, Hastings N, Peacock B (1993) % "Statistical Distributions" % 2nd Ed. Wiley, New York % % Abramowitz M, Stegun IA, (1964) % "Handbook of Mathematical Functions" % US Government Printing Office % % Press WH, Teukolsky SA, Vetterling AT, Flannery BP (1992) % "Numerical Recipes in C" % Cambridge % %__________________________________________________________________________ % Copyright (C) 1994-2011 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id: spm_Fpdf.m 4182 2011-02-01 12:29:09Z guillaume $ %-Format arguments, note & check sizes %-------------------------------------------------------------------------- if nargin<2, error('Insufficient arguments'), end
520,769
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: Solution_test.go path of file: ./repos/awesome-golang-algorithm/leetcode/301-400/0383.Ransom-Note the code of the file until where you have to start completion: package Solution import ( "reflect" "strconv" "testing" ) func TestSolution(t *testing.T) { // 测试用例 cases := []struct { na
func TestSolution2(t *testing.T) { // 测试用例 cases := []struct { name string input1 string input2 string expect bool }{ {"TestCase", "a", "b", false}, {"TestCase", "aa", "ab", false}, {"TestCase", "aa", "aab", true}, {"TestCase", "aab", "baa", true}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { got := canConstruct2(c.input1, c.input2) if !reflect.DeepEqual(got, c.expect) { t.Fatalf("expected: %v, but got: %v, with input1: %v input2: %v", c.expect, got, c.input1, c.input2) } }) } }
185,860
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: errors.go path of file: ./repos/gitkube/vendor/cloud.google.com/go/errorreporting the code of the file until where you have to start completion: // Copyright 2016 Google LLC // // Licensed under the Apache Li
func (c *Client) onError(err error) { if c.onErrorFn != nil { c.onErrorFn(err) return } log.Println(err) }
505,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: builders.rs path of file: ./repos/aws-sdk-rust/sdk/licensemanager/src/operation/list_received_grants_for_organization 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::
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, } }
798,170
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: question03.go path of file: ./repos/training/example06-go-concurrency the code of the file until where you have to start completion: package main import ( "fmt" "time" ) // try to run: go run -race func main() { msg
func main() { msg := "Let's Go" go func() { // Print: "Let's Go" fmt.Println(msg) }() msg = "Let's GoGoGo" time.Sleep(1 * time.Second) }
33,005
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: cycle_error.go path of file: ./repos/hubble-ui/backend/vendor/go.uber.org/dig the code of the file until where you have to start completion: // Copyright (c) 2019 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentat
func (e errCycleDetected) Error() string { // We get something like, // // [scope "foo"] // func(*bar) *foo provided by "path/to/package".NewFoo (path/to/file.go:42) // depends on func(*baz) *bar provided by "another/package".NewBar (somefile.go:1) // depends on func(*foo) baz provided by "somepackage".NewBar (anotherfile.go:2) // depends on func(*bar) *foo provided by "path/to/package".NewFoo (path/to/file.go:42) // b := new(bytes.Buffer) if name := e.scope.name; len(name) > 0 { fmt.Fprintf(b, "[scope %q]\n", name) } for i, entry := range e.Path { if i > 0 { b.WriteString("\n\tdepends on ") } fmt.Fprintf(b, "%v provided by %v", entry.Key, entry.Func) } return b.String() }
381,433
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: lib.rs path of file: ./repos/rspack/crates/rspack_plugin_library/src the code of the file until where you have to start completion: #![feature(let_chains)] mod amd_library_plugin; mod assign_library_plugin; mod export_property_library_plugin; mod module_library_plugin; mod system_library_plugin; mod umd_library_plugin; mod utils; pub use amd_library_plugin::AmdLibraryPlugin; pub use assign_library_plugin::*; pub use export_property_library_plugin::ExportPropertyLibraryPlugin; pub use module_library_plugin::ModuleLibraryPlugin; use rspack_core::{BoxPlugin, PluginExt}; pub use system_library_plugin::SystemLibraryPlugin; pub use umd_library_plugin::UmdLibraryPlugin; pub fn enable_library_plugin(library_type: String, plugins: &mut Vec<BoxPlugin>) { let ns_object_used = library_type != "module"; match library_type.as_str() { "var" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec![]), declare: true, unnamed: Unnamed::Error, named: None, }) .boxed(), ), "assign-properties" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec![]), declare: false, unnamed: Unnamed::Error, named: Some(Named::Copy), }) .boxed(), ), "as
pub fn enable_library_plugin(library_type: String, plugins: &mut Vec<BoxPlugin>) { let ns_object_used = library_type != "module"; match library_type.as_str() { "var" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec![]), declare: true, unnamed: Unnamed::Error, named: None, }) .boxed(), ), "assign-properties" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec![]), declare: false, unnamed: Unnamed::Error, named: Some(Named::Copy), }) .boxed(), ), "assign" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec![]), declare: false, unnamed: Unnamed::Error, named: None, }) .boxed(), ), "this" | "window" | "self" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type: library_type.clone(), prefix: Prefix::Array(vec![library_type]), declare: false, unnamed: Unnamed::Copy, named: None, }) .boxed(), ), "global" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Global, declare: false, unnamed: Unnamed::Copy, named: None, }) .boxed(), ), "commonjs" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec!["exports".to_string()]), declare: false, unnamed: Unnamed::Copy, named: None, }) .boxed(), ), "commonjs-static" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec!["exports".to_string()]), declare: false, unnamed: Unnamed::Static, named: None, }) .boxed(), ), "commonjs2" | "commonjs-module" => plugins.push( AssignLibraryPlugin::new(AssignLibraryPluginOptions { library_type, prefix: Prefix::Array(vec!["module".to_string(), "exports".to_string()]), declare: false, unnamed: Unnamed::Assign, named: None, }) .boxed(), ), "umd" | "umd2" => { plugins.push(ExportPropertyLibraryPlugin::new(library_type.clone(), ns_object_used).boxed()); plugins.push(UmdLibraryPlugin::new("umd2" == library_type, library_type).boxed()); } "amd" | "amd-require" => { plugins.push(ExportPropertyLibraryPlugin::new(library_type.clone(), ns_object_used).boxed()); plugins.push(AmdLibraryPlugin::new("amd-require" == library_type, library_type).boxed()); } "module" => { plugins.push(ExportPropertyLibraryPlugin::new(library_type.clone(), ns_object_used).boxed()); plugins.push(ModuleLibraryPlugin::default().boxed()); } "system" => { plugins.push( ExportPropertyLibraryPlugin::new(library_type.clone(), library_type != "module").boxed(), ); plugins.push(SystemLibraryPlugin::default().boxed()); } _ => {} } }
673,755
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: fake_replicaset.go path of file: ./repos/faas-netes/vendor/k8s.io/client-go/kubernetes/typed/apps/v1beta2/fake the code of the file until where you have to start completion: /* Copyright 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 m
func (c *FakeReplicaSets) Create(ctx context.Context, replicaSet *v1beta2.ReplicaSet, opts v1.CreateOptions) (result *v1beta2.ReplicaSet, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(replicasetsResource, c.ns, replicaSet), &v1beta2.ReplicaSet{}) if obj == nil { return nil, err } return obj.(*v1beta2.ReplicaSet), err }
425,746
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: _instance_type.rs path of file: ./repos/aws-sdk-rust/sdk/ec2/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 m
pub fn try_parse(value: &str) -> ::std::result::Result<Self, crate::error::UnknownVariantError> { match Self::from(value) { #[allow(deprecated)] Self::Unknown(_) => ::std::result::Result::Err(crate::error::UnknownVariantError::new(value)), known => Ok(known), } }
804,817
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: Divide.m path of file: ./repos/PlatEMO/PlatEMO/Algorithms/Single-objective optimization/MFEA-II the code of the file until where you have to start completion: function SubPopulation = Divide(Population,SubCount) %------------------------------- Copyright -------------------------------- % Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for % research purposes. All publications which use this platform or any code
function SubPopulation = Divide(Population,SubCount) %------------------------------- Copyright -------------------------------- % Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for % research purposes. All publications which use this platform or any code % in the platform should acknowledge the use of "PlatEMO" and reference "Ye % Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform % for evolutionary multi-objective optimization [educational forum], IEEE % Computational Intelligence Magazine, 2017, 12(4): 73-87". %-------------------------------------------------------------------------- PopDec = Population.decs; skills = PopDec(:,end
323,507
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: rpc_client.go path of file: ./repos/goldfish/vendor/github.com/hashicorp/go-plugin the code of the file until where you have to start completion: package plugin import ( "crypto/tls" "fmt" "io" "net" "net/rpc" "github.com/hashicorp/yamux" ) // RPCClient connects to an RPCServer over net/rpc to dispense plugin types. type RPCClient struct { broker *MuxBroker control *rpc.Client plugins map[string]Plugin // These are the streams used for the various stdout/err overrides stdout, stderr net.Conn } // newRPCClient creates a new RPCClient. The Client argument is expected // to be successfully started already with a lock held. func newRPCClie
func (c *RPCClient) Close() error { // Call the control channel and ask it to gracefully exit. If this // errors, then we save it so that we always return an error but we // want to try to close the other channels anyways. var empty struct{} returnErr := c.control.Call("Control.Quit", true, &empty) // Close the other streams we have if err := c.control.Close(); err != nil { return err } if err := c.stdout.Close(); err != nil { return err } if err := c.stderr.Close(); err != nil { return err } if err := c.broker.Close(); err != nil { return err } // Return back the error we got from Control.Quit. This is very important // since we MUST return non-nil error if this fails so that Client.Kill // will properly try a process.Kill. return returnErr }
391,251
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: ShowUsers_test.go path of file: ./repos/aws-doc-sdk-examples/go/workdocs/ShowUsers 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: MIT-0 package main import ( "errors" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/workdocs" "github.com/aws/aws-sdk-go/service/workdocs/workdocsiface" ) // D
func (m *mockWorkDocsClient) DescribeUsers(input *workdocs.DescribeUsersInput) (*workdocs.DescribeUsersOutput, error) { // Check that required inputs exist if input.OrganizationId == nil || *input.OrganizationId == "" { return nil, errors.New("DescribeUsersInput.OrganizationId is nil or an empty string") } /* Username GivenName Surname EmailAddress RootFolderId */ resp := workdocs.DescribeUsersOutput{ Users: []*workdocs.User{ { Username: aws.String("test-user@example.com"), GivenName: aws.String("test-user-first-name"), Surname: aws.String("test-user-last-name"), EmailAddress: aws.String("test-user@example.com"), RootFolderId: aws.String("test-root-folder-ID"), }, }, } return &resp, nil }
535,083
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: teammembership_update.go path of file: ./repos/portainer/api/http/handler/teammemberships the code of the file until where you have to start completion: package teammemberships import ( "errors" "net/http" portainer "github.co
func (payload *teamMembershipUpdatePayload) Validate(r *http.Request) error { if payload.UserID == 0 { return errors.New("Invalid UserID") } if payload.TeamID == 0 { return errors.New("Invalid TeamID") } if payload.Role != 1 && payload.Role != 2 { return errors.New("Invalid role value. Value must be one of: 1 (leader) or 2 (member)") } return nil }
533,281
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: sqlite3_test.go path of file: ./repos/goqu/dialect/sqlite3 the code of the file until where you have to start completion: package sqlite3_test import ( "database/sql" "fmt" "testing" "time" _ "github.com/mattn/go-sqlite3" "github.com/doug-martin/goqu/v9" "github.com/doug-martin/goqu/v9/dialect/mysql" "github.com/doug-martin/goqu/v9/dialect/sqlite3" "github.com/stretchr/testify/suite" ) const ( dropTable = "DROP TABLE IF EXISTS `entry`;" createTable = "CREATE TABLE `entry` (" + "`id` INTEGER PRIMARY KEY," + "`int` INT NOT NULL
func (st *sqlite3Suite) TestQuery_ValueExpressions() { type wrappedEntry struct { entry BoolValue bool `db:"bool_value"` } expectedDate, err := time.Parse("2006-01-02T15:04:05.000000000-00:00", "2015-02-22T19:19:55.000000000-00:00") st.NoError(err) ds := st.db.From("entry").Select(goqu.Star(), goqu.V(true).As("bool_value")).Where(goqu.Ex{"int": 1}) var we wrappedEntry found, err := ds.ScanStruct(&we) st.NoError(err) st.True(found) st.Equal(we, wrappedEntry{ entry{2, 1, 0.100000, "0.100000", expectedDate, false, []byte("0.100000")}, true, }) }
595,924
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: config.go path of file: ./repos/corteza/server/pkg/provision the code of the file until where you have to start completion: package provision import ( "context" "fmt" "path/filepath" "strings" "github.com/cortezaproject/corteza/server/pkg/dal" "github.com/cortezaproject/corteza/server/pkg/envoyx" se "github.com/cortezaproject/corteza/server/system/envoy" "github.com/cortezaproject/corteza/server/system/types" "github.com/cortezaproject/corteza/server/pkg/rbac" "github.com/cortezaproject/corteza/server/store" "go.uber.org/zap" ) // imports configuration files from path(s) // // paths can be colon delimited list of absolute or relative paths and/or with glob pattern func importConfig(ctx context.Context, log *zap.Logger, s store.Storer, paths string) error { canImportFull, err := canImportConfig(ctx, s) if !canImportFull { log.Info("already provisioned, skipping full config import") } else if err != nil { return fmt.Errorf("failed to check if config import can be done: %w", err) } var ( nn envoyx.NodeSet auxN envoyx.NodeSet evy = envoyx.Global() sources = make([]string, 0, 16) ) // verify all paths before doing the actual import for _, path := range strings.Split(paths, ":") { if aux, err := filepath.Glob(path); err != nil { return err } else { sources = append(sources, aux...) } } if canImportFull { log.Info("importing all configs", zap.String("paths", paths)) for _, path := range sources { log.Info("provisioning from path", zap.String("path", path)) auxN, _, err = evy.Decode(ctx, envoyx.DecodeParams{ Type: envoyx.DecodeTypeURI, Params: map[string]any{ "uri": "file://" + path, }, }) if err != nil { return err } nn = append(nn, auxN...) } } else { nn, err = collectUnimportedConfigs(ctx, log, s, sources, evy) if err != nil { return err } } // Get potentially missing refs // // @todo replace this with getting missing refs and just fetching those. //
func importConfig(ctx context.Context, log *zap.Logger, s store.Storer, paths string) error { canImportFull, err := canImportConfig(ctx, s) if !canImportFull { log.Info("already provisioned, skipping full config import") } else if err != nil { return fmt.Errorf("failed to check if config import can be done: %w", err) } var ( nn envoyx.NodeSet auxN envoyx.NodeSet evy = envoyx.Global() sources = make([]string, 0, 16) ) // verify all paths before doing the actual import for _, path := range strings.Split(paths, ":") { if aux, err := filepath.Glob(path); err != nil { return err } else { sources = append(sources, aux...) } } if canImportFull { log.Info("importing all configs", zap.String("paths", paths)) for _, path := range sources { log.Info("provisioning from path", zap.String("path", path)) auxN, _, err = evy.Decode(ctx, envoyx.DecodeParams{ Type: envoyx.DecodeTypeURI, Params: map[string]any{ "uri": "file://" + path, }, }) if err != nil { return err } nn = append(nn, auxN...) } } else { nn, err = collectUnimportedConfigs(ctx, log, s, sources, evy) if err != nil { return err } } // Get potentially missing refs // // @todo replace this with getting missing refs and just fetching those. // For now this is the only scenario so we can get away with this just fine. rr, _, err := store.SearchRoles(ctx, s, types.RoleFilter{}) if err != nil { return err } for _, r := range rr { aux, err := se.RoleToEnvoyNode(r) if err != nil { return err } aux.Placeholder = true nn = append(nn, aux) } // ---------------------------------------------------------------------- return store.Tx(ctx, s, func(ctx context.Context, s store.Storer) (err error) { ep := envoyx.EncodeParams{ Type: envoyx.EncodeTypeStore, Params: map[string]any{ "storer": s, "dal": dal.Service(), }, Envoy: envoyx.EnvoyConfig{ MergeAlg: envoyx.OnConflictSkip, }, } gg, err := evy.Bake(ctx, ep, nil, nn..., ) if err != nil { return err } err = evy.Encode(ctx, ep, gg) if err != nil { return err } return nil }) }
543,985
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: computed_column_rewrites.go path of file: ./repos/cockroach/pkg/sql/catalog/schemaexpr the code of the file until where you have to start completion: // Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As
func MaybeRewriteComputedColumn(expr tree.Expr, sessionData *sessiondata.SessionData) tree.Expr { rewritesStr := sessionData.ExperimentalComputedColumnRewrites if rewritesStr == "" { return expr } rewrites, err := ParseComputedColumnRewrites(rewritesStr) if err != nil { // This shouldn't happen - we should have validated the value. return expr } if newExpr, ok := rewrites[tree.Serialize(expr)]; ok { return newExpr } return expr }
703,797
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: password_checker.rs path of file: ./repos/risc0/examples/cycle-counter/src/examples the code of the file until where you have to start completion: // Copyright 2024 RISC Zero, 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
fn run() -> Metrics { let mut rng = StdRng::from_entropy(); let mut salt = [0u8; 32]; rng.fill_bytes(&mut salt); let request = PasswordRequest { password: "S00perSecr1t!!!".into(), salt, }; let env = ExecutorEnv::builder() .write(&request) .unwrap() .build() .unwrap(); exec(Self::NAME, Self::METHOD_ELF, env) }
382,965
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: dsccompilationjob_server.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/automation/armautomation/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 behavior and will be lost if the code is regenerated. package fake import ( "context" "errors" "fmt" azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/automation/armautomation" "net/http" "net/url" "regexp" ) // DscCompilationJobServer is a fake server for instances of the armautomation.DscCompilationJobClient type. type DscCompilationJobServer struct { // BeginCreate is the fake for method DscCompilationJobClient.BeginCreate // HTTP status codes to indicate success: http.StatusCreated BeginCreate func(ctx context.Context, resourceGroupName string, automationAccountName string, compilationJobName string, parameters
func (d *DscCompilationJobServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { if d.srv.Get == nil { return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} } const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Automation/automationAccounts/(?P<automationAccountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/compilationjobs/(?P<compilationJobName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` regex := regexp.MustCompile(regexStr) matches := regex.FindStringSubmatch(req.URL.EscapedPath()) if matches == nil || len(matches) < 4 { 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 } automationAccountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("automationAccountName")]) if err != nil { return nil, err } compilationJobNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("compilationJobName")]) if err != nil { return nil, err } respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, automationAccountNameParam, compilationJobNameParam, nil) if respErr := server.GetError(errRespr, req); respErr != nil { return nil, respErr } respContent := server.GetResponseContent(respr) if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} } resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DscCompilationJob, req) if err != nil { return nil, err } return resp, nil }
271,579
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: generated_test.go path of file: ./repos/cockroach/pkg/sql/opt/exec/execbuilder/tests/local-vec-off the code of the file until where you have to start completion: // Copyright 2022 The Cockroach Authors. // // Use of th
func runExecBuildLogicTest(t *testing.T, file string) { defer sql.TestingOverrideExplainEnvVersion("CockroachDB execbuilder test version")() skip.UnderDeadlock(t, "times out and/or hangs") serverArgs := logictest.TestServerArgs{ DisableWorkmemRandomization: true, ForceProductionValues: true, // Disable the direct scans in order to keep the output of EXPLAIN (VEC) // deterministic. DisableDirectColumnarScans: true, } logictest.RunLogicTest(t, serverArgs, configIdx, filepath.Join(execBuildLogicTestDir, file)) }
704,185
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: pk_test.go path of file: ./repos/xorm/schemas the code of the file until where you have to start completion: // Copyright 2019 The Xorm 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 schemas import ( "reflect" "testing" ) func TestPK(t *testing.T) { p := NewPK(1, 3, "string") str, err := p.ToString() if err != nil
func TestPK(t *testing.T) { p := NewPK(1, 3, "string") str, err := p.ToString() if err != nil { t.Error(err) } t.Log(str) s := &PK{} err = s.FromString(str) if err != nil { t.Error(err) } t.Log(s) if len(*p) != len(*s) { t.Fatal("p", *p, "should be equal", *s) } for i, ori := range *p { if ori != (*s)[i] { t.Fatal("ori", ori, reflect.ValueOf(ori), "should be equal", (*s)[i], reflect.ValueOf((*s)[i])) } } }
194,003
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.rs path of file: ./repos/wgpu/wgpu-core/src/command the code of the file until where you have to start completion: use hal::CommandEncoder as _; #[cfg(feature = "trace")] use crate::device::trace::Command as TraceCommand; use cr
fn fmt_pretty(&self, fmt: &mut crate::error::ErrorFormatter) { fmt.error(self); match *self { Self::InvalidBuffer(id) => fmt.buffer_label(&id), Self::InvalidQuerySet(id) => fmt.query_set_label(&id), _ => {} } }
294,137
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: keywords.rs path of file: ./repos/crates.io/src/tests/krate/publish the code of the file until where you have to start completion: use crate::builders::PublishBuilder; use crate::util::{RequestHelper, TestApp}; use
fn too_many_keywords() { let (app, _, _, token) = TestApp::full().with_token(); let response = token.publish_crate( PublishBuilder::new("foo", "1.0.0") .keyword("one") .keyword("two") .keyword("three") .keyword("four") .keyword("five") .keyword("six"), ); assert_eq!(response.status(), StatusCode::BAD_REQUEST); assert_json_snapshot!(response.json()); assert_that!(app.stored_files(), empty()); }
118,801
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: delete_feature.rs path of file: ./repos/aws-sdk-rust/sdk/evidently/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 `DeleteFeature`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct DeleteFeature; impl DeleteFeature { /// Creates a new `DeleteFeature` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_runtime_api::cli
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::AccessDeniedException(_inner) => _inner.fmt(f), Self::ConflictException(_inner) => _inner.fmt(f), Self::ResourceNotFoundException(_inner) => _inner.fmt(f), Self::ThrottlingException(_inner) => _inner.fmt(f), Self::ValidationException(_inner) => _inner.fmt(f), Self::Unhandled(_inner) => { if let ::std::option::Option::Some(code) = ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) { write!(f, "unhandled error ({code})") } else { f.write_str("unhandled error") } } } }
813,576
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: bytesource.go path of file: ./repos/hubble-ui/backend/vendor/github.com/google/gofuzz/bytesource the code of the file until where you have to start completion: /* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use thi
func (s *ByteSource) Uint64() uint64 { // Return from input if it was not exhausted. if s.Len() > 0 { return s.consumeUint64() } // Input was exhausted, return random number from fallback (in this case fallback should not be // nil). Try first having a Uint64 output (Should work in current rand implementation), // otherwise return a conversion of Int63. if s64, ok := s.fallback.(rand.Source64); ok { return s64.Uint64() } return uint64(s.fallback.Int63()) }
377,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: aes.rs path of file: ./repos/Rust/src/ciphers the code of the file until where you have to start completion: const AES_WORD_SIZE: usize = 4; const AES_BLOCK_SIZE: usize = 16; const AES
fn rot_word(word: Word) -> Word { let mut bytes = word_to_bytes(word); let init = bytes[0]; bytes[0] = bytes[1]; bytes[1] = bytes[2]; bytes[2] = bytes[3]; bytes[3] = init; bytes_to_word(&bytes) }
368,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: syscall_unix.go path of file: ./repos/hoverfly/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by
func SignalName(s syscall.Signal) string { i := sort.Search(len(signalList), func(i int) bool { return signalList[i].num >= s }) if i < len(signalList) && signalList[i].num == s { return signalList[i].name } return "" }
692,648
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: speaker.go path of file: ./repos/beep/speaker the code of the file until where you have to start completion: // Package speaker implements playback of beep.Streamer values through physical speakers. package speaker import ( "sync" "github.com/faiface/beep" "github.com/hajimehoshi/ot
func update() { mu.Lock() mixer.Stream(samples) mu.Unlock() for i := range samples { for c := range samples[i] { val := samples[i][c] if val < -1 { val = -1 } if val > +1 { val = +1 } valInt16 := int16(val * (1<<15 - 1)) low := byte(valInt16) high := byte(valInt16 >> 8) buf[i*4+c*2+0] = low buf[i*4+c*2+1] = high } } player.Write(buf) }
662,848
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_sparc64.go path of file: ./repos/govendor/vendor/golang.org/x/sys/unix the code of the file until where you have to start completion: // Copyright 2009 The Go Authors. All rights reserved. // Use of th
func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return }
376,550
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: 04-outlet.rs path of file: ./repos/ockam/examples/rust/tcp_inlet_and_outlet/examples the code of the file until where you have to start completion: use ockam::identity::SecureChannelListenerOptions; use ockam::remote::RemoteRelayOptions; use ockam::{node, Context, Result, TcpConnectionOptions, TcpOutletOptions, TcpTransportExtension}; #[ockam::node] async fn main(ctx: Context) -> Result<()> { // Initialize the TCP Transport. let node = node(ctx).await?; let tcp = node.create_tcp_transport().await?; let e = node.create_identity().await?; let tcp_options = TcpConnectionOptions::new(); let tcp_flow_control_id = tcp_options.flow_control_id(); let secure_channel_listener_options = SecureChannelListenerOptions::new().as_consumer(&tcp_flow_control_id); let secure_channel_flow_control_id = secure_channel_listener_options.spawner_flow_control_id(); node.create_secure_channel_listener(&e, "secure_channel_listener", secure_channel_listener_options) .await?; // Expect first command line argument to be the TCP address of a target TCP server. // For example: 127.0.0.1:4002 // // Create a TCP Transport Outlet - at Ockam Worker address "outlet" - // that will connect, as a TCP client, to the target TCP server. // // This Outlet will: // 1. Unwrap the payload of any Ockam Routing Message that it receives from an Inlet // and send it as raw TCP data to the target TCP server. First such message from // an Inlet is used to remember the route back the Inlet. // // 2. Wrap any raw TCP data it receives, from the target TCP server, // as payload of a new Ockam Routing Message. This Ockam Routing Message will have // its onward_route be set to the route to an I
async fn main(ctx: Context) -> Result<()> { // Initialize the TCP Transport. let node = node(ctx).await?; let tcp = node.create_tcp_transport().await?; let e = node.create_identity().await?; let tcp_options = TcpConnectionOptions::new(); let tcp_flow_control_id = tcp_options.flow_control_id(); let secure_channel_listener_options = SecureChannelListenerOptions::new().as_consumer(&tcp_flow_control_id); let secure_channel_flow_control_id = secure_channel_listener_options.spawner_flow_control_id(); node.create_secure_channel_listener(&e, "secure_channel_listener", secure_channel_listener_options) .await?; // Expect first command line argument to be the TCP address of a target TCP server. // For example: 127.0.0.1:4002 // // Create a TCP Transport Outlet - at Ockam Worker address "outlet" - // that will connect, as a TCP client, to the target TCP server. // // This Outlet will: // 1. Unwrap the payload of any Ockam Routing Message that it receives from an Inlet // and send it as raw TCP data to the target TCP server. First such message from // an Inlet is used to remember the route back the Inlet. // // 2. Wrap any raw TCP data it receives, from the target TCP server, // as payload of a new Ockam Routing Message. This Ockam Routing Message will have // its onward_route be set to the route to an Inlet that is knows about because of // a previous message from the Inlet. let outlet_target = std::env::args().nth(1).expect("no outlet target given"); tcp.create_outlet( "outlet", outlet_target, TcpOutletOptions::new().as_consumer(&secure_channel_flow_control_id), ) .await?; // To allow Inlet Node and others to initiate an end-to-end secure channel with this program // we connect with 1.node.ockam.network:4000 as a TCP client and ask the forwarding // service on that node to create a relay for us. // // All messages that arrive at that forwarding address will be sent to this program // using the TCP connection we created as a client. let node_in_hub = tcp.connect("1.node.ockam.network:4000", tcp_options).await?; let relay = node.create_relay(node_in_hub, RemoteRelayOptions::new()).await?; println!("\n[✓] RemoteRelay was created on the node at: 1.node.ockam.network:4000"); println!("Forwarding address in Hub is:"); println!("{}", relay.remote_address()); // We won't call ctx.stop() here, // so this program will keep running until you interrupt it with Ctrl-C. Ok(()) }
474,153
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: router.rs path of file: ./repos/snarkOS/node/src/prover the code of the file until where you have to start completion: // Copyright (C) 2019-2023 Aleo Systems Inc. // This file is part of the snarkOS library. // 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 Li
fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool { // Spawn an asynchronous task for the `Ping` request. let self_clone = self.clone(); tokio::spawn(async move { // Sleep for the preset time before sending a `Ping` request. tokio::time::sleep(Duration::from_secs(Self::PING_SLEEP_IN_SECS)).await; // Check that the peer is still connected. if self_clone.router().is_connected(&peer_ip) { // Send a `Ping` message to the peer. self_clone.send_ping(peer_ip, None); } }); true }
148,630
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: telemetry_events.rs path of file: ./repos/zed/crates/telemetry_events/src the code of the file until where you have to start completion: use std::fmt::Display; use serde::{Deserialize, Serialize}; use util::SemanticVersion; #[derive(Serialize, Deserialize,
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Self::Panel => "panel", Self::Inline => "inline", } ) }
108,441
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: authorization.rs path of file: ./repos/Plume/src/api the code of the file until where you have to start completion: use plume_models::{self, api_tokens::ApiToken}; use rocket::{ http::Status, request::{self, FromRequest, Request}, Outcome, }; use std::marker::PhantomData; // Actions pub trait Action { fn to_str() -> &'static str; } pub struct Read; impl Action for Read { fn to_str
fn from_request(request: &'a Request<'r>) -> request::Outcome<Authorization<A, S>, ()> { request .guard::<ApiToken>() .map_failure(|_| (Status::Unauthorized, ())) .and_then(|token| { if token.can(A::to_str(), S::to_str()) { Outcome::Success(Authorization(token, PhantomData)) } else { Outcome::Failure((Status::Unauthorized, ())) } }) }
361,538
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: context.go path of file: ./repos/gitea/modules/cache the code of the file until where you have to start completion: // Copyright 2022 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT package cache import ( "context" "sync" "time" "code.gitea.io/gitea/modules
func WithCacheContext(ctx context.Context) context.Context { if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok { if !c.isDiscard() { // reuse parent context return ctx } } return context.WithValue(ctx, cacheContextKey, &cacheContext{ data: make(map[any]map[any]any), created: timeNow(), }) }
650,653
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: verbatim.rb path of file: ./repos/artichoke/artichoke-backend/vendor/ruby/lib/rdoc/markup the code of the file until where you have to start completion: # frozen_string_literal: true ## # A section of verbatim text class RDoc::Markup::Verbatim < RDoc::Markup::Raw ## # Format of this ve
def normalize parts = [] newlines = 0 @parts.each do |part| case part when /^\s*\n/ then newlines += 1 parts << part if newlines == 1 else newlines = 0 parts << part end end
311,194
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: layoutRoot.m path of file: ./repos/CellExplorer/toolboxes/GUI Layout Toolbox 2.3.5 the code of the file until where you have to start completion: function folder = layoutRoot()
function folder = layoutRoot() %layoutRoot Folder containing the GUI Layout Toolbox % % folder = layoutRoot() returns the full path to the folder containing % the GUI Layout Toolbox. % % Examples: % >> folder = layoutRoot() % folder = 'C:\tools\layouts2\layout' % % See also: layoutVersion % Copyright 2009-2020 The MathWorks, Inc. folder = fileparts( mfilename( 'fullpath' ) ); end
148,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: 04_01_enum.rs path of file: ./repos/clap/examples/tutorial_derive the code of the file until where you have to start completion: use clap::{Parser, ValueEnum}; #[derive(Parser)] #[command(version, about, long_about = None)] struct Cli { ///
fn main() { let cli = Cli::parse(); match cli.mode { Mode::Fast => { println!("Hare"); } Mode::Slow => { println!("Tortoise"); } } }
559,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: 20180719103905_alter_indexes_on_email_logs.rb path of file: ./repos/discourse/db/migrate the code of the file until where you have to start completion: # frozen_string_literal: true class AlterIndexesOnEmailLogs < ActiveRecord::Migration[5.2] def change remove_index :email_logs, name: "index_email_logs_on_user_id_and_create
def change remove_index :email_logs, name: "index_email_logs_on_user_id_and_created_at", column: %i[user_id created_at] add_index :email_logs, :user_id remove_index :email_logs, %i[skipped created_at] add_index :email_logs, %i[skipped bounced created_at] end
615,339
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/lightsail/src/operation/get_load_balancers 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::
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, } }
814,562
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: disability_compensation_pdf_mapper.rb path of file: ./repos/vets-api/modules/claims_api/lib/claims_api/v2 the code of the file until where you have to start completion: # frozen_string_literal: true require 'claims_api/v2/disability_compensation_shared_service_module' module ClaimsApi
def initialize(auto_claim, pdf_data, auth_headers, middle_initial, created_at) @auto_claim = auto_claim @pdf_data = pdf_data @auth_headers = auth_headers&.deep_symbolize_keys @middle_initial = middle_initial @created_at = created_at.strftime('%Y-%m-%d').to_s end
576,278
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: rendering_context.rs path of file: ./repos/emacs-ng/rust_src/crates/emacs/src/gfx/context_impl/surfman the code of the file until where you have to start completion: /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ // Copied from https://github.com/servo/servo/commit/bc211f8ff387ea59bc8af7bb7394c7be7ca69597 #![deny(unsafe_code)] use std::cell::RefCell; use std::ffi::c_void; use std::rc::Rc; use euclid::default::Size2D; use surfman::chains::{PreserveBuffer, SwapChain}; use surfman::{ Adapter, Connection, Context, ContextAttri
pub fn resize(&self, size: Size2D<i32>) -> Result<(), Error> { let ref mut device = self.0.device.borrow_mut(); let ref mut context = self.0.context.borrow_mut(); if let Some(swap_chain) = self.0.swap_chain.as_ref() { return swap_chain.resize(device, context, size); } let mut surface = device.unbind_surface_from_context(context)?.unwrap(); device.resize_surface(context, &mut surface, size)?; device .bind_surface_to_context(context, surface) .map_err(|(err, mut surface)| { let _ = device.destroy_surface(context, &mut surface); err }) }
377,650
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: genPreLitTableLatex.m path of file: ./repos/MATL/spec/latex_tools the code of the file until where you have to start completion: function genPreLitTableLatex p = path; if exist('C:\Users\Luis\Google Drive\MATL', 'dir') baseFolder = 'C:\Users\Luis\Google Drive\MATL'; elseif exist('C:\Users\lmendo\Google Drive\MATL', 'dir') baseFolder = 'C:\Users\lmendo\Google Drive\MATL'; else
function genPreLitTableLatex p = path; if exist('C:\Users\Luis\Google Drive\MATL', 'dir') baseFolder = 'C:\Users\Luis\Google Drive\MATL'; elseif exist('C:\Users\lmendo\Google Drive\MATL', 'dir') baseFolder = 'C:\Users\lmendo\Google Drive\MATL'; else error('Base folder not found') end addpath([baseFolder '\compiler']) preLitTableFileName = [ baseFolder '\spec\preLitTable\preLitTable.tex' ]; preLitMatFileName = [ baseFolder '\compiler\preLit.mat' ]; preLitTxtFileName = [ baseFolder '\compiler\preLit.txt' ]; % Update preLit.mat, if needed; or load file pLTxt = dir(preLitTxtFileName); if ~isempty(pLTxt) pLTxt = datenum(pLTxt.date); else pLTxt = -inf; end
470,396