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: types_linux.go path of file: ./repos/gotosocial/vendor/google.golang.org/grpc/internal/channelz the code of the file until where you have to start completion: /* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2
func (s *SocketOptionData) Getsockopt(fd uintptr) { if v, err := unix.GetsockoptLinger(int(fd), syscall.SOL_SOCKET, syscall.SO_LINGER); err == nil { s.Linger = v } if v, err := unix.GetsockoptTimeval(int(fd), syscall.SOL_SOCKET, syscall.SO_RCVTIMEO); err == nil { s.RecvTimeout = v } if v, err := unix.GetsockoptTimeval(int(fd), syscall.SOL_SOCKET, syscall.SO_SNDTIMEO); err == nil { s.SendTimeout = v } if v, err := unix.GetsockoptTCPInfo(int(fd), syscall.SOL_TCP, syscall.TCP_INFO); err == nil { s.TCPInfo = v } }
26,179
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: open_options.rs path of file: ./repos/rust-clippy/clippy_lints/src/methods the code of the file until where you have to start completion: use rustc_data_structures::fx::FxHashMap; use clippy_utils::diagnostics::{span_lint, span_lint_and_then}; use clippy_utils::ty::{is_type_diagnostic_item, match_type}; use clippy_utils::{match_any_def_paths, paths}; use rustc_ast::ast::LitKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; use rustc_
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { OpenOption::Append => write!(f, "append"), OpenOption::Create => write!(f, "create"), OpenOption::CreateNew => write!(f, "create_new"), OpenOption::Read => write!(f, "read"), OpenOption::Truncate => write!(f, "truncate"), OpenOption::Write => write!(f, "write"), } }
201,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: _asset_relationship_summary.rs path of file: ./repos/aws-sdk-rust/sdk/iotsitewise/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. /// <p>Contains information about assets that are related to one another.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq, ::std::fmt::Debug)] pub struct As
pub fn build(self) -> ::std::result::Result<crate::types::AssetRelationshipSummary, ::aws_smithy_types::error::operation::BuildError> { ::std::result::Result::Ok(crate::types::AssetRelationshipSummary { hierarchy_info: self.hierarchy_info, relationship_type: self.relationship_type.ok_or_else(|| { ::aws_smithy_types::error::operation::BuildError::missing_field( "relationship_type", "relationship_type was not specified but it is required when building AssetRelationshipSummary", ) })?, }) }
773,787
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: dataplatform_node_pool.go path of file: ./repos/terraformer/providers/ionoscloud the code of the file until where you have to start completion: package ionoscloud import ( "context" "log" "github.com/GoogleCloudPlatform/terraformer/providers/ionoscloud/helpers" "github.com/GoogleCloudPlatform/terraformer/terraformutils" ) type DataPlatformNodePoolGenerator struct { Service } func (g *DataPlatformNodePoolGenerator) InitResources() error { client := g.generateClient() dataPlatformClient := client.DataPlatformAPIClient resourceType := "ionoscloud_dataplatform_node_pool" dpClusters, _, err := dataPlatformClient.DataPlatformClusterApi.ClustersGet(context.TODO()).Execute() if err != nil { return err } if dpClusters.Items == nil { log.Printf("[WARNING] expected a response containing data platform clusters but received 'nil' instead.") return nil } for _, dpCluster := range *dpClusters.Items { dpNodePools, _, err := dataPlatformClient.DataPlatformNodePoolApi.ClustersNodepoolsGet(context.TODO(), *dpCluster.Id).Execute() if err != nil { return err } if dpNodePools.Items == nil { log.Printf("[WARNING] expected a response containing data platform node pools but received 'nil' instead, skipping search for data platform cluster with ID: %v", *dpCluster.Id) continue } for _, dpNodePool := range *dpNodePools.Items { if dpNodePool.Properties == nil || dpNodePool.Properties.Name == nil { log.Printf("[WARNING] 'nil' values in the response for data platform node pool with ID %v, cluster ID: %v, skipping this resource", *dpNodePool.Id, *dpCluster.Id) co
func (g *DataPlatformNodePoolGenerator) InitResources() error { client := g.generateClient() dataPlatformClient := client.DataPlatformAPIClient resourceType := "ionoscloud_dataplatform_node_pool" dpClusters, _, err := dataPlatformClient.DataPlatformClusterApi.ClustersGet(context.TODO()).Execute() if err != nil { return err } if dpClusters.Items == nil { log.Printf("[WARNING] expected a response containing data platform clusters but received 'nil' instead.") return nil } for _, dpCluster := range *dpClusters.Items { dpNodePools, _, err := dataPlatformClient.DataPlatformNodePoolApi.ClustersNodepoolsGet(context.TODO(), *dpCluster.Id).Execute() if err != nil { return err } if dpNodePools.Items == nil { log.Printf("[WARNING] expected a response containing data platform node pools but received 'nil' instead, skipping search for data platform cluster with ID: %v", *dpCluster.Id) continue } for _, dpNodePool := range *dpNodePools.Items { if dpNodePool.Properties == nil || dpNodePool.Properties.Name == nil { log.Printf("[WARNING] 'nil' values in the response for data platform node pool with ID %v, cluster ID: %v, skipping this resource", *dpNodePool.Id, *dpCluster.Id) continue } g.Resources = append(g.Resources, terraformutils.NewResource( *dpNodePool.Id, *dpNodePool.Properties.Name+"-"+*dpNodePool.Id, resourceType, helpers.Ionos, map[string]string{helpers.ClusterID: *dpCluster.Id}, []string{}, map[string]interface{}{})) } } return nil }
531,467
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: secrets_encrypt.go path of file: ./repos/k3s/pkg/cli/cmds the code of the file until where you have to start completion: package cmds import ( "github.com/k3s-io/k3s/pkg/version" "github.com/urfave/cli" ) const SecretsEncryptCommand = "secrets-encrypt" var ( forceFlag = &cli.BoolFlag{ Name: "f,force", Usage: "Force this stage.", Destination: &ServerConfig.EncryptForce, } EncryptFlags = []cli.Flag{ DataDirFlag, ServerToken, &cli.StringFlag{ Name: "server, s", Usage: "(cluster) Server to connect to", EnvVar: version.ProgramUpper + "_URL", Value: "https://127.0.0.1:6443", Destination: &ServerConfig.ServerURL, }, } ) func NewSecretsEncryptCommands(status, enable, disable, prepare, rotate, reencrypt, rotateKeys func(ctx *cli.Context) error) cli.Command { return cli.Command{ Name: SecretsEncryptCommand, Usage: "Control secrets encryption and keys rotation", SkipArgReorder: true, Subcommands: []cli.Command{ { Name: "status", Usage: "Print current status of secrets encryption", SkipArgReorder: true, Action: st
func NewSecretsEncryptCommands(status, enable, disable, prepare, rotate, reencrypt, rotateKeys func(ctx *cli.Context) error) cli.Command { return cli.Command{ Name: SecretsEncryptCommand, Usage: "Control secrets encryption and keys rotation", SkipArgReorder: true, Subcommands: []cli.Command{ { Name: "status", Usage: "Print current status of secrets encryption", SkipArgReorder: true, Action: status, Flags: append(EncryptFlags, &cli.StringFlag{ Name: "output,o", Usage: "Status format. Default: text. Optional: json", Destination: &ServerConfig.EncryptOutput, }), }, { Name: "enable", Usage: "Enable secrets encryption", SkipArgReorder: true, Action: enable, Flags: EncryptFlags, }, { Name: "disable", Usage: "Disable secrets encryption", SkipArgReorder: true, Action: disable, Flags: EncryptFlags, }, { Name: "prepare", Usage: "Prepare for encryption keys rotation", SkipArgReorder: true, Action: prepare, Flags: append(EncryptFlags, forceFlag), }, { Name: "rotate", Usage: "Rotate secrets encryption keys", SkipArgReorder: true, Action: rotate, Flags: append(EncryptFlags, forceFlag), }, { Name: "reencrypt", Usage: "Reencrypt all data with new encryption key", SkipArgReorder: true, Action: reencrypt, Flags: append(EncryptFlags, forceFlag, &cli.BoolFlag{ Name: "skip", Usage: "Skip removing old key", Destination: &ServerConfig.EncryptSkip, }), }, { Name: "rotate-keys", Usage: "(experimental) Dynamically rotates secrets encryption keys and re-encrypt secrets", SkipArgReorder: true, Action: rotateKeys, Flags: EncryptFlags, }, }, } }
110,503
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: jobtemplatespec.go path of file: ./repos/agones/vendor/k8s.io/client-go/applyconfigurations/batch/v1 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
func (b *JobTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *JobTemplateSpecApplyConfiguration { b.ensureObjectMetaApplyConfigurationExists() for i := range values { b.Finalizers = append(b.Finalizers, values[i]) } return b }
445,646
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: ui.rs path of file: ./repos/taskwarrior-tui/src the code of the file until where you have to start completion: use ratatui::{ backend::Backend, layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, symbols, text::{Line, Spa
fn draw_title<'a>() -> Paragraph<'a> { Paragraph::new("Taskwarrior TUI") .style(Style::default().fg(Color::LightCyan)) .alignment(Alignment::Center) .block( Block::default() .borders(Borders::ALL) .style(Style::default().fg(Color::White)) .border_type(BorderType::Plain), ) }
64,600
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: query.go path of file: ./repos/plik/vendor/github.com/jackc/pgx/v5/pgproto3 the code of the file until where you have to start completion: package pgproto3 import ( "bytes" "encoding/json" "github.com/jackc/pgx/v5
func (src Query) MarshalJSON() ([]byte, error) { return json.Marshal(struct { Type string String string }{ Type: "Query", String: src.String, }) }
374,283
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: base.rb path of file: ./repos/coursemology2/lib/extensions/acts_as_helpers/active_record the code of the file until where you have to start completion: # frozen_string_literal: true module Extensions::ActsAsHelpers::ActiveRecord::Base module ClassMethods # Decorator for items that give course_users EXP Points def acts_as_experience_points_record acts_as :experience
def acts_as_lesson_plan_item(has_todo: false) acts_as :lesson_plan_item, class_name: Course::LessonPlan::Item.name, autosave: true after_initialize do handle_todo_default(has_todo) if new_record? end scope :active, (lambda do joins(lesson_plan_item: :default_reference_time).merge(Course::ReferenceTime.currently_active) end) include LessonPlanItemInstanceMethods include LessonPlanItemPrivateMethods end end
43,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: autoscaling_client.go path of file: ./repos/kubeedge/vendor/k8s.io/client-go/kubernetes/typed/autoscaling/v1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apach
func NewForConfigOrDie(c *rest.Config) *AutoscalingV1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client }
418,718
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/risc0/examples/voting-machine/src 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://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing,
pub fn freeze(&mut self) -> Result<FreezeStationMessage> { tracing::info!("freeze"); let params = FreezeVotingMachineParams::new(self.state.clone()); let mut output = Vec::new(); let env = ExecutorEnv::builder() .write(&params)? .stdout(&mut output) .build()?; let prover = default_prover(); let receipt = prover.prove(env, FREEZE_ELF)?; let result: FreezeVotingMachineResult = from_slice(&output)?; self.state = result.state; Ok(FreezeStationMessage { receipt }) }
382,952
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: iterator.go path of file: ./repos/ledisdb/store the code of the file until where you have to start completion: package store import ( "bytes" "github.com/ledisdb/ledisdb/store/driver" ) const ( IteratorForward uint8 = 0 IteratorBa
func rangeLimitIterator(i *Iterator, r *Range, l *Limit, direction uint8) *RangeLimitIterator { it := new(RangeLimitIterator) it.it = i it.r = r it.l = l it.direction = direction it.step = 0 if l.Offset < 0 { return it } if direction == IteratorForward { if r.Min == nil { it.it.SeekToFirst() } else { it.it.Seek(r.Min) if r.Type&RangeLOpen > 0 { if it.it.Valid() && bytes.Equal(it.it.RawKey(), r.Min) { it.it.Next() } } } } else { if r.Max == nil { it.it.SeekToLast() } else { it.it.Seek(r.Max) if !it.it.Valid() { it.it.SeekToLast() } else { if !bytes.Equal(it.it.RawKey(), r.Max) { it.it.Prev() } } if r.Type&RangeROpen > 0 { if it.it.Valid() && bytes.Equal(it.it.RawKey(), r.Max) { it.it.Prev() } } } } for i := 0; i < l.Offset; i++ { if it.it.Valid() { if it.direction == IteratorForward { it.it.Next() } else { it.it.Prev() } } } return it }
327,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: DEMO_febio_0022_multigen_interface_band.m path of file: ./repos/GIBBON/docs the code of the file until where you have to start completion: %% DEMO_febio_0022_multigen_interface_band % Below is a demonstration for: % % * Building geometry for limb-like segment with an elastic band wrapped around it %
function can be used to view the xml structure in a MATLAB % figure window. %% % febView(febio_spec); %Viewing the febio file %% Exporting the FEBio input file % Exporting the febio_spec structure to an FEBio input file is done using % the |febioStruct2xml| function. febioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode %% Running the FEBio analysis % To run the analysis defined by the created FEBio input file the % |runMonitorFEBio| function is used. The input for this function is a % structure defining job settings e.g. the FEBio input file name. The % optional output runFlag informs the user if the analysis was run % succesfully. febioAnalysis.run_filename=febioFebFileName; %The input file name febioAnalysis.run_logname=febioLogFileName; %The name for the log file febioAnalysis.disp_on=1; %Display information on the command window febioAnalysis.runMode=runMode; [runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!! %% Import FEBio results if runFlag==1 %i.e. a succesful run %% % Importing nodal displacements from a log file dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp),0,1); %Access data N_disp_mat=dataStruct.data; %Displacement timeVec=dataStruct.time; %Time %Create deformed coordinate set V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]); %% % Importing element stress from a log file dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_strainEnergy),0,1); %Access data E_energy=dataStruct.data; %% % Plotting the simulated results using |anim8| to visualize and animate % deformations c1_plot=c1*ones(size(timeVec)); cg_plot=c1_g(1)*ones(size(timeVec)); cg_plot(timeVec>=1)=c1_g(2); [CV]=faceToVertexMeasure(E,V,E_energy(:,:,end
166,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: _artifact_store_type.rs path of file: ./repos/aws-sdk-rust/sdk/codepipeline/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), } }
780,877
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _input_prepare_schedule_action_settings.rs path of file: ./repos/aws-sdk-rust/sdk/medialive/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 ED
pub fn build(self) -> crate::types::InputPrepareScheduleActionSettings { crate::types::InputPrepareScheduleActionSettings { input_attachment_name_reference: self.input_attachment_name_reference, input_clipping_settings: self.input_clipping_settings, url_path: self.url_path, } }
779,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: activities.go path of file: ./repos/temporal/service/worker/batcher the code of the file until where you have to start completion: // The MIT License // // Copyright (c) 2022 Temporal Technologies Inc. All rights reserved. // // Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the
func (a *activities) checkNamespace(namespace string) error { // Ignore system namespace for backward compatibility. // TODO: Remove the system namespace special handling after 1.19+ if namespace != a.namespace.String() && a.namespace.String() != primitives.SystemLocalNamespace { return errNamespaceMismatch } return nil }
199,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: tap_formatter.rb path of file: ./repos/rubocop/lib/rubocop/formatter the code of the file until where you have to start completion: # frozen_string_literal: true module RuboCop module Formatter # This
def report_line(location) source_line = location.source_line if location.single_line? output.puts("# #{source_line}") else output.puts("# #{source_line} #{yellow(ELLIPSES)}") end
733,329
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: armor.go path of file: ./repos/podman/vendor/golang.org/x/crypto/openpgp/armor the code of the file until where you have to start completion: // Copyright 2010 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 armor implements OpenPGP ASCII Armor, see RFC
func (r *openpgpReader) Read(p []byte) (n int, err error) { n, err = r.b64Reader.Read(p) r.currentCRC = crc24(r.currentCRC, p[:n]) if err == io.EOF && r.lReader.crcSet && r.lReader.crc != r.currentCRC&crc24Mask { return 0, ArmorCorrupt } return }
106,785
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: apache_activemq_rce_cve_2023_46604.rb path of file: ./repos/metasploit-framework/modules/exploits/multi/misc the code of the file until where you have to start completion: ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking prepend Msf::Exploit::Remote::AutoCheck include Msf::Exploit::Remote::HttpServer include Msf::Exploit::Remote::Tcp include Msf::Exploit::Retry def initialize(info = {}) super( update_info( info, 'Name' => 'Apache ActiveMQ Unauthenticated Remote Code Execution', 'Description' => %q{ This module exploits a deserialization vulnerability in the OpenWire transport unmarshaller in Apache ActiveMQ. Affected versions include 5.18.0 through to 5.18.2, 5.17.0 through to 5.17.5, 5.16.0 through to 5.16.6, and all versions before 5.15.16. }, 'License' => MSF_LICENSE, 'Author' => [ 'X1r0z', # Original technical analysis & exploit 'sfewer-r7', # MSF exploit & Rapid7 analysis ], 'References' => [ ['CVE', '2023-46604'], ['URL', 'https://github.com/X1r0z/ActiveMQ-RCE'], ['URL', 'https://exp10it.cn/2023/10/apache-activemq-%E7%89%88%E6%9C%AC-5.18.3-rce-%E5%88%86%E6%9E%90/'], ['URL', 'https://attackerkb.com/topics/IHsgZDE3tS/cve-2023-46604/rapid7-analysis'], ['URL', 'https://activemq.apache.org/security-advisories.data/CVE-2023-46604-announcement.txt'] ], 'DisclosureDate' => '2023-10-27', 'Privileged' => false, 'Platform' => %w[win linux unix], 'Arch' => [ARCH_CMD], # The Msf::Exploit::Remote::HttpServer mixin will bring in Exploit::Remote::SocketServer, this will set the # Stance to passive, which is unexpected and results in the exploit running as a background job, as RunAsJob will # be set to true. To avoid this happening, we explicitly set the Stance to Aggressive. 'Stance' => Stance::Aggressive, 'Targets' => [
def initialize(info = {}) super( update_info( info, 'Name' => 'Apache ActiveMQ Unauthenticated Remote Code Execution', 'Description' => %q{ This module exploits a deserialization vulnerability in the OpenWire transport unmarshaller in Apache ActiveMQ. Affected versions include 5.18.0 through to 5.18.2, 5.17.0 through to 5.17.5, 5.16.0 through to 5.16.6, and all versions before 5.15.16. }, 'License' => MSF_LICENSE, 'Author' => [ 'X1r0z', # Original technical analysis & exploit 'sfewer-r7', # MSF exploit & Rapid7 analysis ], 'References' => [ ['CVE', '2023-46604'], ['URL', 'https://github.com/X1r0z/ActiveMQ-RCE'], ['URL', 'https://exp10it.cn/2023/10/apache-activemq-%E7%89%88%E6%9C%AC-5.18.3-rce-%E5%88%86%E6%9E%90/'], ['URL', 'https://attackerkb.com/topics/IHsgZDE3tS/cve-2023-46604/rapid7-analysis'], ['URL', 'https://activemq.apache.org/security-advisories.data/CVE-2023-46604-announcement.txt'] ], 'DisclosureDate' => '2023-10-27', 'Privileged' => false, 'Platform' => %w[win linux unix], 'Arch' => [ARCH_CMD], # The Msf::Exploit::Remote::HttpServer mixin will bring in Exploit::Remote::SocketServer, this will set the # Stance to passive, which is unexpected and results in the exploit running as a background job, as RunAsJob will # be set to true. To avoid this happening, we explicitly set the Stance to Aggressive. 'Stance' => Stance::Aggressive, 'Targets' => [ [ 'Windows', { 'Platform' => 'win' } ], [ 'Linux', { 'Platform' => 'linux' } ], [ 'Unix', { 'Platform' => 'unix' } ] ], 'DefaultTarget' => 0, 'DefaultOptions' => { # By default ActiveMQ listens for OpenWire requests on TCP port 61616. 'RPORT' => 61616, # The maximum time in seconds to wait for a session. 'WfsDelay' => 30 }, 'Notes' => { 'Stability' => [CRASH_SAFE], 'Reliability' => [REPEATABLE_SESSION], 'SideEffects' => [IOC_IN_LOGS] } ) ) end
741,833
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: document.go path of file: ./repos/kubeedge/vendor/github.com/google/gnostic/openapiv2 the code of the file until where you have to start completion: // Copyright 2020 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this f
func (d *Document) YAMLValue(comment string) ([]byte, error) { rawInfo := d.ToRawInfo() rawInfo = &yaml.Node{ Kind: yaml.DocumentNode, Content: []*yaml.Node{rawInfo}, HeadComment: comment, } return yaml.Marshal(rawInfo) }
414,542
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: init.rs path of file: ./repos/linfa/algorithms/linfa-clustering/src/k_means the code of the file until where you have to start completion: use super::algorithm::{update_cluster_memberships, update_min_dists}; use linfa::Float; use linfa_nn::distance::Distance; use ndarray::parallel::prelude::*; use ndarray::{s, Array1, Array2, ArrayBase, ArrayView1, ArrayView2, Axis, Data, Ix2}; use ndarray_rand::rand::distributions::{Distribution, WeightedIndex}; use ndarray_rand::rand::Rng; use ndarray_rand::rand::{self, SeedableRng}; use rand_xoshiro::Xoshiro256Plus; #[cfg(feature = "serde")] use serde_crate::{Deserialize, Serialize}; use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; #[cfg_attr( feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate") )] #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] /// Specifies centroid initialization algorithm for KMeans. pub enum KMeansInit<F: Float> { /// Pick random points as centroids. Random, /// Precomputed list of centroids, represented as an array of (n_centroids, n_features). Precomputed(Array2<F>), /// K-means++ algorithm. Using this over random initialization causes K-means to converge /// faster for almost all cases, since K-means++ produces better centroids. KMeansPlusPlus, /// K-means|| algorithm, a parallelized version of K-means++. Performs much better than /// K-means++ when the number of clusters is large (>100) while producing similar centroids, so /// use this for larger datasets. Details on the algorithm can be found /// [here](http://vldb.org/pvldb/vol5/p622_bahmanbahmani_vldb2012.pdf). KMeansPara, } impl<F: Float> KMeansInit<F> { /// Runs the chosen initialization routine pub(crate) fn run<R: Rng, D: Distance<F>>( &self, dist_fn: &D, n_clusters: usize, observations: ArrayView2<F>, rng: &mut R, ) -> Array2<F> { match self { Self::Random => random_init(n_clusters, observations, rng), Self::KMeansPlusPlus => k_means_plusplus(dist_fn, n_clusters, observations, rng), Self::KMeansPara => k_means_para(dist_fn, n_clusters, observations, rng), Self::Precomputed(centroids) => { // Check centroid dimensions assert_eq!(centroids.nrows(), n_clusters); assert_eq!(centroids.ncols(), observations.ncols()); centroids.clone() } } } } /// Pick random points from the input matrix as centroids fn random_init<F: Float>( n_clusters: usize, observations: ArrayView2<F>, rng: &mut impl Rng, ) -> Array2<F> { let (n_samples, _) = observations.dim(); let indices = rand::seq::index::sample(rng, n_samples, n_clusters).into_vec(); observations.select(Axis(0), &indices) } /// Selects centroids using the KMeans++ initialization algorithm. The weights determine the /// likeliness of an input point to be selected as a centroid relative to other points. The higher /// the weight, the more likely the point will be selected as a centroid. fn weighted_k_means_plusplus<F: Float, D: Distance<F>>( dist_fn: &D, n_clusters: usize, observations: ArrayView2<F>, weights: ArrayView1<F>, rng: &mut impl Rng, ) -> Array2<F> { let (n_samples, n_features) = observations.dim(); assert_eq!(n_samples, weights.len()); assert_ne!(weights.sum(), F::zero()); let mut centroids = Array2::zeros((n_clusters, n_features)); // Select 1st centroid from the input randomly purely based on the weights. let first_idx = WeightedIndex::new(weights.iter()) .expect("invalid weights") .sample(rng); centroids.row_mut(0).assign(&observations.row(first_idx)); let mut dists = Array1::zeros(n_samples); for c_cnt in 1..n_clusters { update_min_dists( dist_fn, &centroids.slice(s![0..c_cnt, ..]), &observations, &mut dists, ); // The probability of a point being selected as the next centroid is proportional to its // distance from its closest centroid multiplied by its weight. dists *= &weights; let centroid_idx = WeightedIndex::new(dists.iter()) .map(|idx| idx.sample(rng)) // This only errs if all of dists is 0, which means every point is assigned to a // centroid, so extra centroid
fn autotraits() { fn has_autotraits<T: Send + Sync + Sized + Unpin>() {} has_autotraits::<KMeansInit<f64>>(); } #[test] fn test_precomputed() { let mut rng = Xoshiro256Plus::seed_from_u64(40); let centroids = array![[0.0, 1.0], [40.0, 10.0]]; let observations = array![[3.0, 4.0], [1.0, 3.0], [25.0, 15.0]]; let c = KMeansInit::Precomputed(centroids.clone()).run( &L2Dist, 2, observations.view(), &mut rng, ); assert_abs_diff_eq!(c, centroids); } #[test] fn test_sample_subsequent_candidates() { let dists = array![0.0, 0.4, 0.5]; let candidates = sample_subsequent_candidates::<Xoshiro256Plus, _>(&dists, 8.0, 0); assert_eq!(candidates, vec![1, 2]); } #[test] fn test_cluster_membership_counts() { let centroids = array![[0.0, 1.0], [40.0, 10.0], [3.0, 9.0]]; let observations = array![[3.0, 4.0], [1.0, 3.0], [25.0, 15.0]]; let counts = cluster_membership_counts(&L2Dist, &centroids, &observations); assert_abs_diff_eq!(counts, array![2.0, 1.0, 0.0]); let counts = cluster_membership_counts(&L1Dist, &centroids, &observations); assert_abs_diff_eq!(counts, array![1.0, 1.0, 1.0]); } #[test] fn test_weighted_kmeans_plusplus() { let mut rng = Xoshiro256Plus::seed_from_u64(42); let obs = Array::random_using((1000, 2), Normal::new(0.0, 100.).unwrap(), &mut rng); let mut weights = Array1::zeros(1000); weights[0] = 2.0; weights[1] = 3.0; let out = weighted_k_means_plusplus(&L2Dist, 2, obs.view(), weights.view(), &mut rng); let mut expected_centroids = { let mut arr = Array2::zeros((2, 2)); arr.row_mut(0).assign(&obs.row(0)); arr.row_mut(1).assign(&obs.row(1)); arr }; assert!( abs_diff_eq!(out, expected_centroids) || { expected_centroids.invert_axis(Axis(0)); abs_diff_eq!(out, expected_centroids) } ); } #[test] fn test_k_means_plusplus() { verify_init(KMeansInit::KMeansPlusPlus, L2Dist); verify_init(KMeansInit::KMeansPlusPlus, L1Dist); } #[test] fn test_k_means_para() { verify_init(KMeansInit::KMeansPara, L2Dist); verify_init(KMeansInit::KMeansPara, L1Dist); } // Run general tests for a given init algorithm fn verify_init<D: Distance<f64>>(init: KMeansInit<f64>, dist_fn: D) { let mut rng = Xoshiro256Plus::seed_from_u64(42); // Make sure we don't panic on degenerate data (n_clusters > n_samples) let degenerate_data = array![[1.0, 2.0]]; let out = init.run(&dist_fn, 2, degenerate_data.view(), &mut rng); assert_abs_diff_eq!(out, concatenate![Axis(0), degenerate_data, degenerate_data]); // Build 3 separated clusters of points let centroids = [20.0, -1000.0, 1000.0]; let clusters: Vec<Array2<_>> = centroids .iter() .map(|&c| Array::random_using((50, 2), Normal::new(c, 1.).unwrap(), &mut rng)) .collect(); let obs = clusters.iter().fold(Array2::default((0, 2)), |a, b| { concatenate(Axis(0), &[a.view(), b.view()]).unwrap() }); // Look for the right number of centroids let out = init.run(&dist_fn, centroids.len(), obs.view(), &mut rng); let mut cluster_ids = HashSet::new(); for row in out.rows() { // Centroid should not be 0 assert_abs_diff_ne!(row, Array1::zeros(row.len()), epsilon = 1e-1); // Find the resultant centroid in 1 of the 3 clusters let found = clusters .iter() .enumerate() .find_map(|(i, c)| { if c.rows().into_iter().any(|cl| abs_diff_eq!(row, cl)) { Some(i) } else { None } }) .unwrap(); cluster_ids.insert(found); } // Centroids should almost always span all 3 clusters assert_eq!(cluster_ids, [0, 1, 2].iter().copied().collect()); } macro_rules! calc_loss { ($dist_fn:expr, $centroids:expr, $observations:expr) => {{ let mut dists = Array1::zeros($observations.nrows()); update_min_dists(&$dist_fn, &$centroids, &$observations, &mut dists); dists.sum() }}; } fn test_compare<D: Distance<f64>>(dist_fn: D) { let mut rng = Xoshiro256Plus::seed_from_u64(42); let centroids = [20.0, -1000.0, 1000.0]; let clusters: Vec<Array2<_>> = centroids .iter() .map(|&c| Array::random_using((50, 2), Normal::new(c, 1.).unwrap(), &mut rng)) .collect(); let obs = clusters.iter().fold(Array2::default((0, 2)), |a, b| { concatenate(Axis(0), &[a.view(), b.view()]).unwrap() }); let out_rand = random_init(3, obs.view(), &mut rng.clone()); let out_pp = k_means_plusplus(&dist_fn, 3, obs.view(), &mut rng.clone()); let out_para = k_means_para(&dist_fn, 3, obs.view(), &mut rng); // Loss of Kmeans++ should be better than using random_init assert!(calc_loss!(dist_fn, out_pp, obs) < calc_loss!(dist_fn, out_rand, obs)); // Loss of Kmeans|| should be better than using random_init assert!(calc_loss!(dist_fn, out_para, obs) < calc_loss!(dist_fn, out_rand, obs)); } #[test] fn test_compare_l2() { test_compare(L2Dist); } #[test] fn test_compare_l1() { test_compare(L1Dist); } }
111,637
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/101-200/0168.Excel-Sheet-Column-Title 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 { name string inputs int expect string }{ {"TestCase1", 1, "A"}, {"TestCase2", 28, "AB"}, {"TestCase3", 701, "ZY"}, } // 开始测试 for i, c := range ca
func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string inputs int expect string }{ {"TestCase1", 1, "A"}, {"TestCase2", 28, "AB"}, {"TestCase3", 701, "ZY"}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { got := Solution(c.inputs) if !reflect.DeepEqual(got, c.expect) { t.Fatalf("expected: %v, but got: %v, with inputs: %v", c.expect, got, c.inputs) } }) } }
186,777
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: 20181030143627_create_password_histories.rb path of file: ./repos/ifme/db/migrate the code of the file until where you have to start completion: class CreatePasswordHistories < ActiveRecord::Migrati
def up create_table :password_histories do |t| t.integer :user_id, null: false t.string :encrypted_password t.datetime :created_at, null: false end end
636,582
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: inspect.go path of file: ./repos/shiba/cmd the code of the file until where you have to start completion: package main
func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Reads indexes from the given database and outputs the results in CSV.\n") fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) flag.PrintDefaults() } }
123,127
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/alexaforbusiness/src/operation/search_rooms 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, } }
779,030
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.go path of file: ./repos/im_service/imr the code of the file until where you have to start completion: /** * Copyright (c) 2014-2015, GoBelieve * All rights reserved. * * 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 2 of the License, or * (at your option) any la
func GetOnlineClients(w http.ResponseWriter, req *http.Request) { clients := GetClientSet() type App struct { AppId int64 `json:"appid"` Users []int64 `json:"users"` } r := make(map[int64]IntSet) for c := range(clients) { app_users := c.app_route.GetUsers() for appid, users := range(app_users) { if _, ok := r[appid]; !ok { r[appid] = NewIntSet() } uids := r[appid] for uid := range(users) { uids.Add(uid) } } } apps := make([]*App, 0, len(r)) for appid, users := range(r) { app := &App{} app.AppId = appid app.Users = make([]int64, 0, len(users)) for uid := range(users) { app.Users = append(app.Users, uid) } apps = append(apps, app) } res, err := json.Marshal(apps) if err != nil { log.Info("json marshal:", err) WriteHttpError(400, "json marshal err", w) return } w.Header().Add("Content-Type", "application/json") _, err = w.Write(res) if err != nil { log.Info("write err:", err) } }
50,447
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/voiceid/src/operation/disassociate_fraudster 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, } }
775,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: model_pod_item_labels.go path of file: ./repos/pipeline/.gen/pipeline/pipeline the code of the file until where you have to start completion: /* * Pipeline API * * Pipeline is a feature rich application platform, built for containers on top of Kubernetes to automate the DevOps experience, continuous application development and the lifecycle
func AssertRecursePodItemLabelsRequired(objSlice interface{}) error { return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { aPodItemLabels, ok := obj.(PodItemLabels) if !ok { return ErrTypeAssertionError } return AssertPodItemLabelsRequired(aPodItemLabels) }) }
255,449
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: source.rs path of file: ./repos/mos/mos-core/src/parser the code of the file until where you have to start completion: use crate::errors::{map_io_error, CoreResult}; use codespan_repo
fn get_contents(&self, path: &Path) -> CoreResult<String> { match self.files.get(path.to_str().unwrap()) { Some(data) => Ok(data.to_string()), None => Err(Diagnostic::error() .with_message(format!("file not found: '{}'", path.to_str().unwrap())) .into()), } }
552,311
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: xlnet_vocab.rs path of file: ./repos/rust-tokenizers/main/src/vocab the code of the file until where you have to start completion: // Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. // Copyright 2019-2020 Guillaume Becquin // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You
fn from_file<P: AsRef<Path>>(path: P) -> Result<XLNetVocab, TokenizerError> { let values = read_protobuf_file(path)?; let special_token_map = SpecialTokenMap { unk_token: DEFAULT_UNK_TOKEN.to_string(), pad_token: Some(DEFAULT_PAD_TOKEN.to_string()), bos_token: Some(DEFAULT_BOS_TOKEN.to_string()), sep_token: Some(DEFAULT_SEP_TOKEN.to_string()), cls_token: Some(DEFAULT_CLS_TOKEN.to_string()), eos_token: Some(DEFAULT_EOS_TOKEN.to_string()), mask_token: Some(DEFAULT_MASK_TOKEN.to_string()), additional_special_tokens: Some(HashSet::from([ DEFAULT_EOP_TOKEN.to_string(), DEFAULT_EOD_TOKEN.to_string(), ])), }; Self::from_values_and_special_token_map(values, special_token_map) }
123,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: api_op_DescribeEventTopics.go path of file: ./repos/aws-sdk-go-v2/service/directoryservice the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package directoryservice import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middl
func newServiceMetadataMiddleware_opDescribeEventTopics(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "DescribeEventTopics", } }
220,629
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_AssociateResolverEndpointIpAddress.go path of file: ./repos/aws-sdk-go-v2/service/route53resolver the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package route53resolver import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.
func newServiceMetadataMiddleware_opAssociateResolverEndpointIpAddress(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "AssociateResolverEndpointIpAddress", } }
219,786
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: generate_plan_tests.rs path of file: ./repos/nixpacks/tests the code of the file until where you have to start completion: use nixpacks::{generate_build_plan, nixpacks::plan::generator::GeneratePlanOptions}; use std::env::consts::ARCH; test_helper::generate_plan_tests!(); #[test] fn test_custom_plan_path() { let plan = generate_build_p
fn test_rust_rocket() { let plan = simple_gen_plan("./examples/rust-rocket"); let build = plan.get_phase("build").unwrap(); let start = plan.start_phase.clone().unwrap(); assert_eq!( build.cmds, Some(vec![ format!("mkdir -p bin"), format!("cargo build --release --target {ARCH}-unknown-linux-musl"), format!("cp target/{ARCH}-unknown-linux-musl/release/rocket bin") ]) ); assert!(start.cmd.is_some()); assert_eq!(start.clone().cmd.unwrap(), "./bin/rocket".to_string()); assert!(start.run_image.is_some()); }
120,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: bits_compat.go path of file: ./repos/goHackTools/vendor/golang.org/x/crypto/internal/poly1305 the code of the file until where you have to start completion: // Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-st
func bitsMul64(x, y uint64) (hi, lo uint64) { const mask32 = 1<<32 - 1 x0 := x & mask32 x1 := x >> 32 y0 := y & mask32 y1 := y >> 32 w0 := x0 * y0 t := x1*y0 + w0>>32 w1 := t & mask32 w2 := t >> 32 w1 += x0 * y1 hi = x1*y1 + w2 + w1>>32 lo = x * y return }
651,309
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: op_test.go path of file: ./repos/delve/pkg/dwarf/op the code of the file until where you have to start completion: package op import ( "strings" "testing" ) func assertExprResult(t *testing.T, expected int64, instructions []byte) { t.Helper() actual, _, err := ExecuteStackProgram(DwarfRegist
func assertExprResult(t *testing.T, expected int64, instructions []byte) { t.Helper() actual, _, err := ExecuteStackProgram(DwarfRegisters{}, instructions, 8, nil) if err != nil { t.Error(err) } if actual != expected { buf := new(strings.Builder) PrettyPrint(buf, instructions, nil) t.Errorf("actual %d != expected %d (in %s)", actual, expected, buf.String()) } }
620,378
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: corenums.m path of file: ./repos/deep-photo-styletransfer/gen_laplacian/gaimc the code of the file until where you have to start completion: function [d rt]=corenums(A) % CORENUMS Compute the core number for each vertex in the graph. % % [cn rt]=corenums(A) returns the core numbers for each vertex of the graph % A along with the removal order of the vertex. The core number is the % largest integer c such that vertex v exists in a graph where all % vertices have degree >= c. The vector rt returns the removal time % for each vertex. That is, vertex vi was removed at step rt[vi]. % % This method works on directed graphs but gives the in-degree core number. % To get the out-degree core numbers, call corenums(A'). %
function [d rt]=corenums(A) % CORENUMS Compute the core number for each vertex in the graph. % % [cn rt]=corenums(A) returns the core numbers for each vertex of the graph % A along with the removal order of the vertex. The core number is the % largest integer c such that vertex v exists in a graph where all % vertices have degree >= c. The vector rt returns the removal time % for each vertex. That is, vertex vi was removed at step rt[vi]. % % This method works on directed graphs but gives the in-degree core number. % To get the out-degree core numbers, call corenums(A'). % % The linear algorithm comes from: % Vladimir Batagelj and Matjaz Zaversnik, "An O(m) Algorithm for Cores % Decomposition of Networks." Sept. 1 2002. % % Example: % load_gaimc_graph('cores_example'); % the graph A has three components % corenums(A) % % See also WCORENUMS % David F. Gleich % Copyright, Stanford University, 2008-2009 % History % 2008-04-21: Initial Coding if isstruct(A), rp=A.rp; ci=A.ci; %ofs=A.offset; else [rp ci]=sparse_to_csr(A); end
628,242
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_QueryParamsAsStringListMap.go path of file: ./repos/aws-sdk-go-v2/internal/protocoltest/restxml the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package restxml import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.
func newServiceMetadataMiddleware_opQueryParamsAsStringListMap(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "QueryParamsAsStringListMap", } }
215,671
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/1001-1100/1025.Divisor-Game 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 { name string inputs bool expect bool }{ {"TestCase", true, true}
func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string inputs bool expect bool }{ {"TestCase", true, true}, {"TestCase", true, true}, {"TestCase", false, false}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { got := Solution(c.inputs) if !reflect.DeepEqual(got, c.expect) { t.Fatalf("expected: %v, but got: %v, with inputs: %v", c.expect, got, c.inputs) } }) } }
185,501
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: sum.rs path of file: ./repos/faer-rs/src/linalg/reductions the code of the file until where you have to start completion: use super::LINEAR_IMPL_THRESHOLD; use crate::{ mat::MatRef, utils::{simd::*, slice::*}, }; use faer_entity::*; use pulp::Simd; #[inline(always)] fn sum_with_simd_and_offset_prologue<E: ComplexField, S: pulp::Simd>( simd: S, data: SliceGroup<'_, E>, offset: pulp::Offset<SimdMaskFor<E, S>>, ) -> SimdGroupFor<E, S> { let simd = SimdFor::<E, S>::new(simd); let zero = simd.splat(E::faer_zero()); let mut acc0 = zero; let mut acc1 = zero; let
fn sum_contiguous<E: ComplexField>(data: MatRef<'_, E>) -> E { struct Impl<'a, E: ComplexField> { data: MatRef<'a, E>, } impl<E: ComplexField> pulp::WithSimd for Impl<'_, E> { type Output = E; #[inline(always)] fn with_simd<S: pulp::Simd>(self, simd: S) -> Self::Output { let Self { data } = self; let offset = SimdFor::<E, S>::new(simd).align_offset_ptr(data.as_ptr(), LINEAR_IMPL_THRESHOLD); let last_offset = SimdFor::<E, S>::new(simd) .align_offset_ptr(data.as_ptr(), data.nrows() % LINEAR_IMPL_THRESHOLD); let acc = sum_with_simd_and_offset_pairwise_cols(simd, data, offset, last_offset); let simd = SimdFor::<E, S>::new(simd); simd.reduce_add(simd.rotate_left(acc, offset.rotate_left_amount())) } } E::Simd::default().dispatch(Impl { data }) }
159,606
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: response_transfer.go path of file: ./repos/mattermost/server/channels/app the code of the file until where you have to start completion: // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package app import ( "byte
func parseContentLength(cl string) int64 { cl = strings.TrimSpace(cl) if cl == "" { return -1 } n, err := strconv.ParseInt(cl, 10, 64) if err != nil { return -1 } return n }
476,113
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: JudgeMent.go path of file: ./repos/scan4all/webScan/Functions the code of the file until where you have to start completion: package Funcs import ( "fmt" Configs "github.com/GhostTroops/scan4all/webScan/config" "net/ht
func re_replace(str string, str_replace string) string { if str_replace == "" { return str } if strings.Contains(str, "{{replace{search}replace}}") { str = strings.ReplaceAll(str, "{{replace{search}replace}}", str_replace) } return str }
140,296
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: iam-virtual-mfa-devices.go path of file: ./repos/aws-nuke/resources the code of the file until where you have to start completion: package resources import ( "fmt" "strings" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/iam" ) type IAMVirtualMFADevice struct { svc *iam.IAM user *iam.User serialNumber string } func init() { register("IAMVirtualMFADevice", ListIAMV
func ListIAMVirtualMFADevices(sess *session.Session) ([]Resource, error) { svc := iam.New(sess) resp, err := svc.ListVirtualMFADevices(&iam.ListVirtualMFADevicesInput{}) if err != nil { return nil, err } resources := make([]Resource, 0) for _, out := range resp.VirtualMFADevices { resources = append(resources, &IAMVirtualMFADevice{ svc: svc, user: out.User, serialNumber: *out.SerialNumber, }) } return resources, nil }
495,361
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: test_rdoc_rd_inline.rb path of file: ./repos/rdoc/test/rdoc the code of the file until where you have to start completion: # frozen_string_literal: true require_relative 'helper' c
def test_append_inline out = @inline.append @inline assert_same @inline, out assert_equal '+text++text+', @inline.rdoc assert_equal 'texttext', @inline.reference end
203,210
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: urn8141.go path of file: ./repos/gotosocial/vendor/github.com/leodido/go-urn the code of the file until where you have to start completion: package urn import ( "encoding/json" "fmt" ) const errInvalidURN8141 = "invalid URN per RFC 8141: %s" type URN8141 str
func (u *URN8141) UnmarshalJSON(bytes []byte) error { var str string if err := json.Unmarshal(bytes, &str); err != nil { return err } if value, ok := Parse([]byte(str), WithParsingMode(RFC8141Only)); !ok { return fmt.Errorf(errInvalidURN8141, str) } else { *u = URN8141{value} } return nil }
24,748
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: DNLS2NLS.m path of file: ./repos/OPTI/Utilities/opti the code of the file until where you have to start completion: function prob = DNLS2NLS(prob,opts) %DNLS2NLS Converts a Dynamic NLS problem into a NLS problem % prob= DNLS2NLS(prob,opts) % Copyright (C) 2013 Jonathan Currie (Control Engineering) if(~isfield(prob,'type') || isempty(prob.type)) error('This function is not for user use, and should only be called from OPTI'); end %Get warning level warn = optiWarnLevel(opts.warnings); %Get Derivative Checker Level derCheck = false; if(strcmpi(opts.derivCheck,'on')), derCheck = true; end %Transpose as required if(size(prob.odez0,2) > 1), prob.odez0 = prob.odez0'; end %Get Options & Set Sizes dopts = optidynset(opts.dynamicOpts); dopts.n = length(prob.odez0); %number of states dopts.inz0 = isnan(prob.odez0); %index of initial states to estimate dopts.nz0 = sum(dopts.inz0); %number of initial states to estimate dopts.np = length(prob.x0)-dopts.nz0; %number of parameters dopts.inMe
function which accepts 3 arguments (t,z,p)'); end if(derCheck) z = @(z) prob.ode(1,z,x0); dfdz = @(z) dopts.dfdz(1,z,x0); optiDerCheck(z,dfdz,z0,'ODE DFDZ',warn); end dopts.dfdz_method = 2; else if(warn>1), optiwarn('OPTI:NoUserDer','You have specified to use user supplied derivatives for DFDZ, but the corresponding function is empty.\nUsing ND instead.'); end dopts.dfdz_method = 0; end else %Setup derivative estimation method if(strcmpi(dopts.sensitivity,'cs')) dopts.dfdz_method = 3; elseif(strcmpi(dopts.sensitivity,'ad')) dopts.dfdz_method = 1; else dopts.dfdz_method = 0; end end if(strcmpi(dopts.sensitivity,'user')) if(~isempty(dopts.dfdp)) if(nargin(dopts.dfdp) ~= 3), error('ODE dfdp must be a function which accepts 3 arguments (t,z,p)'); end if(derCheck) p = @(p) prob.ode(1,z0,p); dfdp = @(p) dopts.dfdp(1,z0,p); optiDerCheck(p,dfdp,x0,'ODE DFDP',warn); end dopts.dfdp_method = 2; else if(warn>1), optiwarn('OPTI:NoUserDer','You have specified to use user supplied derivatives for DFDP, but the corresponding function is empty.\nUsing ND instead.'); end dopts.dfdp_method = 0; end else %Setup derivative estimation method if(strcmpi(dopts.sensitivity,'cs')) dopts.dfdp_method = 3; elseif(strcmpi(dopts.sensitivity,'ad')) dopts.dfdp_method = 1; else dopts.dfdp_method = 0; end end %Assign Objective dopts.reqGrad = false; prob.fun = @(theta,tm) odeEstim(prob.ode,prob.odez0,tm,theta,dopts); prob.misc.fitFun = prob.fun; %Assign Gradient (if required) if(~strcmpi(dopts.sensitivity,'none')) %Setup Initial Sensitivity Sp0 = zeros(dopts.n,dopts.np); if(dopts.nz0) Sz0 = eye(dopts.n,dopts.n); Sz0(:,~dopts.inz0) = []; else Sz0 = []; end
275,178
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: decode.rb path of file: ./repos/grinder/node/lib/metasm/metasm the code of the file until where you have to start completion: # This file is part of Metasm, the Ruby assembly manipulation suite # Copyright (C) 2006-2009 Yoann GUILLOT # # Licence is LGPL, see LICENCE in the top-level directory require 'metasm/main' require 'metasm/render' module Metasm # symbolic pointer dereference # API similar to Expression class Indirection < ExpressionType # Expression (the pointer) attr_accessor :target alias pointer target alias pointer= target= # length in bytes of data referenced attr_accessor :len # address of the instruction who generated the indirection attr_accessor :origin def initialize(target, len, origin) @target, @len, @origin = target, len, origin end def reduce_rec ptr = Expression[@target.reduce] (ptr == Expression::Unknown) ? ptr : Indirection.new(ptr, @len, @origin) end def bind(h) h[self] || Indirection.new(@target.bind(h), @len, @origin) end def hash ; @target.hash^@len.to_i end def eql?(o) o.class == self.class and [o.target, o.len] == [@target, @len] end alias == eql? include Renderable def render ret = [] qual = {1 => 'byte', 2 => 'word', 4 => 'dword', 8 => 'qword'}[len] || "_#{len*8}bits" if len ret
def hash ; @target.hash^@len.to_i end def eql?(o) o.class == self.class and [o.target, o.len] == [@target, @len] end alias == eql? include Renderable def render ret = [] qual = {1 => 'byte', 2 => 'word', 4 => 'dword', 8 => 'qword'}[len] || "_#{len*8}bits" if len ret << "#{qual} ptr " if qual ret << '[' << @target << ']' end # returns the complexity of the expression (number of externals +1 per indirection) def complexity 1+@target.complexity end def self.[](t, l, o=nil) new(Expression[*t], l, o) end def inspect "Indirection[#{@target.inspect.sub(/^Expression/, '')}, #{@len.inspect}#{', '+@origin.inspect if @origin}]" end def externals @target.externals end def match_rec(target, vars) return false if not target.kind_of? Indirection t = target.target if vars[t] return false if @target != vars[t] elsif vars.has_key? t vars[t] = @target elsif t.kind_of? ExpressionType return false if not @target.match_rec(t, vars) else return false if targ != @target end if vars[target.len] return false if @len != vars[target.len] elsif vars.has_key? target.len vars[target.len] = @len else return false if target.len != @len end vars end
460,014
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ocr_test.go path of file: ./repos/chainlink/integration-tests/smoke the code of the file until where you have to start completion: package smoke import ( "math/big" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-testing-framework/logging" "github.com/smartcontractkit/chainlink-testing-framework/utils/testcontext" "github.com/smartcontractkit/chainlink/integration-tests/actions" "github.com/smartcontractkit/chainlink/integration-tests/contracts" "github.com/smartcontractkit/chainlink/integration-tests/docker/test_env" actions_seth "github.com/smartcontractkit/chainlink/integration-tests/actions/seth" tc "github.com/smartcontractkit/chainlink/integration-tests/testconfig" ) const ( ErrWatchingNewOCRRound = "Error watching for new OCR round" ) func TestOCRBasic(t *testing.T) { t.Parallel() l := logging.GetTestLogger(t) env, ocrInstances := prepareORCv1SmokeTestEnv(t, l, 5) nodeClients := env.ClCluster.NodeAPIs() workerNodes := nodeClients[1:] err := actions.SetAllAdapterResponsesToTheSameValueLocal(10, ocrInstances,
func TestOCRJobReplacement(t *testing.T) { t.Parallel() l := logging.GetTestLogger(t) env, ocrInstances := prepareORCv1SmokeTestEnv(t, l, 5) nodeClients := env.ClCluster.NodeAPIs() bootstrapNode, workerNodes := nodeClients[0], nodeClients[1:] err := actions.SetAllAdapterResponsesToTheSameValueLocal(10, ocrInstances, workerNodes, env.MockAdapter) require.NoError(t, err, "Error setting all adapter responses to the same value") err = actions_seth.WatchNewRound(l, env.SethClient, 2, contracts.V1OffChainAgrregatorToOffChainAggregatorWithRounds(ocrInstances), time.Duration(3*time.Minute)) require.NoError(t, err, ErrWatchingNewOCRRound) answer, err := ocrInstances[0].GetLatestAnswer(testcontext.Get(t)) require.NoError(t, err, "Error getting latest OCR answer") require.Equal(t, int64(10), answer.Int64(), "Expected latest answer from OCR contract to be 10 but got %d", answer.Int64()) err = actions.DeleteJobs(nodeClients) require.NoError(t, err, "Error deleting OCR jobs") err = actions.DeleteBridges(nodeClients) require.NoError(t, err, "Error deleting OCR bridges") //Recreate job err = actions.CreateOCRJobsLocal(ocrInstances, bootstrapNode, workerNodes, 5, env.MockAdapter, big.NewInt(env.SethClient.ChainID)) require.NoError(t, err, "Error creating OCR jobs") err = actions_seth.WatchNewRound(l, env.SethClient, 1, contracts.V1OffChainAgrregatorToOffChainAggregatorWithRounds(ocrInstances), time.Duration(3*time.Minute)) require.NoError(t, err, ErrWatchingNewOCRRound) answer, err = ocrInstances[0].GetLatestAnswer(testcontext.Get(t)) require.NoError(t, err, "Getting latest answer from OCR contract shouldn't fail") require.Equal(t, int64(10), answer.Int64(), "Expected latest answer from OCR contract to be 10 but got %d", answer.Int64()) }
493,686
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: marshaler_registry.go path of file: ./repos/buildkit/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime the code of the file until where you have to start completion: package runtime import ( "errors" "mime" "net/http" "google.golang.org
func WithMarshalerOption(mime string, marshaler Marshaler) ServeMuxOption { return func(mux *ServeMux) { if err := mux.marshalers.add(mime, marshaler); err != nil { panic(err) } } }
653,378
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: loadPoleFigure_beartex.m path of file: ./repos/mtex/interfaces the code of the file until where you have to start completion: function pf = loadPoleFigure_beartex(fname,varargin) % import data fom BeaTex file % % Syntax % pf = loadPoleFigure_beartex(fname) % % Input % fname - filename % % Output % pf - @PoleFigure % % See also % ImportPoleFigureData loadPoleFigure pf = PoleFigure; fid = efopen(fname); ipf = 1; r = regularS2Grid('points',[72, 19],'antipodal');
function pf = loadPoleFigure_beartex(fname,varargin) % import data fom BeaTex file % % Syntax % pf = loadPoleFigure_beartex(fname) % % Input % fname - filename % % Output % pf - @PoleFigure % % See also % ImportPoleFigureData loadPoleFigure pf = PoleFigure; fid = efopen(fname); ipf = 1; r = regularS2Grid('points',[72, 19],'antipodal'); spacegroup = {'C1','C2','D2','C4','D4','T','O','C3','D3','C6','D6'}; try while ~feof(fid) try % next polefigure for k=1:7, c{k} = fgetl(fid); end
606,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: id.go path of file: ./repos/kubernetes/vendor/google.golang.org/grpc/internal/channelz the code of the file until where you have to start completion: /* * * Copyright 2022 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"
func (id *Identifier) Equal(other *Identifier) bool { if (id != nil) != (other != nil) { return false } if id == nil && other == nil { return true } return id.typ == other.typ && id.id == other.id && id.pid == other.pid }
353,941
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: zz_generated.deepequal.go path of file: ./repos/hubble-ui/backend/vendor/github.com/cilium/cilium/pkg/alibabacloud/eni/types the code of the file until where you have to start completion: //go:build !ignore_autogenerated // +build !ignore_autogenerated // SPDX-License-Identifi
func (in *VSwitch) DeepEqual(other *VSwitch) bool { if other == nil { return false } if in.VSwitchID != other.VSwitchID { return false } if in.CIDRBlock != other.CIDRBlock { return false } if in.IPv6CIDRBlock != other.IPv6CIDRBlock { return false } return true }
378,662
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: evil_query.rb path of file: ./repos/diaspora/lib the code of the file until where you have to start completion: # frozen_string_literal: true module EvilQuery class
def initialize(user, klass, key, id, conditions={}) @querent = user @class = klass @key = key @id = id @conditions = conditions end
30,821
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: _power_phase.rs path of file: ./repos/aws-sdk-rust/sdk/outposts/src/types the code of the file until where you have to start completion: // Code generated by software.a
fn from(s: &str) -> Self { match s { "SINGLE_PHASE" => PowerPhase::SinglePhase, "THREE_PHASE" => PowerPhase::ThreePhase, other => PowerPhase::Unknown(crate::primitives::sealed_enum_unknown::UnknownVariantValue(other.to_owned())), } }
801,024
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: rooms.rs path of file: ./repos/HandsOnRust/InventoryAndPowerUps/carrying_items/src/map_builder the code of the file until where you have to start completion: use crate::prelude::*; use super::MapArchitect; pub struct RoomsArchitect {} impl MapArchitect for RoomsArchitect { fn new(&mut self, rng: &mut RandomNumberGenerator) -> MapBuilder { let mut mb = MapBuilder{ map : Map::new(), rooms: Vec::new(), monster_spawns : Vec::new(), player_s
fn new(&mut self, rng: &mut RandomNumberGenerator) -> MapBuilder { let mut mb = MapBuilder{ map : Map::new(), rooms: Vec::new(), monster_spawns : Vec::new(), player_start : Point::zero(), amulet_start : Point::zero(), theme: super::themes::DungeonTheme::new() }; mb.fill(TileType::Wall); mb.build_random_rooms(rng); mb.build_corridors(rng); mb.player_start = mb.rooms[0].center(); mb.amulet_start = mb.find_most_distant(); for room in mb.rooms.iter().skip(1) { mb.monster_spawns.push(room.center()); } mb }
286,887
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: env_visitor.go path of file: ./repos/erda/pkg/parser/diceyml the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc. // // Licensed under the Apache
func (o *EnvVisitor) VisitService(v DiceYmlVisitor, obj *Service) { if obj.Envs == nil { obj.Envs = map[string]string{} } for k, v := range o.globalEnv { if _, ok := obj.Envs[k]; !ok { obj.Envs[k] = v } } }
713,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: target.go path of file: ./repos/trojan-go/test/util the code of the file until where you have to start completion: package util import ( "crypto/rand" "fmt" "io" "io/ioutil" "net" "net/http" "sync" "time" "golang.org/x/net/websocket" "github.com/p4gefau1t/trojan-go/common" "github.com/p4gefau1t/trojan-go/log" ) var ( HTTPAddr string HTTPPort string ) func runHelloHTTPServer() { httpHello := func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("H
func runHelloHTTPServer() { httpHello := func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("HelloWorld")) } wsConfig, err := websocket.NewConfig("wss://127.0.0.1/websocket", "https://127.0.0.1") common.Must(err) wsServer := websocket.Server{ Config: *wsConfig, Handler: func(conn *websocket.Conn) { conn.Write([]byte("HelloWorld")) }, Handshake: func(wsConfig *websocket.Config, httpRequest *http.Request) error { log.Debug("websocket url", httpRequest.URL, "origin", httpRequest.Header.Get("Origin")) return nil }, } mux := &http.ServeMux{} mux.HandleFunc("/", httpHello) mux.HandleFunc("/websocket", wsServer.ServeHTTP) HTTPAddr = GetTestAddr() _, HTTPPort, _ = net.SplitHostPort(HTTPAddr) server := http.Server{ Addr: HTTPAddr, Handler: mux, } go server.ListenAndServe() time.Sleep(time.Second * 1) // wait for http server fmt.Println("http test server listening on", HTTPAddr) wg.Done() }
633,974
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: text_decode.go path of file: ./repos/comply/vendor/github.com/golang/protobuf/proto the code of the file until where you have to start completion: // Copyright 2010 The Go Authors. All right
func newTextParser(s string) *textParser { p := new(textParser) p.s = s p.line = 1 p.cur.line = 1 return p }
291,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: 1325A.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 ( . "fmt" "io" ) // github.com/EndlessCheng/codeforces-go func CF13
func CF1325A(in io.Reader, out io.Writer) { var T, n int for Fscan(in, &T); T > 0; T-- { Fscan(in, &n) Fprintln(out, 1, n-1) } }
135,721
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: verify_all_generated_files_are_up_to_date.rb path of file: ./repos/gitlabhq/scripts/lib/glfm the code of the file until where you have to start completion: # frozen_string_
def process verify_cmd = "git status --porcelain #{GLFM_OUTPUT_SPEC_PATH} #{ES_OUTPUT_EXAMPLE_SNAPSHOTS_PATH}" verify_cmd_output = run_external_cmd(verify_cmd) unless verify_cmd_output.empty? msg = "ERROR: Cannot run `#{__FILE__}` because `#{verify_cmd}` shows the following uncommitted changes:\n" \ "#{verify_cmd_output}" raise(msg) end
302,960
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: searchAttrValidator_test.go path of file: ./repos/cadence/common/elasticsearch/validator the code of the file until where you have to start completion: // Copyright (c) 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to qvom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, qvETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
func (s *searchAttributesValidatorSuite) TestValidateSearchAttributes() { numOfKeysLimit := 2 sizeOfValueLimit := 5 sizeOfTotalLimit := 20 validator := NewSearchAttributesValidator(log.NewNoop(), dynamicconfig.GetBoolPropertyFn(true), dynamicconfig.GetMapPropertyFn(definition.GetDefaultIndexedKeys()), dynamicconfig.GetIntPropertyFilteredByDomain(numOfKeysLimit), dynamicconfig.GetIntPropertyFilteredByDomain(sizeOfValueLimit), dynamicconfig.GetIntPropertyFilteredByDomain(sizeOfTotalLimit)) domain := "domain" var attr *types.SearchAttributes err := validator.ValidateSearchAttributes(attr, domain) s.Nil(err) fields := map[string][]byte{ "CustomIntField": []byte(`1`), } attr = &types.SearchAttributes{ IndexedFields: fields, } err = validator.ValidateSearchAttributes(attr, domain) s.Nil(err) fields = map[string][]byte{ "CustomIntField": []byte(`1`), "CustomKeywordField": []byte(`"keyword"`), "CustomBoolField": []byte(`true`), } attr.IndexedFields = fields err = validator.ValidateSearchAttributes(attr, domain) s.Equal("number of keys 3 exceed limit", err.Error()) fields = map[string][]byte{ "InvalidKey": []byte(`"1"`), } attr.IndexedFields = fields err = validator.ValidateSearchAttributes(attr, domain) s.Equal(`InvalidKey is not a valid search attribute key`, err.Error()) fields = map[string][]byte{ "CustomStringField": []byte(`"1"`), "CustomBoolField": []byte(`123`), } attr.IndexedFields = fields err = validator.ValidateSearchAttributes(attr, domain) s.Equal(`123 is not a valid search attribute value for key CustomBoolField`, err.Error()) fields = map[string][]byte{ "CustomIntField": []byte(`[1,2]`), } attr.IndexedFields = fields err = validator.ValidateSearchAttributes(attr, domain) s.NoError(err) fields = map[string][]byte{ "StartTime": []byte(`1`), } attr.IndexedFields = fields err = validator.ValidateSearchAttributes(attr, domain) s.Equal(`StartTime is read-only Cadence reservered attribute`, err.Error()) fields = map[string][]byte{ "CustomKeywordField": []byte(`"123456"`), } attr.IndexedFields = fields err = validator.ValidateSearchAttributes(attr, domain) s.Equal(`size limit exceed for key CustomKeywordField`, err.Error()) fields = map[string][]byte{ "CustomKeywordField": []byte(`"123"`), "CustomStringField": []byte(`"12"`), } attr.IndexedFields = fields err = validator.ValidateSearchAttributes(attr, domain) s.Equal(`total size 44 exceed limit`, err.Error()) }
12,766
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: nic.rs path of file: ./repos/heim/heim-net/src/sys/windows the code of the file until where you have to start completion: use heim_common::prelude::*; use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::net::SocketAddrV4; use std::net::SocketAddrV6; use std::ffi::CStr; use widestring::UCStr; use winapi::shared::ifdef::IfOperStatusUp; use winapi::shared::minwindef::ULONG; use winapi::shared::ntdef::NULL; use winapi::shared::winerror::{ERROR_BUFFER_OVERFLOW, NO_ERROR}; use winapi::shared::ws2def::AF_UNSPEC; use winapi::shared::ws2def::SOCKADDR_IN; use wina
fn sockaddr_to_ipv4(sa: SOCKET_ADDRESS) -> Option<Address> { // Check this sockaddr can fit one short and a char[14] // (see https://docs.microsoft.com/en-us/windows/win32/winsock/sockaddr-2) // This should always happen though, this is guaranteed by winapi's interface if (sa.iSockaddrLength as usize) < std::mem::size_of::<SOCKADDR_IN>() { return None; } if sa.lpSockaddr.is_null() { return None; } let arr = unsafe { (*sa.lpSockaddr).sa_data }; let ip4 = Ipv4Addr::new(arr[2] as _, arr[3] as _, arr[4] as _, arr[5] as _); let port = (arr[0] as u16) + (arr[1] as u16) * 0x100; Some(Address::Inet(SocketAddrV4::new(ip4, port))) }
130,393
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: AffineGridGenerator.m path of file: ./repos/Pedestrian_Alignment/matlab/+dagnn the code of the file until where you have to start completion: classdef AffineGridGenerator < dagnn.Layer %DAGNN.AFFINEGRIDGENERATIOR Generate an affine grid for bilinear resampling
function [derInputs, derParams] = backward(obj, inputs, ~, derOutputs) useGPU = isa(derOutputs{1}, 'gpuArray'); dY = derOutputs{1}; nbatch = size(dY,4); % cudnn compatibility: dY = permute(dY, [3,2,1,4]); % create the gradient buffer: dA = zeros([2,3,nbatch], 'single'); if useGPU, dA = gpuArray(dA); end
591,045
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: catalog.go path of file: ./repos/milvus/internal/metastore the code of the file until where you have to start completion: package metastore import ( "context" "github.com/milvus-io/milvus-proto
func (t AlterType) String() string { switch t { case ADD: return "ADD" case DELETE: return "DELETE" case MODIFY: return "MODIFY" } return "" }
14,106
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: excel-compare.rb path of file: ./repos/homebrew-core/Formula/e the code of the file until where you have to start completion: class ExcelCom
def install libexec.install Dir["lib/*"] (bin/"excel_cmp").write <<~EOS #!/bin/bash export JAVA_HOME="${JAVA_HOME:-#{Formula["openjdk"].opt_prefix}}" exec "${JAVA_HOME}/bin/java" -ea -cp "#{libexec}/*" com.ka.spreadsheet.diff.SpreadSheetDiffer "$@" EOS end
694,201
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: product_import_spec.rb path of file: ./repos/openfoodnetwork/spec/system/admin the code of the file until where you have to start completion: # frozen_string_literal: false require 'system_helper' require 'open_food_network/permissions' describe "Product Import" do include AdminHelper include AuthenticationHelper include WebHelper let!(:admin) { create(:admin_user) } let!(:user) { create(:user) } l
def expect_import_completed # The step pages are hidden and shown by AngularJS and we get a false # positive when querying for the content of a hidden step. # # expect(page).to have_content I18n.t('admin.product_import.save_results.final_results') # # Being more explicit seems to work: using_wait_time 60 do expect(page).to have_selector("h5", text: "Import final results") end end
303,808
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main_monolithic.rs path of file: ./repos/Rust-Full-Stack/gRPC/rust/user/src the code of the file until where you have to start completion: // https://docs.rs/postgres/0.15.2/postgres/ // main.rs + models.rs, use it for Rust gRPC tonic blog posts. extern crate postgres; extern crate dotenv; extern crate chrono; use chrono::*; use tonic::{transport::Server, Request, Response, Status}; extern crate uuid; use uuid::Uuid; extern crate console; use console::Style; pub mod user { tonic::include_proto!("user"); } use user::{ server::{Crud, CrudServer}, CreateUserReply, CreateUserRequest, DeleteUserReply, Empty, UpdateUserReply, UpdateUserRequest, UserReply, UserRequest, Users, }; mod db_connection; use crate::db_connection::establish_connection; #[derive(Default)] pub struct User {} // If you want optional values or custom error messages, refer to this. // https://stackoverflow.com/questions/42622015/how-to-define-an-optional-
async fn list_users(&self, request: Request<Empty>) -> Result<Response<Users>, Status> { println!("Got a request: {:#?}", &request); let conn = establish_connection(); // https://docs.rs/postgres/0.15.2/postgres/ // use functional approach? https://docs.rs/postgres/0.15.2/postgres/rows/struct.Rows.html#method.iter let mut v: Vec<UserReply> = Vec::new(); // https://docs.rs/postgres/0.15.2/postgres/struct.Connection.html#method.query for row in &conn.query("SELECT * FROM users", &[]).unwrap() { let date_of_birth: NaiveDate = row.get(3); let user = UserReply { id: row.get(0), first_name: row.get(1), last_name: row.get(2), date_of_birth: date_of_birth.to_string(), }; v.push(user); } // rows.len() // message Users { // repeated UserReply users = 1; // } // (repeated, vec), (users, users) let reply = Users { users: v }; Ok(Response::new(reply)) }
484,513
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: p1494_test.go path of file: ./repos/codeforces-go/misc/luogu the code of the file until where you have to start completion: package main import ( "github.com/EndlessCheng/codeforces-go/main/testutil" "testi
func Test_p1494(t *testing.T) { samples := [][2]string{ { `6 4 1 2 3 3 3 2 2 6 1 3 3 5 1 6`, `2/5 0/1 1/1 4/15`, }, } testutil.AssertEqualStringCase(t, samples, 0, p1494) }
137,418
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/exception/query the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licens
func (p *provider) Init(ctx servicehub.Context) error { if p.Cfg.QuerySource.Cassandra { if p.Cassandra == nil { panic("cassandra provider autowired failed.") } if p.Cassandra != nil { session, err := p.Cassandra.NewSession(&p.Cfg.Cassandra) if err != nil { return fmt.Errorf("fail to create cassandra session: %s", err) } p.Source = &source.CassandraSource{CassandraSession: session} } } if p.Cfg.QuerySource.ElasticSearch { if p.Cfg.EntityGrpcClientMaxRecvBytes != defaultEntityGrpcClientMaxRecvBytes { p.Entity = ctx.Service("erda.oap.entity.EntityService", grpc.MaxCallRecvMsgSize(p.Cfg.EntityGrpcClientMaxRecvBytes)).(entitypb.EntityServiceServer) } p.Source = &source.ElasticsearchSource{Metric: p.Metric, Event: p.Event, Entity: p.Entity} } p.exceptionService = &exceptionService{ p: p, source: p.Source, } if p.Register != nil { pb.RegisterExceptionServiceImp(p.Register, p.exceptionService, apis.Options()) } return nil }
709,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: loopback.go path of file: ./repos/buildkit/vendor/github.com/hanwen/go-fuse/v2/fs the code of the file until where you have to start completion: // Copyright 2019 the Go-FUSE 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 fs import ( "context" "os" "path/filepath" "syscall" "github.com/hanwen/go-fuse/v2/fuse" ) // LoopbackRoot holds the parameters for creating a new loopback // filesystem. Loopback filesystem delegate their operations to an // underlying POSIX file system
func (r *LoopbackRoot) idFromStat(st *syscall.Stat_t) StableAttr { // We compose an inode number by the underlying inode, and // mixing in the device number. In traditional filesystems, // the inode numbers are small. The device numbers are also // small (typically 16 bit). Finally, we mask out the root // device number of the root, so a loopback FS that does not // encompass multiple mounts will reflect the inode numbers of // the underlying filesystem swapped := (uint64(st.Dev) << 32) | (uint64(st.Dev) >> 32) swappedRootDev := (r.Dev << 32) | (r.Dev >> 32) return StableAttr{ Mode: uint32(st.Mode), Gen: 1, // This should work well for traditional backing FSes, // not so much for other go-fuse FS-es Ino: (swapped ^ swappedRootDev) ^ st.Ino, } }
654,070
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: 1188B.go path of file: ./repos/codeforces-go/main/1100-1199 the code of the file until where you have to start completion: package main import ( "bufio" . "fmt" "io" ) // github.com/EndlessCheng/codeforces-go func CF1188B(_r io.Reader, out io.Writer) { in := bufio.NewReader(_r) c := map[int]int{}
func CF1188B(_r io.Reader, out io.Writer) { in := bufio.NewReader(_r) c := map[int]int{} var n int var p, k, v, ans int64 for Fscan(in, &n, &p, &k); n > 0; n-- { Fscan(in, &v) w := int((v*v%p*v%p*v%p - v*k%p + p) % p) ans += int64(c[w]) c[w]++ } Fprint(out, ans) }
134,854
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: zsyscall_plan9_arm.go path of file: ./repos/plumber/vendor/golang.org/x/sys/plan9 the code of the file until where you have to start completion: // go run mksyscall.go -l32 -plan9 -tags plan9,arm syscall_plan9.go // Code generated by the command above; see README.md. DO NOT
func Fstat(fd int, edir []byte) (n int, err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) n = int(r0) if int32(r0) == -1 { err = e1 } return }
459,260
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: not_pwned_validator.rb path of file: ./repos/pwned/lib/pwned the code of the file until where you have to start completion: # frozen_string_literal: true ## # An +ActiveModel+ validator to check passwords a
def validate_each(record, attribute, value) return if value.blank? begin pwned_check = Pwned::Password.new(value, request_options) if pwned_check.pwned_count > threshold record.errors.add(attribute, :not_pwned, **options.merge(count: pwned_check.pwned_count)) end
121,175
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: accounts_client_example_test.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/graphservices/armgraphservices 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. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // DO NOT EDIT. package armgraphservices_test import ( "context" "log" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "
func ExampleAccountsClient_Update() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := armgraphservices.NewClientFactory("<subscription-id>", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewAccountsClient().Update(ctx, "testResourceGroupGRAM", "11111111-aaaa-1111-bbbb-111111111111", armgraphservices.AccountPatchResource{ Tags: map[string]*string{ "tag1": to.Ptr("value1"), "tag2": to.Ptr("value2"), }, }, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res.AccountResource = armgraphservices.AccountResource{ // Name: to.Ptr("11111111-aaaa-1111-bbbb-111111111111"), // Type: to.Ptr("Microsoft.GraphServices/accounts"), // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testResourceGroupGRAM/providers/Microsoft.GraphServices/accounts/11111111-aaaa-1111-bbbb-111111111111"), // Tags: map[string]*string{ // "tag1": to.Ptr("value1"), // "tag2": to.Ptr("value2"), // }, // Properties: &armgraphservices.AccountResourceProperties{ // AppID: to.Ptr("11111111-aaaa-1111-bbbb-111111111111"), // BillingPlanID: to.Ptr("11111111-aaaa-1111-bbbb-111111111111"), // ProvisioningState: to.Ptr(armgraphservices.ProvisioningStateSucceeded), // }, // } }
266,663
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: MUSCL_EulerRes2d_v2.m path of file: ./repos/ApproximateRiemannSolvers/MUSLC_TVD_Genuine2D the code of the file until where you have to start completion: function [res] = MUSCL_EulerRes2d_v2(q,~,dx,dy,N,M,limiter,fluxMethod) % A genuine 2d HLLE Riemnan solver for Euler Equations using a Monotonic % Upstreat Centered Scheme for Conservation Laws (MUSCL). % % e.g. where: limiter='MC'; fluxMethod='HLLE1d'; % % Flux at j+1/2 % % j+1/2 Cell's grid: % | wL| | % | /|wR | 1 2 3 4 N-2 N-1 N % | / |\ | {x=0} |-o-|-o-|-o-|-o-| ... |-o-|-o-|-o-| {x=L} % |/ | \ | 1 2 3 4 N-2 N-1
function [res] = MUSCL_EulerRes2d_v2(q,~,dx,dy,N,M,limiter,fluxMethod) % A genuine 2d HLLE Riemnan solver for Euler Equations using a Monotonic % Upstreat Centered Scheme for Conservation Laws (MUSCL). % % e.g. where: limiter='MC'; fluxMethod='HLLE1d'; % % Flux at j+1/2 % % j+1/2 Cell's grid: % | wL| | % | /|wR | 1 2 3 4 N-2 N-1 N % | / |\ | {x=0} |-o-|-o-|-o-|-o-| ... |-o-|-o-|-o-| {x=L} % |/ | \ | 1 2 3 4 N-2 N-1 % | | \| % | | | NC: Here cells 1 and N are ghost cells % j j+1 faces 1 and N-1, are the real boundary faces. % % q = cat(3, r, r.*u, r.*v, r.*E); % F = cat(3, r.*u, r.*u.^2+p, r.*u.*v, u.*(r.*E+p)); % G = cat(3, r.*v, r.*u.*v, r.*v.^2+p, v.*(r.*E+p)); % % Written by Manuel Diaz, NTU, 05.25.2015. res = zeros(M,N,4); % Normal unitary face vectors: (nx,ny) % normals = {[0,1], [1,0], [0,-1], [-1,0]}; % i.e.: [N, E, S, W] % Build cells cell(M,N).all = M*N; for i = 1:M for j = 1:N cell(i,j).q = [q(i,j,1);q(i,j,2);q(i,j,3);q(i,j,4)]; cell(i,j).qN = zeros(4,1); cell(i,j).qS = zeros(4,1); cell(i,j).qE = zeros(4,1); cell(i,j).qW = zeros(4,1); cell(i,j).res= zeros(4,1); end
305,086
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: subscription_tracking.rb path of file: ./repos/sendgrid-ruby/lib/sendgrid/helpers/mail the code of the file until where you have to start completion: require 'json' module SendGrid class SubscriptionTracking attr_accessor
def to_json(*) { 'enable' => enable, 'text' => text, 'html' => html, 'substitution_tag' => substitution_tag }.delete_if { |_, value| value.to_s.strip == '' } end
49,413
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: secret.go path of file: ./repos/hubble-ui/backend/vendor/k8s.io/client-go/applyconfigurations/core/v1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apache
func Secret(name, namespace string) *SecretApplyConfiguration { b := &SecretApplyConfiguration{} b.WithName(name) b.WithNamespace(namespace) b.WithKind("Secret") b.WithAPIVersion("v1") return b }
379,846
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: safebags.go path of file: ./repos/docker-ce/components/engine/vendor/golang.org/x/crypto/pkcs12 the code of the file until where you have to start completion: // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import ( "crypto/x509" "encoding/asn1" "errors" ) var ( // see https://tools.ietf.org/html/rfc7292#app
func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) { pkinfo := new(encryptedPrivateKeyInfo) if err = unmarshal(asn1Data, pkinfo); err != nil { return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error()) } pkData, err := pbDecrypt(pkinfo, password) if err != nil { return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error()) } ret := new(asn1.RawValue) if err = unmarshal(pkData, ret); err != nil { return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error()) } if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil { return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error()) } return privateKey, nil }
567,032
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: inputstruct.m path of file: ./repos/segment-open/source the code of the file until where you have to start completion: function [res,varargout] = inputstruct(s,tit,text) %INPUTSTRUCT creates a popup input dialog box from a struct % % INPUTSTRUCT(struct_var,title) % % Input is a struct with exploraty names, a title for the dialogbox % and a descriptive text % Output is the modified struct, and optional an ok variable. % % Example % s.FirstString = 'First string';
function [res,varargout] = inputstruct(s,tit,text) %INPUTSTRUCT creates a popup input dialog box from a struct % % INPUTSTRUCT(struct_var,title) % % Input is a struct with exploraty names, a title for the dialogbox % and a descriptive text % Output is the modified struct, and optional an ok variable. % % Example % s.FirstString = 'First string'; % s.DoubleVector = [1 2]; %A double vector % s.TrueOrFalse = true; %A logical % [res,ok] = inputstruct(s,'mytitel') %Brings up dialog box. % % Limitations: % The function behaviours poorly when there a very many fields. In % these cases split it up by the usage of COPYFIELDS. Example % s.A = 1; % s.B = 2; % %etc % s = inputstruct(s,'First parameter set.') % temp = []; % temp.C = 3; % temp.D = 4; % s = copyfields(s,temp); % % The function does only currently handles the following datatype % - double(s) % - chars or string arrays % - logicals %Einar Heiberg 2003-12-04 if nargin==0 error('Expected at least one input argument.'); end
238,322
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: optimNn.m path of file: ./repos/bspm/thirdparty/spm8/toolbox/DARTEL the code of the file until where you have to start completion: function varargout = optimNn(varargin) % Full multigrid matrix solver stuff (zero gradient at boundaries) %_______________________________________________________________________ % % FORMAT v = optimNn('fmg',A, b, param) % v - the solution n1*n2*n3*n4 % A - parameterisation of 2nd derivatives % n1*n2*n3*(n4*(n4+1)/2) % The first n4 volumes are the diagonal elements, which are % followed by the off-diagonals (note that 2nd derivs are% % symmetric). e.g. if n4=3, then the ordering would be % (1,1),(2,2),(3,3),(1,2),(1,3),(2,3)
function varargout = optimNn(varargin) % Full multigrid matrix solver stuff (zero gradient at boundaries) %_______________________________________________________________________ % % FORMAT v = optimNn('fmg',A, b, param) % v - the solution n1*n2*n3*n4 % A - parameterisation of 2nd derivatives % n1*n2*n3*(n4*(n4+1)/2) % The first n4 volumes are the diagonal elements, which are % followed by the off-diagonals (note that 2nd derivs are% % symmetric). e.g. if n4=3, then the ordering would be % (1,1),(2,2),(3,3),(1,2),(1,3),(2,3) % b - parameterisation of first derivatives n1*n2*n3*n4 % param - 6 parameters (settings) % - [1] Regularisation type, can take values of % - 1 Membrane energy % - 2 Bend
521,012
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: secret_key.rs path of file: ./repos/Rocket/core/lib/src/config the code of the file until where you have to start completion: use std::fmt; use cookie::Key; use serde::{de, ser, Deserialize, Serialize}; use crate::request::{Outcome, Request, FromReq
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_zero() { f.write_str("[zero]") } else { match self.provided { true => f.write_str("[provided]"), false => f.write_str("[generated]"), } } }
435,584
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: edit.go path of file: ./repos/gccrs/libgo/go/cmd/go/internal/modcmd the code of the file until where you have to start completion: // Copyright 2018 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. // go mod edit package modcmd import ( "bytes" "context" "encoding/json" "errors" "fmt" "os" "strings" "cmd/go/internal/base" "cmd/go/internal/lockedfile" "cmd/go/internal/modfetch" "cmd/go/internal/modload" "golang.org/x/mod/modfile" "golang.org/x/mod/module" ) var cmdEdit = &base.Command{ UsageLine: "go mod edit [editing flags] [-fmt|-print|-json] [go.mod]", Short: "edit go.mod from tools or scripts", Long: ` Edit provides a command-line interface for editing go.mod, for use primarily by tools or scripts. It reads only go.mod; it does not look up information about the modules involved. By default, edit reads and writes the go.mod file of the main module, but a different target file can be specified after the editing flags. The editing flags specify a sequence of editing operations. The -fmt flag reformats the go.mod file without making other changes. This reformatting is also implied by any other modifications that use or rewrite the go.mod file. The only time this flag is needed is if no other flags are specified, as in 'go mod edit -fmt'. The -module flag changes the module's path (the go.mod file's module line). The -require=path@version and -
func runEdit(ctx context.Context, cmd *base.Command, args []string) { anyFlags := *editModule != "" || *editGo != "" || *editJSON || *editPrint || *editFmt || len(edits) > 0 if !anyFlags { base.Fatalf("go: no flags specified (see 'go help mod edit').") } if *editJSON && *editPrint { base.Fatalf("go: cannot use both -json and -print") } if len(args) > 1 { base.Fatalf("go: too many arguments") } var gomod string if len(args) == 1 { gomod = args[0] } else { gomod = modload.ModFilePath() } if *editModule != "" { if err := module.CheckImportPath(*editModule); err != nil { base.Fatalf("go: invalid -module: %v", err) } } if *editGo != "" { if !modfile.GoVersionRE.MatchString(*editGo) { base.Fatalf(`go mod: invalid -go option; expecting something like "-go %s"`, modload.LatestGoVersion()) } } data, err := lockedfile.Read(gomod) if err != nil { base.Fatalf("go: %v", err) } modFile, err := modfile.Parse(gomod, data, nil) if err != nil { base.Fatalf("go: errors parsing %s:\n%s", base.ShortPath(gomod), err) } if *editModule != "" { modFile.AddModuleStmt(*editModule) } if *editGo != "" { if err := modFile.AddGoStmt(*editGo); err != nil { base.Fatalf("go: internal error: %v", err) } } if len(edits) > 0 { for _, edit := range edits { edit(modFile) } } modFile.SortBlocks() modFile.Cleanup() // clean file after edits if *editJSON { editPrintJSON(modFile) return } out, err := modFile.Format() if err != nil { base.Fatalf("go: %v", err) } if *editPrint { os.Stdout.Write(out) return } // Make a best-effort attempt to acquire the side lock, only to exclude // previous versions of the 'go' command from making simultaneous edits. if unlock, err := modfetch.SideLock(); err == nil { defer unlock() } err = lockedfile.Transform(gomod, func(lockedData []byte) ([]byte, error) { if !bytes.Equal(lockedData, data) { return nil, errors.New("go.mod changed during editing; not overwriting") } return out, nil }) if err != nil { base.Fatalf("go: %v", err) } }
748,290
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: pipe.go path of file: ./repos/sealer/vendor/golang.org/x/net/http2 the code of the file until where you have to start completion: // Copyright 2014 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 http2 import ( "errors" "
func (p *pipe) Done() <-chan struct{} { p.mu.Lock() defer p.mu.Unlock() if p.donec == nil { p.donec = make(chan struct{}) if p.err != nil || p.breakErr != nil { // Already hit an error. p.closeDoneLocked() } } return p.donec }
725,059
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.go path of file: ./repos/google-cloud-go/internal/generated/snippets/aiplatform/apiv1/EndpointClient/GetIamPolicy the code of the file until where you have to start completion: // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go_gapic. DO NOT EDIT. // [START aiplatform_v1_generated_EndpointService_GetIamPolicy_sync] package main import ( "context" aiplatform "cloud.g
func main() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in: // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options c, err := aiplatform.NewEndpointClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/cloud.google.com/go/iam/apiv1/iampb#GetIamPolicyRequest. } resp, err := c.GetIamPolicy(ctx, req) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp }
276,402
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: mt_utils_windows.go path of file: ./repos/kubernetes/test/images/agnhost/mounttest the code of the file until where you have to start completion: //go:build windows // +build windows /* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is dist
func getFilePerm(path string) (os.FileMode, error) { var ( out bytes.Buffer errOut bytes.Buffer ) // NOTE(claudiub): Symlinks have different permissions which might not match the target's. // We want to evaluate the permissions of the target's not the symlink's. info, err := os.Lstat(path) if err == nil && info.Mode()&os.ModeSymlink != 0 { evaluated, err := filepath.EvalSymlinks(path) if err != nil { return 0, err } path = evaluated } cmd := exec.Command("powershell.exe", "-NonInteractive", "./filePermissions.ps1", "-FileName", path) cmd.Stdout = &out cmd.Stderr = &errOut err = cmd.Run() if err != nil { fmt.Printf("error from PowerShell Script: %v, %v\n", err, errOut.String()) return 0, err } output := strings.TrimSpace(out.String()) val, err := strconv.ParseInt(output, 8, 32) if err != nil { fmt.Printf("error parsing string '%s' as int: %v\n", output, err) return 0, err } return os.FileMode(val), nil }
351,593
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: consist.m path of file: ./repos/pcm/matlab/lib/netlab3_3 the code of the file until where you have to start completion: function errstring = consist(model, type, inputs, outputs) %CONSIST Check that arguments are consistent. % % Description % % ERRSTRING = CONSIST(NET, TYPE, INPUTS) takes a network data structure % NET together with a string TYPE containing the correct network type, % a matrix INPUTS of input vectors and checks that the data structure % is consistent with the other arguments. An empty string is returned % if there is no error, otherwise the string contains the relevant % error message. If the TYPE string is empty, then any type of network % is allowed. % % ERRSTRING = CONSIST(NET, TYPE) takes a network data structure NET % together with a string TYPE containing the correct network type, and % checks that the two types match. % % ERRSTRING = CONSIST(NET, TYPE, INPUTS, OUTPUTS) also checks that the % network has the correct number of outputs, and that the number of % patterns in the INPUTS and OUTPUTS is the same. The fields in NET % that are used are % type % nin % nout %
function errstring = consist(model, type, inputs, outputs) %CONSIST Check that arguments are consistent. % % Description % % ERRSTRING = CONSIST(NET, TYPE, INPUTS) takes a network data structure % NET together with a string TYPE containing the correct network type, % a matrix INPUTS of input vectors and checks that the data structure % is consistent with the other arguments. An empty string is returned % if there is no error, otherwise the string contains the relevant % error message. If the TYPE string is empty, then any type of network % is allowed. % % ERRSTRING = CONSIST(NET, TYPE) takes a network data structure NET % together with a string TYPE containing the correct network type, and % checks that the two types match. % % ERRSTRING = CONSIST(NET, TYPE, INPUTS, OUTPUTS) also checks that the % network has the correct number of outputs, and that the number of % patterns in the INPUTS and OUTPUTS is the same. The fields in NET % that are used are % type % nin % nout % % See also % MLPFWD % % Copyright (c) Ian T Nabney (1996-2001) % Assume that all is OK as default errstring = ''; % If type string is not empty if ~isempty(type) % First check that model has type field if ~isfield(model, 'type') errstring = 'Data structure does not contain type field'; return end
538,063
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: unit_assignment_test.go path of file: ./repos/juju/state the code of the file until where you have to start completion: // Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package state_test import ( "github.com/juju/errors" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "github.com/juju/juju/core
func (s *UnitAssignmentSuite) TestAssignUnitCleanMachineUpgradeSeriesLockError(c *gc.C) { s.addLockedMachine(c, true) charm := s.AddTestingCharm(c, "dummy") app, err := s.State.AddApplication(state.AddApplicationArgs{ Name: "dummy", Charm: charm, CharmOrigin: &state.CharmOrigin{Platform: &state.Platform{ OS: "ubuntu", Channel: "22.04/stable", }}, NumUnits: 1, }) c.Assert(err, jc.ErrorIsNil) units, err := app.AllUnits() c.Assert(err, jc.ErrorIsNil) c.Assert(units, gc.HasLen, 1) unit := units[0] _, err = unit.AssignToCleanEmptyMachine() c.Assert(err, gc.ErrorMatches, eligibleMachinesInUse) }
612,145
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: app_package_integration_type.rb path of file: ./repos/chaskiq/app/graphql/types the code of the file until where you have to start completion: # frozen_string_literal: true module Types class AppP
def call_hook(kind:, ctx:) object.call_hook({ kind: kind, ctx: ctx.merge!( lang: I18n.locale, current_user: current_user ) }) end
470,806
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: ext_info.go path of file: ./repos/gotosocial/vendor/github.com/cilium/ebpf/btf the code of the file until where you have to start completion: package btf import ( "bytes" "encoding/binary" "errors" "fmt" "io" "math" "sort" "github.com/cilium/ebpf/asm" "github.com/cilium/ebpf/i
func MarshalExtInfos(insns asm.Instructions, typeID func(Type) (TypeID, error)) (funcInfos, lineInfos []byte, _ error) { iter := insns.Iterate() var fiBuf, liBuf bytes.Buffer for iter.Next() { if fn := FuncMetadata(iter.Ins); fn != nil { fi := &funcInfo{ fn: fn, offset: iter.Offset, } if err := fi.marshal(&fiBuf, typeID); err != nil { return nil, nil, fmt.Errorf("write func info: %w", err) } } if line, ok := iter.Ins.Source().(*Line); ok { li := &lineInfo{ line: line, offset: iter.Offset, } if err := li.marshal(&liBuf); err != nil { return nil, nil, fmt.Errorf("write line info: %w", err) } } } return fiBuf.Bytes(), liBuf.Bytes(), nil }
24,509
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: getfile.go path of file: ./repos/gotosocial/internal/processing/media the code of the file until where you have to start completion: // GoToSocial // Copyright (C) GoToSocial Authors admin@gotosocial.org // SPDX-License-Identifier: AGPL-3.0-or-later // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package media import ( "context" "fmt" "io" "net/url" "strings" "time" apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model" "github.com/superseriousbusiness/gotosocial/internal/gtscontext" "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" "github.com/superseriousbusiness/gotosocial/internal/media" "github.com/superseriousbusiness/gotosocial/internal/storage" "github.com/superseriousbusiness/gotosocial/internal/uris" ) // GetFile retrieves a file from storage and streams it back // to the caller via an io.reader embedded in *apimodel.Content. func (p *Processor) GetFile( ctx context.Context, requestingAccount *gtsmodel.Account, form *apimodel.GetContentRequestForm, ) (*apimodel.Content, gtserror.WithCode) { // parse the form fields mediaSize, err := parseSize(form.MediaSize) if err != nil { return nil, gtserror.NewErrorNotFound(fmt.Errorf("media size %s not valid", form.MediaSize)) } mediaType, err := parseType(form.MediaType) if err != nil { return nil, gtserror.NewErrorNotFound(fmt.Errorf("media type %s not valid", form.MediaType)) } spl := strings.Split(form.FileName, ".") if len(spl) != 2 || spl[0] == "" || spl[1] == "" { return nil, gtserror.NewErrorNotFound(fmt.Errorf("file name %s not parseable", form.FileName)) } wantedMediaID := spl[0] owningAccountID := form.AccountID // get the account that owns the media and make sure it's not suspended owningAccount, err := p.state.DB.GetAccountByID(ctx, owningAccountID) if err != nil { return nil, gtserror.NewErrorNotFound(fmt.Errorf("account with id %s could not be selected from the db: %s", owningAccountID, err)) } if !owningAccount.SuspendedAt.IsZero() { return nil, gtserror.NewErrorNotFound(fmt.Errorf("account with id %s is suspended", owningAccountID)) } // make sure the requesting account and the media account don't block each other if requestingAccount != nil { blocked, err := p.state.DB.IsEitherBlocked(ctx, requestingAccount.ID, owningAccountID) if err != nil { return nil, gtserror.NewErrorNotFound(fmt.Errorf("block status could not be established between accounts %s and %s: %s", owningAccountID, requestingAccount.ID, err)) } if blocked { return nil, gtserror.NewErrorNotFound(fmt.Errorf("block exists between accounts %s and %s", owningAccountID, requestingAccount.ID)) } } // the way we store emojis is a little different from the way we store other attachments, // so we need to take different steps depending on the media type being requested switch mediaType { case media.TypeEmoji: return p.getEmojiContent(ctx, wantedMediaID, owningAccountID, mediaSize) case media.TypeAttachment, media.TypeHeader, media.TypeAvatar: return p.getAttachmentContent(ctx, requ
func (p *Processor) getAttachmentContent(ctx context.Context, requestingAccount *gtsmodel.Account, wantedMediaID string, owningAccountID string, mediaSize media.Size) (*apimodel.Content, gtserror.WithCode) { // retrieve attachment from the database and do basic checks on it a, err := p.state.DB.GetAttachmentByID(ctx, wantedMediaID) if err != nil { err = gtserror.Newf("attachment %s could not be taken from the db: %w", wantedMediaID, err) return nil, gtserror.NewErrorNotFound(err) } if a.AccountID != owningAccountID { err = gtserror.Newf("attachment %s is not owned by %s", wantedMediaID, owningAccountID) return nil, gtserror.NewErrorNotFound(err) } // If this is an "Unknown" file type, ie., one we // tried to process and couldn't, or one we refused // to process because it wasn't supported, then we // can skip a lot of steps here by simply forwarding // the request to the remote URL. if a.Type == gtsmodel.FileTypeUnknown { remoteURL, err := url.Parse(a.RemoteURL) if err != nil { err = gtserror.Newf("error parsing remote URL of 'Unknown'-type attachment for redirection: %w", err) return nil, gtserror.NewErrorInternalError(err) } url := &storage.PresignedURL{ URL: remoteURL, // We might manage to cache the media // at some point, so set a low-ish expiry. Expiry: time.Now().Add(2 * time.Hour), } return &apimodel.Content{URL: url}, nil } if !*a.Cached { // if we don't have it cached, then we can assume two things: // 1. this is remote media, since local media should never be uncached // 2. we need to fetch it again using a transport and the media manager remoteMediaIRI, err := url.Parse(a.RemoteURL) if err != nil { return nil, gtserror.NewErrorNotFound(fmt.Errorf("error parsing remote media iri %s: %w", a.RemoteURL, err)) } // use an empty string as requestingUsername to use the instance account, unless the request for this // media has been http signed, then use the requesting account to make the request to remote server var requestingUsername string if requestingAccount != nil { requestingUsername = requestingAccount.Username } // Pour one out for tobi's original streamed recache // (streaming data both to the client and storage). // Gone and forever missed <3 // // [ // the reason it was removed was because a slow // client connection could hold open a storage // recache operation -> holding open a media worker. // ] dataFn := func(ctx context.Context) (io.ReadCloser, int64, error) { t, err := p.transportController.NewTransportForUsername(ctx, requestingUsername) if err != nil { return nil, 0, err } return t.DereferenceMedia(gtscontext.SetFastFail(ctx), remoteMediaIRI) } // Start recaching this media with the prepared data function. processingMedia, err := p.mediaManager.PreProcessMediaRecache(ctx, dataFn, wantedMediaID) if err != nil { return nil, gtserror.NewErrorNotFound(fmt.Errorf("error recaching media: %w", err)) } // Load attachment and block until complete a, err = processingMedia.LoadAttachment(ctx) if err != nil { return nil, gtserror.NewErrorNotFound(fmt.Errorf("error loading recached attachment: %w", err)) } } var ( storagePath string attachmentContent = &apimodel.Content{ ContentUpdated: a.UpdatedAt, } ) // get file information from the attachment depending on the requested media size switch mediaSize { case media.SizeOriginal: attachmentContent.ContentType = a.File.ContentType attachmentContent.ContentLength = int64(a.File.FileSize) storagePath = a.File.Path case media.SizeSmall: attachmentContent.ContentType = a.Thumbnail.ContentType attachmentContent.ContentLength = int64(a.Thumbnail.FileSize) storagePath = a.Thumbnail.Path default: return nil, gtserror.NewErrorNotFound(fmt.Errorf("media size %s not recognized for attachment", mediaSize)) } // ... so now we can safely return it return p.retrieveFromStorage(ctx, storagePath, attachmentContent) }
23,448
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_UpdateSlotType.go path of file: ./repos/aws-sdk-go-v2/service/lexmodelsv2 the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package lexmodelsv2 import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/service/lexmodelsv2/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "time" ) // Updates the configuration of an existing slot type. func (c *Client) UpdateSlotType(ctx context.Context, params *UpdateSlotTypeInput, optFns ...func(*Options)) (*UpdateSlotTypeOutput, error) { if params == nil { params = &UpdateSlotTypeInput{} } result, metadata, err := c.invokeOperation(ctx, "UpdateSlotType", params, optFns, c.addOperationUpdateSlotTypeMiddlewares) if err != nil { return nil, err } out := result.(*UpdateSlotTypeOutput) out.ResultMetadata = metadata return out, nil } type UpdateSlotTypeInput struct { // The identifier of the bot that contains the slot type. // // This member is required. BotId *string // The version of the bot that contains the slot type. Must be DRAFT . // // This member is required.
func (c *Client) addOperationUpdateSlotTypeMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsRestjson1_serializeOpUpdateSlotType{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpUpdateSlotType{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateSlotType"); err != nil { return fmt.Errorf("add protocol finalizers: %v", err) } if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = addClientRequestID(stack); err != nil { return err } if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addComputePayloadSHA256(stack); err != nil { return err } if err = addRetry(stack, options); err != nil { return err } if err = addRawResponseToMetadata(stack); err != nil { return err } if err = addRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { return err } if err = addOpUpdateSlotTypeValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateSlotType(options.Region), middleware.Before); err != nil { return err } if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } if err = addDisableHTTPSMiddleware(stack, options); err != nil { return err } return nil }
222,544
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: stackframe.go path of file: ./repos/lazydocker/vendor/github.com/go-errors/errors the code of the file until where you have to start completion: package errors import ( "bufio" "bytes" "fmt" "os" "runtime" "strings" ) // A StackFrame contains all necessary information ab
func (frame *StackFrame) String() string { str := fmt.Sprintf("%s:%d (0x%x)\n", frame.File, frame.LineNumber, frame.ProgramCounter) source, err := frame.sourceLine() if err != nil { return str } return str + fmt.Sprintf("\t%s: %s\n", frame.Name, source) }
584,685
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: constants.go path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/healthbot/armhealthbot the code of the file until where you have to start completion: //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corp
func PossibleResourceIdentityTypeValues() []ResourceIdentityType { return []ResourceIdentityType{ ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned, } }
265,086
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: summary_test.go path of file: ./repos/kubernetes/staging/src/k8s.io/component-base/metrics the code of the file until where you have to start completion: /* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software 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 metrics import ( "testing" "github.com/blang/semver/v4" "github.com/stretchr/testify/assert" apimachineryversion "k8s.io/apimachinery/pkg/version" ) func TestSummary(t *testing.T) { v115 := semver.MustParse("1.15.0") var tests = []struct { desc string *SummaryOpts registryVersion *semver.Version expectedMetricCount int expectedHelp string }{ { desc: "Test non deprecated", SummaryOpts: &SummaryOpts{ Namespace: "namespace", Name: "metric_test_name", Subsystem: "subsystem", Help: "summary help message", StabilityLevel: ALPHA, }, registryVersion: &v115, expectedMetricCount: 1, expectedHelp: "[ALPHA] summary help message", }, { desc: "Test deprecated", SummaryOpts: &SummaryOpts{ Namespace: "namespace", Name: "metric_test_name", Subsystem: "subsystem", Help: "summary help message", DeprecatedVersion: "1.15.0", StabilityLevel: ALPHA, }, registryVersion: &v115, expectedMetricCount: 1, expectedHelp: "[ALPHA] (Deprecated since 1.15.0) summary help message", }, { desc: "Test hidden", SummaryOpts: &SummaryOpts{
func TestSummaryVec(t *testing.T) { v115 := semver.MustParse("1.15.0") var tests = []struct { desc string *SummaryOpts labels []string registryVersion *semver.Version expectedMetricCount int expectedHelp string }{ { desc: "Test non deprecated", SummaryOpts: &SummaryOpts{ Namespace: "namespace", Name: "metric_test_name", Subsystem: "subsystem", Help: "summary help message", }, labels: []string{"label_a", "label_b"}, registryVersion: &v115, expectedMetricCount: 1, expectedHelp: "[ALPHA] summary help message", }, { desc: "Test deprecated", SummaryOpts: &SummaryOpts{ Namespace: "namespace", Name: "metric_test_name", Subsystem: "subsystem", Help: "summary help message", DeprecatedVersion: "1.15.0", }, labels: []string{"label_a", "label_b"}, registryVersion: &v115, expectedMetricCount: 1, expectedHelp: "[ALPHA] (Deprecated since 1.15.0) summary help message", }, { desc: "Test hidden", SummaryOpts: &SummaryOpts{ Namespace: "namespace", Name: "metric_test_name", Subsystem: "subsystem", Help: "summary help message", DeprecatedVersion: "1.14.0", }, labels: []string{"label_a", "label_b"}, registryVersion: &v115, expectedMetricCount: 0, expectedHelp: "summary help message", }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { registry := newKubeRegistry(apimachineryversion.Info{ Major: "1", Minor: "15", GitVersion: "v1.15.0-alpha-1.12345", }) c := NewSummaryVec(test.SummaryOpts, test.labels) registry.MustRegister(c) c.WithLabelValues("1", "2").Observe(1.0) ms, err := registry.Gather() assert.Equalf(t, test.expectedMetricCount, len(ms), "Got %v metrics, Want: %v metrics", len(ms), test.expectedMetricCount) assert.Nil(t, err, "Gather failed %v", err) for _, metric := range ms { assert.Equalf(t, test.expectedHelp, metric.GetHelp(), "Got %s as help message, want %s", metric.GetHelp(), test.expectedHelp) } // let's increment the counter and verify that the metric still works c.WithLabelValues("1", "3").Observe(1.0) c.WithLabelValues("2", "3").Observe(1.0) ms, err = registry.Gather() assert.Nil(t, err, "Gather failed %v", err) for _, mf := range ms { assert.Equalf(t, 3, len(mf.GetMetric()), "Got %v metrics, wanted 2 as the count", len(mf.GetMetric())) for _, m := range mf.GetMetric() { assert.Equalf(t, uint64(1), m.GetSummary().GetSampleCount(), "Got %v metrics, wanted 1 as the summary sample count", m.GetSummary().GetSampleCount()) } } }) } }
356,216
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: create_generated_template.rs path of file: ./repos/aws-sdk-rust/sdk/cloudformation/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 `CreateGeneratedTemplate`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct CreateGeneratedTemplate; impl CreateGeneratedTemplate { /// Creates a new `CreateGeneratedTemplate` pub fn new() -> Self { Self } pub(crate) async fn orchestrate( runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins, input: crate::operation::create_generated_template::CreateGeneratedTemplateInput, ) -> ::std::result::Result< crate::operation::create_generated_template::CreateGeneratedTemplateOutput, ::aws_smithy_runtime_api::client::result::SdkError< crate
fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> { let mut cfg = ::aws_smithy_types::config_bag::Layer::new("CreateGeneratedTemplate"); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new( CreateGeneratedTemplateRequestSerializer, )); cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new( CreateGeneratedTemplateResponseDeserializer, )); cfg.store_put(::aws_smithy_runtime_api::client::auth::AuthSchemeOptionResolverParams::new( ::aws_smithy_runtime_api::client::auth::static_resolver::StaticAuthSchemeOptionResolverParams::new(), )); cfg.store_put(::aws_smithy_runtime_api::client::orchestrator::Metadata::new( "CreateGeneratedTemplate", "cloudformation", )); let mut signing_options = ::aws_runtime::auth::SigningOptions::default(); signing_options.double_uri_encode = true; signing_options.content_sha256_header = false; signing_options.normalize_uri_path = true; signing_options.payload_override = None; cfg.store_put(::aws_runtime::auth::SigV4OperationSigningConfig { signing_options, ..::std::default::Default::default() }); ::std::option::Option::Some(cfg.freeze()) }
788,234
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: fixture.go path of file: ./repos/docker-ce/components/cli/vendor/k8s.io/client-go/testing the code of the file until where you have to start completion: /* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
func (t *tracker) add(gvr schema.GroupVersionResource, obj runtime.Object, ns string, replaceExisting bool) error { t.lock.Lock() defer t.lock.Unlock() gr := gvr.GroupResource() // To avoid the object from being accidentally modified by caller // after it's been added to the tracker, we always store the deep // copy. obj = obj.DeepCopyObject() newMeta, err := meta.Accessor(obj) if err != nil { return err } // Propagate namespace to the new object if hasn't already been set. if len(newMeta.GetNamespace()) == 0 { newMeta.SetNamespace(ns) } if ns != newMeta.GetNamespace() { msg := fmt.Sprintf("request namespace does not match object namespace, request: %q object: %q", ns, newMeta.GetNamespace()) return errors.NewBadRequest(msg) } for i, existingObj := range t.objects[gvr] { oldMeta, err := meta.Accessor(existingObj) if err != nil { return err } if oldMeta.GetNamespace() == newMeta.GetNamespace() && oldMeta.GetName() == newMeta.GetName() { if replaceExisting { for _, w := range t.getWatches(gvr, ns) { w.Modify(obj) } t.objects[gvr][i] = obj return nil } return errors.NewAlreadyExists(gr, newMeta.GetName()) } } if replaceExisting { // Tried to update but no matching object was found. return errors.NewNotFound(gr, newMeta.GetName()) } t.objects[gvr] = append(t.objects[gvr], obj) for _, w := range t.getWatches(gvr, ns) { w.Add(obj) } return nil }
569,390
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_mock_receiver.go path of file: ./repos/chainlink/core/internal/cltest the code of the file until where you have to start completion: package cltest import ( "errors" "reflect" "testing" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" ) // funcSigLength is the length of the function signa
func (receiver contractMockReceiver) MockRevertResponse(funcName string) *mock.Call { funcSig := hexutil.Encode(receiver.abi.Methods[funcName].ID) if len(funcSig) != funcSigLength { receiver.t.Fatalf("Unable to find Registry contract function with name %s", funcName) } return receiver.ethMock. On( "CallContract", mock.Anything, mock.MatchedBy(func(callArgs ethereum.CallMsg) bool { return *callArgs.To == receiver.address && hexutil.Encode(callArgs.Data)[0:funcSigLength] == funcSig }), mock.Anything). Return(nil, errors.New("revert")) }
491,955
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mod.rs path of file: ./repos/meilisearch/milli/src/search/new/matches the code of the file until where you have to start completion: use std::borrow::Cow; use charabia::{SeparatorKind, Token, Tokenizer}; pub use matching_words::MatchingWords; use matching_words::{MatchType, PartialMatch, WordId}; use serde::Serialize; pub mod matching
pub fn build<'t>(&'m self, text: &'t str) -> Matcher<'t, 'm> { let crop_marker = match &self.crop_marker { Some(marker) => marker.as_str(), None => DEFAULT_CROP_MARKER, }; let highlight_prefix = match &self.highlight_prefix { Some(marker) => marker.as_str(), None => DEFAULT_HIGHLIGHT_PREFIX, }; let highlight_suffix = match &self.highlight_suffix { Some(marker) => marker.as_str(), None => DEFAULT_HIGHLIGHT_SUFFIX, }; Matcher { text, matching_words: &self.matching_words, tokenizer: &self.tokenizer, crop_marker, highlight_prefix, highlight_suffix, matches: None, } }
540,347
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: quantified.rb path of file: ./repos/ekylibre/lib/procedo/engine/intervention the code of the file until where you have to start completion: module Procedo module Engine class Intervention class Quantified < Pr
def quantity_handler=(handler) rh = reference.handler(handler) raise 'Invalid handler: ' + handler.inspect unless rh unless usable_handler?(rh) rh = reference.handlers.detect { |h| usable_handler?(h) } handler = rh.name.to_s if rh end
628,763
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: endpoints.go path of file: ./repos/aws-sdk-go-v2/service/mediaconvert/internal/endpoints the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package endpoi
func transformToSharedOptions(options Options) endpoints.Options { return endpoints.Options{ Logger: options.Logger, LogDeprecated: options.LogDeprecated, ResolvedRegion: options.ResolvedRegion, DisableHTTPS: options.DisableHTTPS, UseDualStackEndpoint: options.UseDualStackEndpoint, UseFIPSEndpoint: options.UseFIPSEndpoint, } }
224,826
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: storage.go path of file: ./repos/docker-ce/components/engine/vendor/github.com/docker/swarmkit/manager/state/raft the code of the file until where you have to start completion: package raft import ( "context" "fmt" "github.com/coreos/etcd/raft" "github.com/coreos/etcd/raft/raftpb" "github.com/docker/go-metrics" "github.com/docker/swarmkit/api" "
func (n *Node) triggerSnapshot(ctx context.Context, raftConfig api.RaftConfig) { snapshot := api.Snapshot{Version: api.Snapshot_V0} for _, member := range n.cluster.Members() { snapshot.Membership.Members = append(snapshot.Membership.Members, &api.RaftMember{ NodeID: member.NodeID, RaftID: member.RaftID, Addr: member.Addr, }) } snapshot.Membership.Removed = n.cluster.Removed() viewStarted := make(chan struct{}) n.asyncTasks.Add(1) n.snapshotInProgress = make(chan raftpb.SnapshotMetadata, 1) // buffered in case Shutdown is called during the snapshot go func(appliedIndex uint64, snapshotMeta raftpb.SnapshotMetadata) { // Deferred latency capture. defer metrics.StartTimer(snapshotLatencyTimer)() defer func() { n.asyncTasks.Done() n.snapshotInProgress <- snapshotMeta }() var err error n.memoryStore.View(func(tx store.ReadTx) { close(viewStarted) var storeSnapshot *api.StoreSnapshot storeSnapshot, err = n.memoryStore.Save(tx) snapshot.Store = *storeSnapshot }) if err != nil { log.G(ctx).WithError(err).Error("failed to read snapshot from store") return } d, err := snapshot.Marshal() if err != nil { log.G(ctx).WithError(err).Error("failed to marshal snapshot") return } snap, err := n.raftStore.CreateSnapshot(appliedIndex, &n.confState, d) if err == nil { if err := n.raftLogger.SaveSnapshot(snap); err != nil { log.G(ctx).WithError(err).Error("failed to save snapshot") return } snapshotMeta = snap.Metadata if appliedIndex > raftConfig.LogEntriesForSlowFollowers { err := n.raftStore.Compact(appliedIndex - raftConfig.LogEntriesForSlowFollowers) if err != nil && err != raft.ErrCompacted { log.G(ctx).WithError(err).Error("failed to compact snapshot") } } } else if err != raft.ErrSnapOutOfDate { log.G(ctx).WithError(err).Error("failed to create snapshot") } }(n.appliedIndex, n.snapshotMeta) // Wait for the goroutine to establish a read transaction, to make // sure it sees the state as of this moment. <-viewStarted }
566,052