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: status_test.go
path of file: ./repos/sharingan/grpc-server/v1.33.2/status
the code of the file until where you have to start completion: /*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance
| func (s) TestFromErrorImplementsInterface(t *testing.T) {
code, message := codes.Internal, "test description"
details := []*apb.Any{{
TypeUrl: "testUrl",
Value: []byte("testValue"),
}}
err := customError{
Code: code,
Message: message,
Details: details,
}
s, ok := FromError(err)
if !ok || s.Code() != code || s.Message() != message || s.Err() == nil {
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
}
pd := s.Proto().GetDetails()
if len(pd) != 1 || !proto.Equal(pd[0], details[0]) {
t.Fatalf("s.Proto.GetDetails() = %v; want <Details()=%s>", pd, details)
}
} | 87,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: api_op_DeleteResourcePolicy.go
path of file: ./repos/aws-sdk-go-v2/service/ssm
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package ssm
import (
"context"
"fmt"
awsmiddleware "gith
| func newServiceMetadataMiddleware_opDeleteResourcePolicy(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
OperationName: "DeleteResourcePolicy",
}
} | 224,527 |
You are an expert in writing code in many different languages. Your goal is 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/iottwinmaker/src/operation/update_entity
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,
}
} | 809,661 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: deserializers.go
path of file: ./repos/aws-sdk-go-v2/service/route53domains
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package route53domains
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws/protocol/restjson"
"github.com/aws/aws-sdk-go-v2/service/route53domains/types"
smithy "github.com/aws/smithy-go"
smithyio "github.com/aws/smithy-go/io"
"github.com/aws/smithy-go/middleware"
"github.com/aws/smithy-go/ptr"
smithytime "github.com/aws/smithy-go/time"
smithyhttp "github.com/aws/smithy-go/transport/http"
"io"
"io/ioutil"
"math"
"strings"
)
type awsAwsjson11_deserializeOpAcceptDomainTransferFromAnotherAwsAccount struct {
}
func (*awsAwsjson11_deserializeOpAcceptDomainTr
| func awsAwsjson11_deserializeOpErrorEnableDomainAutoRenew(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
headerCode := response.Header.Get("X-Amzn-ErrorType")
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
bodyInfo, err := getProtocolErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if typ, ok := resolveProtocolErrorType(headerCode, bodyInfo); ok {
errorCode = restjson.SanitizeErrorCode(typ)
}
if len(bodyInfo.Message) != 0 {
errorMessage = bodyInfo.Message
}
switch {
case strings.EqualFold("InvalidInput", errorCode):
return awsAwsjson11_deserializeErrorInvalidInput(response, errorBody)
case strings.EqualFold("TLDRulesViolation", errorCode):
return awsAwsjson11_deserializeErrorTLDRulesViolation(response, errorBody)
case strings.EqualFold("UnsupportedTLD", errorCode):
return awsAwsjson11_deserializeErrorUnsupportedTLD(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
} | 235,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: no_data.go
path of file: ./repos/tegola/vendor/github.com/jackc/pgproto3/v2
the code of the file until where you have to start completion: package pgproto3
import (
"encoding/json"
)
type NoData struct{}
// Backend identifies thi
| func (src NoData) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string
}{
Type: "NoData",
})
} | 95,294 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: get_firewall_rule_group_policy.rs
path of file: ./repos/aws-sdk-rust/sdk/route53resolver/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
| pub fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata {
match self {
Self::AccessDeniedException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),
Self::InternalServiceErrorException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),
Self::ResourceNotFoundException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),
Self::ThrottlingException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),
Self::ValidationException(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),
Self::Unhandled(e) => &e.meta,
}
} | 766,654 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: tetraplets.rs
path of file: ./repos/nox/crates/nox-tests/tests
the code of the file until where you have to start completion: /*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#[macro_use]
extern crate fstrings;
use fstrings::f;
use maplit::hashmap;
use serde_json::json;
use connected_client::ConnectedClient;
use created_swarm::make_swarms;
use fluence_app_service::SecurityTetraplet;
use service_modules::load_module;
use test_utils::create_service;
use eyre::WrapErr;
#[tokio::test]
async fn test_tetraplets() {
let swarms = make_swarms(1).await;
let mut client = ConnectedClient::connect_to(swarms[0].multiaddr.clone())
.await
.wrap_err("connect client")
.unwrap();
let tetraplets_service = create_service(
&mut client,
"tetraplets",
load_module("tests/tetraplets/artifacts", "tetraplets").expect("load module"),
)
.await;
let script = f!(r#"
(seq
(seq
(seq
(seq
(ap "test" ap_literal)
(seq
(call host ("op" "identity") ["test"] result)
(ap result ap_result)
)
)
(seq
(seq
(call host (service_id "get_tetraplets") [ap_literal] ap_literal_tetraplets)
(call host (service_id "get_tetraplets") [result] first_tetraplets)
)
(call host (service_id "get_tetraplets") [ap_result] ap_first_tetraplets)
)
)
| async fn test_tetraplets() {
let swarms = make_swarms(1).await;
let mut client = ConnectedClient::connect_to(swarms[0].multiaddr.clone())
.await
.wrap_err("connect client")
.unwrap();
let tetraplets_service = create_service(
&mut client,
"tetraplets",
load_module("tests/tetraplets/artifacts", "tetraplets").expect("load module"),
)
.await;
let script = f!(r#"
(seq
(seq
(seq
(seq
(ap "test" ap_literal)
(seq
(call host ("op" "identity") ["test"] result)
(ap result ap_result)
)
)
(seq
(seq
(call host (service_id "get_tetraplets") [ap_literal] ap_literal_tetraplets)
(call host (service_id "get_tetraplets") [result] first_tetraplets)
)
(call host (service_id "get_tetraplets") [ap_result] ap_first_tetraplets)
)
)
(seq
(call host ("op" "noop") [])
(call host (service_id "get_tetraplets") [first_tetraplets.$.[0][0].peer_pk] second_tetraplets)
)
)
(seq
(call host ("op" "noop") [])
(call client ("return" "") [ap_literal_tetraplets first_tetraplets ap_first_tetraplets second_tetraplets])
)
)"#);
let data = hashmap! {
"host" => json!(client.node.to_string()),
"client" => json!(client.peer_id.to_string()),
"service_id" => json!(tetraplets_service.id),
};
client.send_particle(script, data.clone()).await;
let args = client.receive_args().await.wrap_err("receive").unwrap();
let mut args = args.into_iter();
let ap_literal_tetraplets = args.next().unwrap();
let ap_literal_tetraplets: Vec<Vec<SecurityTetraplet>> =
serde_json::from_value(ap_literal_tetraplets)
.wrap_err("deserialize tetraplets")
.unwrap();
assert_eq!(ap_literal_tetraplets.len(), 1);
assert_eq!(ap_literal_tetraplets[0].len(), 1);
let tetraplet = &ap_literal_tetraplets[0][0];
assert_eq!(tetraplet.function_name, "");
assert_eq!(tetraplet.peer_pk, client.peer_id.to_base58());
assert_eq!(tetraplet.lens, "");
assert_eq!(tetraplet.service_id, "");
let first_tetraplets = args.next().unwrap();
let first_tetraplets: Vec<Vec<SecurityTetraplet>> = serde_json::from_value(first_tetraplets)
.wrap_err("deserialize tetraplets")
.unwrap();
assert_eq!(first_tetraplets.len(), 1);
assert_eq!(first_tetraplets[0].len(), 1);
let tetraplet = &first_tetraplets[0][0];
assert_eq!(tetraplet.function_name, "identity");
assert_eq!(tetraplet.peer_pk, client.node.to_base58());
assert_eq!(tetraplet.lens, "");
assert_eq!(tetraplet.service_id, "op");
let ap_first_tetraplets = args.next().unwrap();
let ap_first_tetraplets: Vec<Vec<SecurityTetraplet>> =
serde_json::from_value(ap_first_tetraplets)
.wrap_err("deserialize tetraplets")
.unwrap();
let ap_tetraplet = &ap_first_tetraplets[0][0];
assert_eq!(tetraplet, ap_tetraplet);
let second_tetraplets = args.next().unwrap();
let second_tetraplets: Vec<Vec<SecurityTetraplet>> = serde_json::from_value(second_tetraplets)
.wrap_err("deserialize tetraplets")
.unwrap();
let tetraplet = &second_tetraplets[0][0];
assert_eq!(tetraplet.function_name, "get_tetraplets");
assert_eq!(tetraplet.peer_pk, client.node.to_base58());
assert_eq!(tetraplet.lens, ".$.[0].[0].peer_pk");
assert_eq!(tetraplet.service_id, tetraplets_service.id.as_str());
} | 74,149 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: explicit_block_argument_spec.rb
path of file: ./repos/rubocop/spec/rubocop/cop/style
the code of the file until where you have to start completion: # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ExplicitBlockArgument, :config do
it 'registers an offense and corrects when block just yields its arguments' do
expect_offense(<<~RUBY)
def m
items.something(first_arg) { |i| yield i }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature
| def m
items.something { |i| yield i }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
if condition
yield 2
elsif other_condition
3.times { yield }
^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
else
other_items.something { |i, j| yield i, j }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end | 734,035 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: change_password.rb
path of file: ./repos/Cookbook/ruby/xmpp/examples/basic
the code of the file until where you have to start completion: #!/usr/bin/ruby
#
# A tool to change the password
| def with_status(str, &block)
print "#{str}..."
$stdout.flush
begin
yield
puts " Ok"
rescue Exception => e
puts " Exception: #{e.to_s}"
raise e
end | 213,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: repos_hooks.go
path of file: ./repos/devspace/vendor/github.com/google/go-github/v30/github
the code of the file until where you have to start completion: // Copyright 2013 The go-github 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 github
import (
"context"
"fmt"
"time"
)
/
| func (s *RepositoriesService) PingHook(ctx context.Context, owner, repo string, id int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/hooks/%d/pings", owner, repo, id)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
} | 466,404 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: vb.go
path of file: ./repos/sliver/vendor/github.com/alecthomas/chroma/lexers/v
the code of the file until where you have to start completion: package v
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
const vbName = `[_\w][\w]*`
// VB.Net lexer.
var VBNet = internal.Register(MustNewLazyLexer(
&Config{
Name: "VB.net",
Aliases: []string{"vb.net", "vbnet"},
Filenames: []string{"*.vb", "*.bas"},
MimeTypes: []string{"text/x-vbnet", "text/x-vba"},
CaseInsensitive: true,
},
vbNetRules,
))
func vbNetRules() Rules {
return Rules{
"root": {
{`^\s*<.*?>`, NameAttribute, nil},
{`\s+`, Text, nil},
{`\n`, Text, nil},
{`rem\b.*?\n`, Comment, nil},
{`'.*?\n`, Comment, nil},
{`#If\s.*?\sThen|#ElseIf\s.*?\sThen|#Else|#End\s+If|#Const|#ExternalSource.*?\n|#End\s+ExternalSource|#Region.*?\n|#End\s+Region|#ExternalChecksum`, CommentPreproc, nil},
{`[(){}!#,.:]`, Punctuation, nil},
{`Option\s+(Strict|Explicit|Compare)\s+(On|Off|Binary|Text)`, KeywordDeclaration, nil},
{Words(`(?<!\.)`, `\b`, `AddHandler`, `Alias`, `ByRef`, `ByVal`, `Call`, `Case`, `Catch`, `CBool`, `CByte`, `CChar`, `CDate`, `CDec`, `CDbl`, `CInt`, `CLng`, `CObj`, `Continue`, `CSByte`, `CShort`, `CSng`, `CStr`, `CType`, `CUInt`, `CULng`, `CUShort`, `Declare`, `Default`, `Delegate`, `DirectCast`, `Do`, `Each`, `Else`, `ElseIf`, `EndIf`, `Erase`, `Error`, `Event`, `Exit`, `False`, `Finally`, `For`, `Friend`, `Get`, `Global`, `GoSub`, `GoTo`, `Handles`, `If`, `Implements`, `Inherits`, `Interface`, `Let`, `Lib`, `Loop`, `Me`, `MustInherit`, `MustOverride`, `MyBase`, `MyClass`, `Narrowing`, `New`, `Next`, `Not`, `Nothing`, `NotInheritable`, `NotOverridable`, `Of`, `On`, `Operator`, `Option`, `Optional`, `Overloads`, `Overridable`, `Overrides`, `ParamArray`, `Partial`, `Private`, `Protected`, `Public`, `RaiseEvent`, `ReadOnly`, `ReDim`, `RemoveHandler`, `Resume`, `Return`, `Select`, `Set`, `Shadows`, `Shared`, `Single`, `Static`, `Step`, `Stop`, `SyncLock`, `Then`, `Throw`, `To`, `True`, `Try`, `TryCast`, `Wend`, `Using`, `When`, `While`, `Widening`, `With`, `WithEvents`, `WriteOnly`), Keyword, nil},
{`(?<!\.)End\b`, Keyword, Push("end")},
{`(?<!\.)(Dim|Const)\b`, Keyword, Push("dim")},
{`(?<!\.)(Function|Sub|Property)(\s+)`, ByGroups(Keyword, Text), Push("funcname")},
{`(?<!\.)(Class|Structure|Enum)(\s+)`, ByGroups(Keyword, Text), Push("classname")},
{`(?<!\.)(Module|Namespace|Imports)(\s+)`, ByGroups(Keyword, Text), Push("namespace")},
{`(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|Object|SByte|Short|Single|String|Variant|UInteger|ULong|UShort)\b`, KeywordType, nil},
{`(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|Or|OrElse|TypeOf|Xor)\b`, OperatorWord, nil},
{`&=|[*]=|/=|\\=|\^=|
| func vbNetRules() Rules {
return Rules{
"root": {
{`^\s*<.*?>`, NameAttribute, nil},
{`\s+`, Text, nil},
{`\n`, Text, nil},
{`rem\b.*?\n`, Comment, nil},
{`'.*?\n`, Comment, nil},
{`#If\s.*?\sThen|#ElseIf\s.*?\sThen|#Else|#End\s+If|#Const|#ExternalSource.*?\n|#End\s+ExternalSource|#Region.*?\n|#End\s+Region|#ExternalChecksum`, CommentPreproc, nil},
{`[(){}!#,.:]`, Punctuation, nil},
{`Option\s+(Strict|Explicit|Compare)\s+(On|Off|Binary|Text)`, KeywordDeclaration, nil},
{Words(`(?<!\.)`, `\b`, `AddHandler`, `Alias`, `ByRef`, `ByVal`, `Call`, `Case`, `Catch`, `CBool`, `CByte`, `CChar`, `CDate`, `CDec`, `CDbl`, `CInt`, `CLng`, `CObj`, `Continue`, `CSByte`, `CShort`, `CSng`, `CStr`, `CType`, `CUInt`, `CULng`, `CUShort`, `Declare`, `Default`, `Delegate`, `DirectCast`, `Do`, `Each`, `Else`, `ElseIf`, `EndIf`, `Erase`, `Error`, `Event`, `Exit`, `False`, `Finally`, `For`, `Friend`, `Get`, `Global`, `GoSub`, `GoTo`, `Handles`, `If`, `Implements`, `Inherits`, `Interface`, `Let`, `Lib`, `Loop`, `Me`, `MustInherit`, `MustOverride`, `MyBase`, `MyClass`, `Narrowing`, `New`, `Next`, `Not`, `Nothing`, `NotInheritable`, `NotOverridable`, `Of`, `On`, `Operator`, `Option`, `Optional`, `Overloads`, `Overridable`, `Overrides`, `ParamArray`, `Partial`, `Private`, `Protected`, `Public`, `RaiseEvent`, `ReadOnly`, `ReDim`, `RemoveHandler`, `Resume`, `Return`, `Select`, `Set`, `Shadows`, `Shared`, `Single`, `Static`, `Step`, `Stop`, `SyncLock`, `Then`, `Throw`, `To`, `True`, `Try`, `TryCast`, `Wend`, `Using`, `When`, `While`, `Widening`, `With`, `WithEvents`, `WriteOnly`), Keyword, nil},
{`(?<!\.)End\b`, Keyword, Push("end")},
{`(?<!\.)(Dim|Const)\b`, Keyword, Push("dim")},
{`(?<!\.)(Function|Sub|Property)(\s+)`, ByGroups(Keyword, Text), Push("funcname")},
{`(?<!\.)(Class|Structure|Enum)(\s+)`, ByGroups(Keyword, Text), Push("classname")},
{`(?<!\.)(Module|Namespace|Imports)(\s+)`, ByGroups(Keyword, Text), Push("namespace")},
{`(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|Object|SByte|Short|Single|String|Variant|UInteger|ULong|UShort)\b`, KeywordType, nil},
{`(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|Or|OrElse|TypeOf|Xor)\b`, OperatorWord, nil},
{`&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|<=|>=|<>|[-&*/\\^+=<>\[\]]`, Operator, nil},
{`"`, LiteralString, Push("string")},
{`_\n`, Text, nil},
{vbName, Name, nil},
{`#.*?#`, LiteralDate, nil},
{`(\d+\.\d*|\d*\.\d+)(F[+-]?[0-9]+)?`, LiteralNumberFloat, nil},
{`\d+([SILDFR]|US|UI|UL)?`, LiteralNumberInteger, nil},
{`&H[0-9a-f]+([SILDFR]|US|UI|UL)?`, LiteralNumberInteger, nil},
{`&O[0-7]+([SILDFR]|US|UI|UL)?`, LiteralNumberInteger, nil},
},
"string": {
{`""`, LiteralString, nil},
{`"C?`, LiteralString, Pop(1)},
{`[^"]+`, LiteralString, nil},
},
"dim": {
{vbName, NameVariable, Pop(1)},
Default(Pop(1)),
},
"funcname": {
{vbName, NameFunction, Pop(1)},
},
"classname": {
{vbName, NameClass, Pop(1)},
},
"namespace": {
{vbName, NameNamespace, nil},
{`\.`, NameNamespace, nil},
Default(Pop(1)),
},
"end": {
{`\s+`, Text, nil},
{`(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b`, Keyword, Pop(1)},
Default(Pop(1)),
},
}
} | 452,791 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: vpmaskmovd.rb
path of file: ./repos/fisk/lib/fisk/instructions
the code of the file until where you have to start completion: # frozen_string_literal: true
class Fisk
module Instructions
# Instruction VPMASKMOVD: Conditional Move Packed Doubleword Integers
VPMASKMOVD = Instructio
| def encode buffer, operands
add_VEX(buffer, operands)
add_opcode(buffer, 0x8C, 0) +
add_modrm(buffer,
0,
operands[0].op_value,
operands[2].op_value, operands) +
0
end | 190,886 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: util.rs
path of file: ./repos/plane/plane/src
the code of the file until where you have to start completion: use chrono::Duration;
use futures_util::Future;
use rand::{
distributions::{Distribution, Uniform},
Rng,
};
use std::{
net::{IpAddr, ToSocketAddrs},
time::SystemTime,
};
use
| pub fn resolve_hostname(hostname: &str) -> Option<IpAddr> {
// The port is arbitrary, but needs to be provided.
let socket_addrs = format!("{}:0", hostname).to_socket_addrs().ok()?;
for socket_addr in socket_addrs {
if let IpAddr::V4(ip) = socket_addr.ip() {
return Some(ip.into());
}
}
None
} | 727,809 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: reviewable_priorities_spec.rb
path of file: ./repos/discourse/spec/jobs
the code of the file until where you have to start completion: # frozen_string_literal: true
RSpec.describe Jobs::ReviewablePriorities do
it "needs returns 0s with no existing reviewables" do
Jobs::ReviewablePriorities.new.execute({})
expect_min_score(:low, 0.0)
| def create_with_score(score, status: :approved)
Fabricate(:reviewable_flagged_post, status: Reviewable.statuses[status]).tap do |reviewable|
reviewable.add_score(user_0, PostActionType.types[:off_topic])
reviewable.add_score(user_1, PostActionType.types[:off_topic])
reviewable.update!(score: score)
end
end | 616,595 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: customresourcedefinitionversion.go
path of file: ./repos/hubble-ui/backend/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1
the code of the file until where you have to start completion: /*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You 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, so
| func (b *CustomResourceDefinitionVersionApplyConfiguration) WithAdditionalPrinterColumns(values ...*CustomResourceColumnDefinitionApplyConfiguration) *CustomResourceDefinitionVersionApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithAdditionalPrinterColumns")
}
b.AdditionalPrinterColumns = append(b.AdditionalPrinterColumns, *values[i])
}
return b
} | 379,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: provider.go
path of file: ./repos/erda/internal/apps/dop/providers/publishitem
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
| func init() {
servicehub.Register("erda.dop.publishitem", &servicehub.Spec{
Services: pb.ServiceNames(),
Types: pb.Types(),
OptionalDependencies: []string{"service-register"},
Description: "",
ConfigFunc: func() interface{} {
return &config{}
},
Creator: func() servicehub.Provider {
return &provider{}
},
})
} | 709,992 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: tee_test.go
path of file: ./repos/zap/zapcore
the code of the file until where you have to start completion: // Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any per
| func TestTeeUnusualInput(t *testing.T) {
// Verify that Tee handles receiving one and no inputs correctly.
t.Run("one input", func(t *testing.T) {
obs, _ := observer.New(DebugLevel)
assert.Equal(t, obs, NewTee(obs), "Expected to return single inputs unchanged.")
})
t.Run("no input", func(t *testing.T) {
assert.Equal(t, NewNopCore(), NewTee(), "Expected to return NopCore.")
})
} | 3,073 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: article_customer_factory.rb
path of file: ./repos/zammad/lib/import/otrs
the code of the file until where you have to start completion: # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
module Import
module OTRS
module ArticleCustomerFactory
| def skip?(record, *_args)
return true if record['SenderType'] != 'customer'
return true if create_by_id(record) != 1
return true if record['From'].blank?
false
end | 253,269 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: yaml.go
path of file: ./repos/AdGuardHome/internal/configmigrate
the code of the file until where you have to start completion: package configmigrate
import (
"fmt"
)
type (
// yarr is the conven
| func fieldVal[T any](obj yobj, key string) (v T, ok bool, err error) {
val, ok := obj[key]
if !ok {
return v, false, nil
}
if val == nil {
return v, true, nil
}
v, ok = val.(T)
if !ok {
return v, false, fmt.Errorf("unexpected type of %q: %T", key, val)
}
return v, true, nil
} | 114,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: main.rs
path of file: ./repos/turbo/crates/turbopack-trace-server/src
the code of the file until where you have to start completion: #![feature(i
| fn main() {
let args: HashSet<String> = std::env::args().skip(1).collect();
let arg = args
.iter()
.next()
.expect("missing argument: trace file path");
let store = Arc::new(StoreContainer::new());
let reader = TraceReader::spawn(store.clone(), arg.into());
serve(store).unwrap();
reader.join().unwrap();
} | 464,739 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: strategy.go
path of file: ./repos/kubernetes/pkg/registry/resource/podschedulingcontext
the code of the file until where you have to start completion: /*
Copyright 2022 The Kubernetes Authors.
Licensed under the Apache License, Version
| func Match(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
return storage.SelectionPredicate{
Label: label,
Field: field,
GetAttrs: GetAttrs,
}
} | 360,182 |
You are an expert in writing code in many different languages. Your goal is 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/2301-2400/2384.Largest-Palindromic-Number
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 bo
| 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,515 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: fdyn.m
path of file: ./repos/robotics-toolbox-matlab/Octave/@SerialLink
the code of the file until where you have to start completion: %SerialLink.fdyn Integrate forward dynamics
%
% [T,Q,QD] = R.fdyn(T1, TORQFUN) integrates the dynamics of the robot over
% the time interval 0 to T and returns vectors of time TI, joint position Q
% and joint velocity QD. The initial joint position and velocity are zero.
% The torque applied to the joints is computed by the user function TORQFUN:
%
% [TI,Q,QD] = R.fdyn(T, TORQFUN, Q0, QD0) as above but allows the initial
% joint position and velocity to be specified.
%
% The control torque is computed by a user defined function
%
% TAU = TORQFUN(T, Q, QD, ARG1, ARG2, ...)
%
% where Q and QD are the manipulator
| function called by FDYN
%
% XDD = FDYN2(T, X, FLAG, ROBOT, TORQUEFUN)
%
% Called by FDYN to evaluate the robot velocity and acceleration for
% forward dynamics. T is the current time, X = [Q QD] is the state vector,
% ROBOT is the object being integrated, and TORQUEFUN is the string name of
% the function to compute joint torques and called as
%
% TAU = TORQUEFUN(T, X)
%
% if not given zero joint torques are assumed.
%
% The result is XDD = [QD QDD].
function xd = fdyn2(x, t)
global __fdyn_robot;
global __fdyn_torqfun;
robot = __fdyn_robot;
torqfun = __fdyn_torqfun;
n = robot.n;
q = x(1:n);
qd = x(n+1:2*n);
if isstr(torqfun)
tau = feval(torqfun, t, q, qd);
else
tau = zeros(n,1)';
end | 392,998 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: post_wrapper.rb
path of file: ./repos/kitsu-server/app/services/zorro/wrapper
the code of the file until where you have to start completion: module Zorro
class Wrapper
class PostWrapper < BasePost
# Wrap a Post in whichever delegate knows how to handle it proper
| def self.wrap(data)
# Ignore posts involving Recommendations
return if data['parentClass'] == 'Recommendation'
# Normally replyLevel maps straight 0->Post, 1->Comment, but Anime threads have 0->Comment,
# 1->Subcomment, so we push them down one, identifying them by lack of a parentClass and
# presence of a _p_thread. This makes the mappings 0->Post, 1->Comment, 2->Subcomment
reply_level = data['replyLevel'] || 0
reply_level += 1 if data['parentClass'].blank? && data['_p_thread'].present?
# Delegate based on reply level
case reply_level
when 0 then PostWrapper.new(data)
when 1 then CommentWrapper.new(data)
when 2 then ReplyWrapper.new(data)
end
end | 70,929 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: hello-world.rs
path of file: ./repos/roa/examples
the code of the file until where you have to start completion: //! RUST_LOG=info Cargo run --example he
| async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.try_init()
.map_err(|err| anyhow::anyhow!("fail to init tracing subscriber: {}", err))?;
let app = App::new().gate(logger).end("Hello, World!");
app.listen("127.0.0.1:8000", |addr| {
info!("Server is listening on {}", addr)
})?
.await?;
Ok(())
} | 31,314 |
You are an expert in writing code in many different languages. Your goal is 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_client_test.go
path of file: ./repos/aws-sdk-go-v2/service/elasticinference
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package elasticinference
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
"io/ioutil"
"net/http"
"strings"
"testing"
)
func TestClient_resolveRetryOptions(t *testing.T) {
nopClient := smithyhttp.ClientDoFunc(func(_ *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(strings.NewReader("")),
}, nil
})
cases := map[string]struct {
defaultsMode aws.DefaultsMode
retryer aws.Retryer
retryMaxAttempts int
opRetryMaxAttempts *int
retryMode aws.RetryMode
expectClientRetryMode aws.RetryMode
expectClientMaxAttempts int
expectOpMaxAttempts int
}{
"defaults": {
defaultsMode: aws.DefaultsModeStandard,
expectClientRetryMode: aws.RetryModeStandard,
expectClientMaxAttempts: 3,
expectOpMaxAttempts: 3,
},
"custom default retry": {
retryMode: aws.RetryModeAdaptive,
retryMaxAttempts: 10,
expectClientRetryMode: aws.RetryModeAdaptive,
expectClientMaxAttempts: 10,
expectOpMaxAttempts: 10,
},
"custom op max attempts": {
retryMode: aws.RetryModeAdaptive,
retryMaxAttempts: 10,
opRetryMaxAttempts: aws.Int(2),
expectClientRetryMode: aws.RetryModeAdaptive,
expectClientMaxAttempts: 10,
expectOpMaxAttempts: 2,
},
"custom op no change max attempts": {
retryMode: aws.RetryModeAdaptive,
retryMaxAttempts: 10,
opRetryMaxAttempts: aws.Int(10),
expectClientRetryMode: aws.RetryModeAdaptive,
expectClientMaxAttempts: 10,
expectOpMaxAttempts: 10,
},
| func TestClient_resolveRetryOptions(t *testing.T) {
nopClient := smithyhttp.ClientDoFunc(func(_ *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Header: http.Header{},
Body: ioutil.NopCloser(strings.NewReader("")),
}, nil
})
cases := map[string]struct {
defaultsMode aws.DefaultsMode
retryer aws.Retryer
retryMaxAttempts int
opRetryMaxAttempts *int
retryMode aws.RetryMode
expectClientRetryMode aws.RetryMode
expectClientMaxAttempts int
expectOpMaxAttempts int
}{
"defaults": {
defaultsMode: aws.DefaultsModeStandard,
expectClientRetryMode: aws.RetryModeStandard,
expectClientMaxAttempts: 3,
expectOpMaxAttempts: 3,
},
"custom default retry": {
retryMode: aws.RetryModeAdaptive,
retryMaxAttempts: 10,
expectClientRetryMode: aws.RetryModeAdaptive,
expectClientMaxAttempts: 10,
expectOpMaxAttempts: 10,
},
"custom op max attempts": {
retryMode: aws.RetryModeAdaptive,
retryMaxAttempts: 10,
opRetryMaxAttempts: aws.Int(2),
expectClientRetryMode: aws.RetryModeAdaptive,
expectClientMaxAttempts: 10,
expectOpMaxAttempts: 2,
},
"custom op no change max attempts": {
retryMode: aws.RetryModeAdaptive,
retryMaxAttempts: 10,
opRetryMaxAttempts: aws.Int(10),
expectClientRetryMode: aws.RetryModeAdaptive,
expectClientMaxAttempts: 10,
expectOpMaxAttempts: 10,
},
"custom op 0 max attempts": {
retryMode: aws.RetryModeAdaptive,
retryMaxAttempts: 10,
opRetryMaxAttempts: aws.Int(0),
expectClientRetryMode: aws.RetryModeAdaptive,
expectClientMaxAttempts: 10,
expectOpMaxAttempts: 10,
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
client := NewFromConfig(aws.Config{
DefaultsMode: c.defaultsMode,
Retryer: func() func() aws.Retryer {
if c.retryer == nil {
return nil
}
return func() aws.Retryer { return c.retryer }
}(),
HTTPClient: nopClient,
RetryMaxAttempts: c.retryMaxAttempts,
RetryMode: c.retryMode,
}, func(o *Options) {
if o.Retryer == nil {
t.Errorf("retryer must not be nil in functional options")
}
})
if e, a := c.expectClientRetryMode, client.options.RetryMode; e != a {
t.Errorf("expect %v retry mode, got %v", e, a)
}
if e, a := c.expectClientMaxAttempts, client.options.Retryer.MaxAttempts(); e != a {
t.Errorf("expect %v max attempts, got %v", e, a)
}
_, _, err := client.invokeOperation(context.Background(), "mockOperation", struct{}{},
[]func(*Options){
func(o *Options) {
if c.opRetryMaxAttempts == nil {
return
}
o.RetryMaxAttempts = *c.opRetryMaxAttempts
},
},
func(s *middleware.Stack, o Options) error {
s.Initialize.Clear()
s.Serialize.Clear()
s.Build.Clear()
s.Finalize.Clear()
s.Deserialize.Clear()
if e, a := c.expectOpMaxAttempts, o.Retryer.MaxAttempts(); e != a {
t.Errorf("expect %v op max attempts, got %v", e, a)
}
return nil
})
if err != nil {
t.Fatalf("expect no operation error, got %v", err)
}
})
}
} | 229,559 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: mcache.rs
path of file: ./repos/rust-libp2p/protocols/gossipsub/src
the code of the file until where you have to start completion: // Copyright 2020 Sigma Prime Pty Ltd.
//
// Permission is hereby g
| fn test_empty_shift() {
let mut mc = new_cache(1, 5);
let topic1_hash = Topic::new("topic1").hash();
// Build the message
for i in 0..10 {
let (id, m) = gen_testm(i, topic1_hash.clone());
mc.put(&id, m.clone());
}
mc.shift();
// Ensure the shift occurred
assert!(mc.history[0].is_empty());
assert!(mc.history[1].len() == 10);
mc.shift();
assert!(mc.history[2].len() == 10);
assert!(mc.history[1].is_empty());
assert!(mc.history[0].is_empty());
} | 56,093 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: end_turn.rs
path of file: ./repos/HandsOnRust/InventoryAndPowerUps/carrying_items/src/systems
the code of the file until where you have to start completion: use crate::prelude::*;
#[system]
#[read_component(Health)]
#[read_component(Point)]
#[read_component(Player)]
#[read_component(AmuletOfYala)]
pub fn end_turn(ecs: &SubWorld, #[resource] turn_state: &mut TurnState) {
let mut player_hp = <(&Health, &Point)>::query().filter(component::<Player>());
let mut amulet = <&Point>::query().filter(component::<AmuletOfYala>());
let current_state = turn_state.clone();
| pub fn end_turn(ecs: &SubWorld, #[resource] turn_state: &mut TurnState) {
let mut player_hp = <(&Health, &Point)>::query().filter(component::<Player>());
let mut amulet = <&Point>::query().filter(component::<AmuletOfYala>());
let current_state = turn_state.clone();
let mut new_state = match current_state {
TurnState::AwaitingInput => return,
TurnState::PlayerTurn => TurnState::MonsterTurn,
TurnState::MonsterTurn => TurnState::AwaitingInput,
_ => current_state
};
let amulet_pos = amulet
.iter(ecs)
.nth(0)
.unwrap();
player_hp.iter(ecs).for_each(|(hp, pos)| {
if hp.current < 1 {
new_state = TurnState::GameOver;
}
if pos == amulet_pos {
new_state = TurnState::Victory;
}
});
*turn_state = new_state;
} | 286,902 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: provision.go
path of file: ./repos/erda/internal/tools/volume-provisioner/localvolume
the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package localvolume
import (
"context"
"errors"
"fmt"
"sync"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"sigs.k8s.io/sig-storage-lib-external-provisioner/v6/controller"
"github.com/erda-project/erda/internal/tool
| func (p *localVolumeProvisioner) Provision(ctx context.Context, options controller.ProvisionOptions) (*v1.PersistentVolume, controller.ProvisioningState, error) {
logrus.Infof("Start provisioning local volume: options: %v", options)
if options.SelectedNode == nil {
err := errors.New("not provide selectedNode in provisionOptions")
logrus.Error(err)
return nil, controller.ProvisioningFinished, err
}
volPathOnHost, err := volumeRealPath(&options, options.PVName)
if err != nil {
return nil, controller.ProvisioningFinished, err
}
volPath, err := volumePath(&options, options.PVName)
if err != nil {
return nil, controller.ProvisioningFinished, err
}
if p.lvpConfig.ModeEdge {
if p.lvpConfig.NodeName != options.SelectedNode.Name {
err = fmt.Errorf("cant't match create request, want: %s, request: %s", p.lvpConfig.NodeName, options.SelectedNode.Name)
return nil, controller.ProvisioningFinished, err
}
if err = p.cmdExecutor.OnLocal(fmt.Sprintf("mkdir -p %s", volPath)); err != nil {
logrus.Errorf("node %s mkdir %s error: %v", p.lvpConfig.NodeName, volPath, err)
return nil, controller.ProvisioningFinished, err
}
} else {
nodeSelector := fmt.Sprintf("kubernetes.io/hostname=%s", options.SelectedNode.Name)
if err := p.cmdExecutor.OnNodesPods(fmt.Sprintf("mkdir -p %s", volPath),
metav1.ListOptions{
LabelSelector: nodeSelector,
}, metav1.ListOptions{
LabelSelector: p.lvpConfig.MatchLabel,
}); err != nil {
return nil, controller.ProvisioningFinished, err
}
}
return &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
},
PersistentVolumeSource: v1.PersistentVolumeSource{
Local: &v1.LocalVolumeSource{
Path: volPathOnHost,
},
},
NodeAffinity: &v1.VolumeNodeAffinity{
Required: &v1.NodeSelector{
NodeSelectorTerms: []v1.NodeSelectorTerm{
{
MatchExpressions: []v1.NodeSelectorRequirement{
{
Key: "kubernetes.io/hostname",
Operator: v1.NodeSelectorOpIn,
Values: []string{options.SelectedNode.Name},
},
},
},
},
},
},
},
}, controller.ProvisioningFinished, nil
} | 711,550 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: build_paths.rs
path of file: ./repos/perseus/examples/core/state_generation/src/templates
the code of the file until where you have to start completion: use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
#[derive(Serialize, Deserialize, Clone, Rea
| async fn get_build_state(info: StateGeneratorInfo<()>) -> PageState {
let title = info.path.clone();
let content = format!(
"This is a post entitled 'build_paths/{}'. Its original slug was 'build_paths/{}'.",
&title, &info.path
);
PageState { title, content }
} | 655,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: interceptor.go
path of file: ./repos/erda/internal/pkg/audit
the code of the file until where you have to start completion: // Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package audit
import (
"context"
"fmt"
"reflect"
"runtime"
"strings"
"unicode"
"github.com/erda-project/erda-infra/pkg/transport"
"github.com/erda-project/erda-infra/pkg/transport/interceptor"
)
type (
// MethodAuditor .
MethodAuditor st
| func (a *auditor) Audit(auditors ...*MethodAuditor) transport.ServiceOption {
methods := make(map[string]*MethodAuditor)
for _, audit := range auditors {
if _, ok := methods[audit.method]; ok {
panic(fmt.Errorf("method %q already exists for audit", audit.method))
}
if len(audit.method) <= 0 {
panic(fmt.Errorf("invalid method %q for audit", audit.method))
}
methods[audit.method] = audit
}
return transport.WithInterceptors(func(h interceptor.Handler) interceptor.Handler {
if a.p.Cfg != nil && a.p.Cfg.Skip {
return h
}
return func(ctx context.Context, req interface{}) (interface{}, error) {
info := transport.ContextServiceInfo(ctx)
ma := methods[info.Method()]
if ma == nil {
return h(ctx, req)
}
rec := a.Begin()
ctxData := &optionContextData{}
ctx = withOptionDataContext(ctx, ctxData)
resp, err := h(ctx, req)
if err == nil || ma.recordError {
var (
loaded bool
scopeID interface{}
entries map[string]interface{}
loadError error
)
loadScopeIDAndEntries := func() {
if !loaded {
loaded = true
scopeID, entries, loadError = ma.getter(ctx, req, resp, err)
}
}
ctxOpts := ctxData.opts
opts := make([]Option, 1+len(ma.options)+len(ctxOpts))
opts[0] = Entries(func(ctx context.Context) (map[string]interface{}, error) {
loadScopeIDAndEntries()
return entries, loadError
})
copy(opts[1:], ma.options)
copy(opts[1+len(ma.options):], ctxOpts)
if err != nil {
rec.RecordError(ctx, ma.scope, func(ctx context.Context) (interface{}, error) {
loadScopeIDAndEntries()
return scopeID, loadError
}, ma.template, opts...)
} else {
rec.Record(ctx, ma.scope, func(ctx context.Context) (interface{}, error) {
loadScopeIDAndEntries()
return scopeID, loadError
}, ma.template, opts...)
}
}
return resp, err
}
})
} | 710,973 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: msmbackward_parallel.m
path of file: ./repos/mdtoolbox/mdtoolbox
the code of the file until where you have to start completion: function [logL, beta, beta_nonscaled] = msmbackward_parallel(data, factor, T, emission, pi_i)
%% msmbackward
% backward algorithm to calculate the probability of observed sequence
%
%% Syntax
%# [logL, beta] = msmbackward(data, factor, T, emission, pi_i)
%# [logL, beta, beta_nonscaled] = msmbackward(data, factor, T, emission, pi_i)
%
%% Description
%
| function [logL, beta, beta_nonscaled] = msmbackward_parallel(data, factor, T, emission, pi_i)
%% msmbackward
% backward algorithm to calculate the probability of observed sequence
%
%% Syntax
%# [logL, beta] = msmbackward(data, factor, T, emission, pi_i)
%# [logL, beta, beta_nonscaled] = msmbackward(data, factor, T, emission, pi_i)
%
%% Description
%
%
%% Example
%#
%
%% See also
%
%% TODO
% robustness against zero elements of T
%
%% setup
if iscell(data)
data_cell = data;
factor_cell = factor;
is_cell = true;
else
data_cell{1} = data;
factor_cell{1} = factor;
is_cell = false;
end | 53,368 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: get_cult_by_id.rs
path of file: ./repos/rust-graphql-docker/api/src/data/cult
the code of the file until where you have to start completion: extern crate postgres;
use crate::db::get_db_conn;
use crate::type_defs::Cult;
use dataloader::cached::
| // pub fn create_cult(data: NewCult) -> Cult {
// let conn = get_db_conn();
// let res = &conn
// .query(
// "INSERT INTO cults (name, cult) VALUES ($1, $2) RETURNING id, name, cult;",
// &[&data.name, &data.cult],
// )
// .unwrap();
// let row = res.iter().next().unwrap();
// Cult {
// id: row.get(0),
// name: row.get(1),
// cult: row.get(2)
// }
// } | 94,661 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: endpoint.rs
path of file: ./repos/summer-boot/summer-boot/src/server
the code of the file until where you have to start completion: use crate::utils;
use crate::{Middleware, Request, Response};
use async_st
| fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
fmt,
"MiddlewareEndpoint (length: {})",
self.middleware.len(),
)
} | 119,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: endpoints_config_test.go
path of file: ./repos/aws-sdk-go-v2/service/wellarchitected
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package wellarchitected
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"os"
"reflect"
"testing"
)
type mockConfigSource struct {
global string
service string
ignore bool
}
// GetIgnoreConfiguredEndpoints is used in knowing when to disable configured
// endpoints feature.
func (m mockConfigSource) GetIgnoreConfiguredEndpoints(context.Context) (bool, bool, error) {
return m.ignore, m.ignore, nil
}
// GetServiceBaseEndpoint is used to retrieve a normalized SDK ID for use
// with configured endpoints.
func (m mockConfigSource) GetServiceBaseEndpoint(ctx context.Context, sdkID string) (string, bool, error) {
if m.service != "" {
return m.service, true, nil
}
return "", false, nil
}
func TestResolveBaseEndpoint(t *testing.T) {
cases := map[string]struct {
envGlobal string
envService string
envIgnore bool
configGlobal string
configService string
configIgnore bool
clientEndpoint *string
expectURL *string
}{
"env ignore": {
envGlobal: "https://env-global.dev",
envService: "https://env-wellarchitected.dev",
envIgnore: true,
configGlobal: "http://config-global.dev",
configService: "http://config-wellarchitected.dev",
expectURL: nil,
},
"env global": {
envGlobal: "https://env-global.dev",
configGlobal: "
| func TestResolveBaseEndpoint(t *testing.T) {
cases := map[string]struct {
envGlobal string
envService string
envIgnore bool
configGlobal string
configService string
configIgnore bool
clientEndpoint *string
expectURL *string
}{
"env ignore": {
envGlobal: "https://env-global.dev",
envService: "https://env-wellarchitected.dev",
envIgnore: true,
configGlobal: "http://config-global.dev",
configService: "http://config-wellarchitected.dev",
expectURL: nil,
},
"env global": {
envGlobal: "https://env-global.dev",
configGlobal: "http://config-global.dev",
configService: "http://config-wellarchitected.dev",
expectURL: aws.String("https://env-global.dev"),
},
"env service": {
envGlobal: "https://env-global.dev",
envService: "https://env-wellarchitected.dev",
configGlobal: "http://config-global.dev",
configService: "http://config-wellarchitected.dev",
expectURL: aws.String("https://env-wellarchitected.dev"),
},
"config ignore": {
envGlobal: "https://env-global.dev",
envService: "https://env-wellarchitected.dev",
configGlobal: "http://config-global.dev",
configService: "http://config-wellarchitected.dev",
configIgnore: true,
expectURL: nil,
},
"config global": {
configGlobal: "http://config-global.dev",
expectURL: aws.String("http://config-global.dev"),
},
"config service": {
configGlobal: "http://config-global.dev",
configService: "http://config-wellarchitected.dev",
expectURL: aws.String("http://config-wellarchitected.dev"),
},
"client": {
envGlobal: "https://env-global.dev",
envService: "https://env-wellarchitected.dev",
configGlobal: "http://config-global.dev",
configService: "http://config-wellarchitected.dev",
clientEndpoint: aws.String("https://client-wellarchitected.dev"),
expectURL: aws.String("https://client-wellarchitected.dev"),
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
os.Clearenv()
awsConfig := aws.Config{}
ignore := c.envIgnore || c.configIgnore
if c.configGlobal != "" && !ignore {
awsConfig.BaseEndpoint = aws.String(c.configGlobal)
}
if c.envGlobal != "" {
t.Setenv("AWS_ENDPOINT_URL", c.envGlobal)
if !ignore {
awsConfig.BaseEndpoint = aws.String(c.envGlobal)
}
}
if c.envService != "" {
t.Setenv("AWS_ENDPOINT_URL_WELLARCHITECTED", c.envService)
}
awsConfig.ConfigSources = []interface{}{
mockConfigSource{
global: c.envGlobal,
service: c.envService,
ignore: c.envIgnore,
},
mockConfigSource{
global: c.configGlobal,
service: c.configService,
ignore: c.configIgnore,
},
}
client := NewFromConfig(awsConfig, func(o *Options) {
if c.clientEndpoint != nil {
o.BaseEndpoint = c.clientEndpoint
}
})
if e, a := c.expectURL, client.options.BaseEndpoint; !reflect.DeepEqual(e, a) {
t.Errorf("expect endpoint %v , got %v", e, a)
}
})
}
} | 231,891 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: codec_message.go
path of file: ./repos/buildkit/vendor/google.golang.org/protobuf/internal/impl
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-style
// license that can be found in the LICENSE file.
package impl
import (
"fmt"
"reflect"
"sort"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/internal/encoding/messageset"
"google.golang.org/protobuf/internal/order"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/runtime/protoiface"
)
// coderMessageInfo contains per-message information used by the fast-path functions.
// This is a different type from MessageInfo to keep MessageInfo as general-purpose as
// possible.
type coderMessageInfo struct {
methods protoiface.Methods
orderedCoderFields []*coderFieldInfo
denseCoderFields []*coderFieldInfo
coderFields map[protowire.Number]*coderFieldInfo
sizecacheOffset offset
unknownOffset offset
unknownPtrKind bool
extensionOffset offset
needsInitCheck bool
isMessageSet bool
numRequiredFields uint8
}
type coderFieldInfo struct {
funcs pointerCoderFuncs // fast-path per-field functions
mi *MessageInfo // field's message
ft reflect.Type
validation validationInfo // information used by message validation
num protoreflect.FieldNumber // field number
offset offset // struct field offset
wiretag uint64 // field tag (number + wire type)
tagsize int // size of the varint-encoded tag
isPointer bool // true if IsNil may be called on the struct field
isRequired bool // true if field is required
}
func (mi *MessageInfo) makeCoderMethods(t reflect.Type, si structInfo) {
mi.sizecacheOffset = invalidOffset
mi.unknownOffset = invalidOffset
mi.extensionOffset = invalidOffset
if si.sizecacheOffset.IsValid() && si.sizecacheType == sizecacheType {
mi.sizecacheOffset = si.sizecacheOffset
}
if si.unknownOffset.IsValid() && (si.unknownType == unknownFieldsAType || si.unknownType == unknownFieldsBType) {
mi.unknownOffset = si.unknownOffset
mi.unknownPtrKind = si.unknownType.Kind() == reflect.Ptr
}
if si.extensionOffset.IsValid() && si.extensionType == extensionFieldsType {
mi.extensionOffset = si.extensionOffset
}
mi.coderFields = make(map[protowire.Number]*coderFieldInfo)
fields := mi.Desc.Fields()
preallocFields := make([]coderFieldInfo, fields.Len())
for i := 0; i < fields.Len(); i++ {
fd := fields.Get(i)
fs := si.fieldsByNumber[fd.Number()]
isOneof := fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic()
if isOneof {
fs = si.oneofsByName[fd.ContainingOneof().Name()]
}
ft := fs.Type
var wiretag uint64
if !fd.IsPacked() {
wiretag = protowire.EncodeTag(fd.Number(), wireTypes[fd.Kind()])
} else {
wiretag = protowire.EncodeTag(fd.Number(), protowire.BytesType)
}
var fieldOffset offset
var funcs pointerCoderFuncs
var childMessage *MessageInfo
switch {
case ft == nil:
// This never occurs for generated message types.
// It implies that a hand-crafted type has missing Go fields
// for specific protobuf message fields.
funcs = pointerCoderFuncs{
size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int {
return 0
},
marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) {
return nil, nil
},
unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) {
panic("missing Go struct field for " + string(fd.FullName()))
},
isInit: func(p pointer, f *coderFieldInfo) error {
panic("missing Go struct field for " + string(fd.FullName()))
},
merge: func(dst, src pointer, f *coderFieldInfo, opts mergeOptions) {
panic("missing Go struct field for " + string(fd.FullName()))
},
}
case isOneof:
fieldOffset = offsetOf(fs, mi.Exporter)
case fd.IsWeak():
fieldOffset = si.weakOffset
funcs = makeWeakMessageFieldCoder(fd)
default:
fieldOffset = offsetOf(fs, mi.Exporter)
childMessage, funcs = fieldCoder(fd, ft)
}
cf := &preallocFields[i]
*cf = coderFieldInfo{
num: fd.Number(),
offset: fieldOffset,
wiretag: wiretag,
ft: ft,
tagsize: protowire.SizeVarint(wiretag),
funcs: funcs,
mi: childMessage,
validation: newFieldValidationInfo(mi, si, fd, ft),
isPointer: fd.Cardinality() == protoreflect.Repeated || fd.HasPresence(),
isRequired: fd.Car
| func (mi *MessageInfo) makeCoderMethods(t reflect.Type, si structInfo) {
mi.sizecacheOffset = invalidOffset
mi.unknownOffset = invalidOffset
mi.extensionOffset = invalidOffset
if si.sizecacheOffset.IsValid() && si.sizecacheType == sizecacheType {
mi.sizecacheOffset = si.sizecacheOffset
}
if si.unknownOffset.IsValid() && (si.unknownType == unknownFieldsAType || si.unknownType == unknownFieldsBType) {
mi.unknownOffset = si.unknownOffset
mi.unknownPtrKind = si.unknownType.Kind() == reflect.Ptr
}
if si.extensionOffset.IsValid() && si.extensionType == extensionFieldsType {
mi.extensionOffset = si.extensionOffset
}
mi.coderFields = make(map[protowire.Number]*coderFieldInfo)
fields := mi.Desc.Fields()
preallocFields := make([]coderFieldInfo, fields.Len())
for i := 0; i < fields.Len(); i++ {
fd := fields.Get(i)
fs := si.fieldsByNumber[fd.Number()]
isOneof := fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic()
if isOneof {
fs = si.oneofsByName[fd.ContainingOneof().Name()]
}
ft := fs.Type
var wiretag uint64
if !fd.IsPacked() {
wiretag = protowire.EncodeTag(fd.Number(), wireTypes[fd.Kind()])
} else {
wiretag = protowire.EncodeTag(fd.Number(), protowire.BytesType)
}
var fieldOffset offset
var funcs pointerCoderFuncs
var childMessage *MessageInfo
switch {
case ft == nil:
// This never occurs for generated message types.
// It implies that a hand-crafted type has missing Go fields
// for specific protobuf message fields.
funcs = pointerCoderFuncs{
size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int {
return 0
},
marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) {
return nil, nil
},
unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) {
panic("missing Go struct field for " + string(fd.FullName()))
},
isInit: func(p pointer, f *coderFieldInfo) error {
panic("missing Go struct field for " + string(fd.FullName()))
},
merge: func(dst, src pointer, f *coderFieldInfo, opts mergeOptions) {
panic("missing Go struct field for " + string(fd.FullName()))
},
}
case isOneof:
fieldOffset = offsetOf(fs, mi.Exporter)
case fd.IsWeak():
fieldOffset = si.weakOffset
funcs = makeWeakMessageFieldCoder(fd)
default:
fieldOffset = offsetOf(fs, mi.Exporter)
childMessage, funcs = fieldCoder(fd, ft)
}
cf := &preallocFields[i]
*cf = coderFieldInfo{
num: fd.Number(),
offset: fieldOffset,
wiretag: wiretag,
ft: ft,
tagsize: protowire.SizeVarint(wiretag),
funcs: funcs,
mi: childMessage,
validation: newFieldValidationInfo(mi, si, fd, ft),
isPointer: fd.Cardinality() == protoreflect.Repeated || fd.HasPresence(),
isRequired: fd.Cardinality() == protoreflect.Required,
}
mi.orderedCoderFields = append(mi.orderedCoderFields, cf)
mi.coderFields[cf.num] = cf
}
for i, oneofs := 0, mi.Desc.Oneofs(); i < oneofs.Len(); i++ {
if od := oneofs.Get(i); !od.IsSynthetic() {
mi.initOneofFieldCoders(od, si)
}
}
if messageset.IsMessageSet(mi.Desc) {
if !mi.extensionOffset.IsValid() {
panic(fmt.Sprintf("%v: MessageSet with no extensions field", mi.Desc.FullName()))
}
if !mi.unknownOffset.IsValid() {
panic(fmt.Sprintf("%v: MessageSet with no unknown field", mi.Desc.FullName()))
}
mi.isMessageSet = true
}
sort.Slice(mi.orderedCoderFields, func(i, j int) bool {
return mi.orderedCoderFields[i].num < mi.orderedCoderFields[j].num
})
var maxDense protoreflect.FieldNumber
for _, cf := range mi.orderedCoderFields {
if cf.num >= 16 && cf.num >= 2*maxDense {
break
}
maxDense = cf.num
}
mi.denseCoderFields = make([]*coderFieldInfo, maxDense+1)
for _, cf := range mi.orderedCoderFields {
if int(cf.num) >= len(mi.denseCoderFields) {
break
}
mi.denseCoderFields[cf.num] = cf
}
// To preserve compatibility with historic wire output, marshal oneofs last.
if mi.Desc.Oneofs().Len() > 0 {
sort.Slice(mi.orderedCoderFields, func(i, j int) bool {
fi := fields.ByNumber(mi.orderedCoderFields[i].num)
fj := fields.ByNumber(mi.orderedCoderFields[j].num)
return order.LegacyFieldOrder(fi, fj)
})
}
mi.needsInitCheck = needsInitCheck(mi.Desc)
if mi.methods.Marshal == nil && mi.methods.Size == nil {
mi.methods.Flags |= protoiface.SupportMarshalDeterministic
mi.methods.Marshal = mi.marshal
mi.methods.Size = mi.size
}
if mi.methods.Unmarshal == nil {
mi.methods.Flags |= protoiface.SupportUnmarshalDiscardUnknown
mi.methods.Unmarshal = mi.unmarshal
}
if mi.methods.CheckInitialized == nil {
mi.methods.CheckInitialized = mi.checkInitialized
}
if mi.methods.Merge == nil {
mi.methods.Merge = mi.merge
}
} | 654,557 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: delete_trained_model_alias.go
path of file: ./repos/go-elasticsearch/typedapi/ml/deletetrainedmodelalias
the code of the file until where you have to start completion: // Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyr
| func NewDeleteTrainedModelAliasFunc(tp elastictransport.Interface) NewDeleteTrainedModelAlias {
return func(modelid, modelalias string) *DeleteTrainedModelAlias {
n := New(tp)
n._modelalias(modelalias)
n._modelid(modelid)
return n
}
} | 671,841 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: elasticbeanstalk.rs
path of file: ./repos/rusoto/integration_tests/tests
the code of the file until where you have to start completion: #![cfg(feature = "elasticbeanstalk")]
ext
| async fn should_describe_applications() {
let client = ElasticBeanstalkClient::new(Region::UsEast1);
let request = DescribeApplicationsMessage::default();
let result = client.describe_applications(request).await.unwrap();
println!("{:#?}", result);
} | 32,389 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: detect_face.m
path of file: ./repos/MTCNN_face_detection_alignment/code/codes/MTCNNv1
the code of the file until where you have to start completion: function [total_boxes points] = detect_face(img,minsize,PNet,RNet,ONet,threshold,fastresize,factor)
%im: input image
%minsize: minimum of faces' size
%pnet, rnet, onet: caffemodel
%threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold
%fastresize: resize img from last scale (using in high-resolution images) if fastresize==true
| function [total_boxes points] = detect_face(img,minsize,PNet,RNet,ONet,threshold,fastresize,factor)
%im: input image
%minsize: minimum of faces' size
%pnet, rnet, onet: caffemodel
%threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold
%fastresize: resize img from last scale (using in high-resolution images) if fastresize==true
factor_count=0;
total_boxes=[];
points=[];
h=size(img,1);
w=size(img,2);
minl=min([w h]);
img=single(img);
if fastresize
im_data=(single(img)-127.5)*0.0078125;
end | 409,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: chunk_processor.rs
path of file: ./repos/CYFS/src/service/chunk-manager/src
the code of the file until where you have to start completion: use async_std::io::Cursor;
use tide::{Request, Response, StatusCode};
use cyfs_base::*;
use crate::chunk_manager::{ChunkManager};
use crate::chunk_delegate;
// use crate::chunk_tx;
use crate::chunk_context::ChunkContext;
use std::io::Write;
use std::sync::
| async fn get_chunk_data_with_meta(trace:&str, chunk_manager: &ChunkManager, chunk_get_req:&cyfs_chunk::ChunkGetReq, source_peer_sec:&PrivateKey, source_device_id:&DeviceId)->BuckyResult<Response>{
// if &chunk_get_req.client_device_id!=source_device_id{
// error!("{} client peer id is not the data owner, will not resp raw data with meta, chunk id:{}", trace, chunk_get_req.chunk_id);
// return Err(BuckyError::from(BuckyErrorCode::PermissionDenied));
// }
info!("{} client peer id is the data owner, and request raw data with meta, just return, chunk id:{}", trace, chunk_get_req.chunk_id());
let chunk_data = chunk_manager.get_data(chunk_get_req.chunk_id()).await?;
info!("{} get chunk data with meta success, resp", trace);
let chunk_get_resp = cyfs_chunk::ChunkGetResp::new_raw(
&source_peer_sec,
&source_device_id,
&chunk_get_req.client_device_id(),
&chunk_get_req.chunk_id(),
chunk_data
)?;
let resp_str = chunk_get_resp.to_vec()?;
let len = resp_str.len();
let mut resp = Response::new(StatusCode::Ok);
let reader = CachedDataWithTimeout::new(chunk_get_req.chunk_id().clone(), Arc::new(resp_str), std::time::Duration::from_secs(60 * 5));
resp.set_body(http_types::Body::from_reader(reader, Some(len)));
info!("{} OK", trace);
return Ok(resp);
} | 125,107 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: environ.go
path of file: ./repos/sliver/vendor/github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1
the code of the file until where you have to start completion: package wasi_snapshot_preview1
import (
"context"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/experimental/sys"
"github.com/tetratelabs/wazero/internal/wasip1"
"github.com/tetratelabs/wazero/internal/wasm"
)
// environGet is the WASI function named EnvironGetName that reads
// environment variables.
//
// #
| func environSizesGetFn(_ context.Context, mod api.Module, params []uint64) sys.Errno {
sysCtx := mod.(*wasm.ModuleInstance).Sys
mem := mod.Memory()
resultEnvironc, resultEnvironvLen := uint32(params[0]), uint32(params[1])
// environc and environv_len offsets are not necessarily sequential, so we
// have to write them independently.
if !mem.WriteUint32Le(resultEnvironc, uint32(len(sysCtx.Environ()))) {
return sys.EFAULT
}
if !mem.WriteUint32Le(resultEnvironvLen, sysCtx.EnvironSize()) {
return sys.EFAULT
}
return 0
} | 452,367 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: 20210813141741_add_timestamps_to_chat_channels.rb
path of file: ./repos/discourse/plugins/chat/db/migrate
the code of the file until where you have to start completion: # frozen_string_literal: true
class AddTimestampsToChatChannels < ActiveRecord::Migration[6.1]
def change
add_column
| def change
add_column :chat_channels, :created_at, :timestamp
add_column :chat_channels, :updated_at, :timestamp
DB.exec("UPDATE chat_channels SET created_at = NOW() WHERE created_at IS NULL")
DB.exec("UPDATE chat_channels SET updated_at = NOW() WHERE updated_at IS NULL")
change_column_null :chat_channels, :created_at, false
change_column_null :chat_channels, :updated_at, false
end | 617,282 |
You are an expert in writing code in many different languages. Your goal is 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/rhit/src/cli
the code of the file until where you have to start completion: pub mod args;
mod help;
use {
crate::*,
args::Args,
clap::Parser,
cli_log::*,
std::path::PathBuf,
};
const DEFAULT_NGINX_LOCATION: &str = "/var/log/nginx";
static MISSING_DEFAULT_MESSAGE:
| fn print_analysis(paths: &[PathBuf], args: &args::Args) -> Result<(), RhitError> {
let mut log_base = time!("LogBase::new", LogBase::new(paths, args))?;
let printer = md::Printer::new(args, &log_base);
let base = &mut log_base;
let trend_computer = time!("Trend computer initialization", TrendComputer::new(base, args))?;
md::summary::print_summary(base, &printer);
time!("Analysis & Printing", md::print_analysis(&log_base, &printer, trend_computer.as_ref()));
Ok(())
} | 488,332 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: lib.rs
path of file: ./repos/polkadot/node/core/candidate-validation/src
the code of the file until where you have to start completion: // Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polka
| fn start(self, ctx: Context) -> SpawnedSubsystem {
if let Some(config) = self.config {
let future = run(ctx, self.metrics, self.pvf_metrics, config)
.map_err(|e| SubsystemError::with_origin("candidate-validation", e))
.boxed();
SpawnedSubsystem { name: "candidate-validation-subsystem", future }
} else {
polkadot_overseer::DummySubsystem.start(ctx)
}
} | 599,284 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: event_aggregator_test.rb
path of file: ./repos/newrelic-ruby-agent/test/new_relic/agent
the code of the file until where you have to start completion: # This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
require_relative '../../test_helper'
require_relative '../data_container_tests'
require 'new_relic
| def test_notifies_full_resets_after_buffer_reset
msg = 'TestAggregator capacity of 5 reached'
expects_logging(:debug, includes(msg))
with_config(:cap_key => 5) do
5.times { |i| @aggregator.record(i) }
end
@aggregator.reset!
expects_logging(:debug, includes(msg))
with_config(:cap_key => 5) do
5.times { |i| @aggregator.record(i) }
end
end | 239,292 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: workspaceconnections_client.go
path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/machinelearning/armmachinelearning
the code of the file until where you have to start completion: //go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armmachinelearning
import (
"context"
"errors"
"github.
| func (client *WorkspaceConnectionsClient) NewListPager(resourceGroupName string, workspaceName string, options *WorkspaceConnectionsClientListOptions) *runtime.Pager[WorkspaceConnectionsClientListResponse] {
return runtime.NewPager(runtime.PagingHandler[WorkspaceConnectionsClientListResponse]{
More: func(page WorkspaceConnectionsClientListResponse) bool {
return page.NextLink != nil && len(*page.NextLink) > 0
},
Fetcher: func(ctx context.Context, page *WorkspaceConnectionsClientListResponse) (WorkspaceConnectionsClientListResponse, error) {
ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WorkspaceConnectionsClient.NewListPager")
nextLink := ""
if page != nil {
nextLink = *page.NextLink
}
resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
return client.listCreateRequest(ctx, resourceGroupName, workspaceName, options)
}, nil)
if err != nil {
return WorkspaceConnectionsClientListResponse{}, err
}
return client.listHandleResponse(resp)
},
Tracer: client.internal.Tracer(),
})
} | 270,820 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: ipfSpotKey.m
path of file: ./repos/mtex/plotting/orientationColorKeys
the code of the file until where you have to start completion: classdef ipfSpotKey < ipfColorKey
%
% Colorizes single spots in the inverse pole figure with individual colors.
%
% Syntax
% ipfKey = ipfSpotKey
% ipfKey.inversePoleFigureDire
| function oM = ipfSpotKey(varargin)
oM = oM@ipfColorKey(varargin{:});
oM.center = get_option(varargin,'center',Miller(0,0,1,oM.CS1));
oM.CS1 = oM.center.CS;
oM.color = get_option(varargin,'color',[1 0 0]);
oM.psi = get_option(varargin,'S2Kernel',...
S2DeLaValleePoussinKernel('halfwidth',get_option(varargin,'halfwidth',10*degree)));
oM.dirMap = directionColorKey(oM.CS1,'dir2color',@(varargin) oM.dir2color(varargin{:}));
end | 606,892 |
You are an expert in writing code in many different languages. Your goal is 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/advisor/armadvisor
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.
/
| func PossibleCPUThresholdValues() []CPUThreshold {
return []CPUThreshold{
CPUThresholdFifteen,
CPUThresholdFive,
CPUThresholdTen,
CPUThresholdTwenty,
}
} | 266,461 |
You are an expert in writing code in many different languages. Your goal is 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_network.rs
path of file: ./repos/aws-sdk-rust/sdk/managedblockchain/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 `CreateNetwork`.
#[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)]
#[non_exhaustive]
pub struct CreateNetwork;
impl CreateNetwork {
/// Creates a new `CreateNetwork`
pub fn new() -> Self {
Self
}
pub(crate) async fn orchestrate(
runtime_plugins: &::aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins,
input: crate::operation::create_network::CreateNetworkInput,
) -> ::std::result::Result<
crate::operation::create_network::CreateNetworkOutput,
::aws_smithy_runtime_api::client::re
| fn config(&self) -> ::std::option::Option<::aws_smithy_types::config_bag::FrozenLayer> {
let mut cfg = ::aws_smithy_types::config_bag::Layer::new("CreateNetwork");
cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedRequestSerializer::new(
CreateNetworkRequestSerializer,
));
cfg.store_put(::aws_smithy_runtime_api::client::ser_de::SharedResponseDeserializer::new(
CreateNetworkResponseDeserializer,
));
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(
"CreateNetwork",
"managedblockchain",
));
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,551 |
You are an expert in writing code in many different languages. Your goal is 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_ListBotResourceGenerations.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.c
| func (p *ListBotResourceGenerationsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListBotResourceGenerationsOutput, error) {
if !p.HasMorePages() {
return nil, fmt.Errorf("no more pages available")
}
params := *p.params
params.NextToken = p.nextToken
var limit *int32
if p.options.Limit > 0 {
limit = &p.options.Limit
}
params.MaxResults = limit
result, err := p.client.ListBotResourceGenerations(ctx, ¶ms, optFns...)
if err != nil {
return nil, err
}
p.firstPage = false
prevToken := p.nextToken
p.nextToken = result.NextToken
if p.options.StopOnDuplicateToken &&
prevToken != nil &&
p.nextToken != nil &&
*prevToken == *p.nextToken {
p.nextToken = nil
}
return result, nil
} | 222,644 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: csum.m
path of file: ./repos/bnt/BNT/examples/static/Zoubin
the code of the file until where you have to start completion: % column sum
% function Z=csum(X)
function Z=csum(X)
N=length(X(:
| function Z=csum(X)
function Z=csum(X)
N=length(X(:,1));
if (N>1)
Z=sum(X);
else
Z=X;
end | 250,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: main_with_use_of_moved_value_ctx.rs
path of file: ./repos/Rust-Full-Stack/bots/teloxide/src/get
the code of the file until where you have to start completion: // Use nightly to make this work.
// $ rustup update nightly
// $ rustup override set nightly
#![feature(async_closure)]
// https://github.com/rust-lang/rustfmt
// $cargo fmt
// $cargo fmt -- --check
// $cargo watch -x '
| async fn run() {
teloxide::enable_logging!();
log::info!("Starting reqwest proxy GET bot!");
let bot = Bot::from_env();
Dispatcher::new(bot)
.messages_handler(|rx: DispatcherHandlerRx<Message>| {
rx.text_messages().for_each_concurrent(None, |(ctx, target_webpage)| async move {
let resp = reqwest::get(&target_webpage)
.await;
match resp {
Ok(body) => {
let body_text_async = body.text().await
.map(async move |payload| {
println!("Payload(body) is {:#?}", &payload);
// Should handle when payload(body) is too long.
// Handle send().await part manually instead of log_on_error whenever it is necessary.
// Ignore incompatible return value.
let _ = ctx.answer(payload).send().await
.map(async move |_| {
println!("The body was sent safely to the user.");
})
.map_err(async move |e| {
println!("Error from API limit of Telegram is {:#?}", e);
ctx.answer("There was an error from Telegram API. The body part of your target maybe too long.").send().await.log_on_error().await;
});
})
.map_err(async move |e| {
println!("Error from parsing body to text is {:#?}", e);
ctx.answer("There was an error parsing the body of your target webpage.").send().await.log_on_error().await;
});
}
Err(e) => {
println!("Error from GET taget_webpage is {:#?}", e);
ctx.answer("There was an error requesting your target webpage. Verify you entered the correct data.").send().await.log_on_error().await;
}
}
})
})
.dispatch()
.await;
} | 484,520 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: enums.go
path of file: ./repos/aws-sdk-go-v2/service/entityresolution/types
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package types
type AttributeMatchingModel string
// Enum values for AttributeMatchingModel
const (
AttributeMatchingModelOneToOne AttributeMatchingModel = "ONE_TO_ONE"
AttributeMatchin
| func (SchemaAttributeType) Values() []SchemaAttributeType {
return []SchemaAttributeType{
"NAME",
"NAME_FIRST",
"NAME_MIDDLE",
"NAME_LAST",
"ADDRESS",
"ADDRESS_STREET1",
"ADDRESS_STREET2",
"ADDRESS_STREET3",
"ADDRESS_CITY",
"ADDRESS_STATE",
"ADDRESS_COUNTRY",
"ADDRESS_POSTALCODE",
"PHONE",
"PHONE_NUMBER",
"PHONE_COUNTRYCODE",
"EMAIL_ADDRESS",
"UNIQUE_ID",
"DATE",
"STRING",
"PROVIDER_ID",
}
} | 221,623 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: search-request-sort_44dfac5bc3131014e2c6bb1ebc76b33d_test.go
path of file: ./repos/go-elasticsearch/.doc/examples/src
the code of the file until where you have to start completion: // Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You
| func Test_search_request_sort_44dfac5bc3131014e2c6bb1ebc76b33d(t *testing.T) {
es, _ := elasticsearch.NewDefaultClient()
// tag:44dfac5bc3131014e2c6bb1ebc76b33d[]
res, err := es.Indices.Create(
"index_double",
es.Indices.Create.WithBody(strings.NewReader(`{
"mappings": {
"properties": {
"field": {
"type": "double"
}
}
}
}`)),
)
fmt.Println(res, err)
if err != nil { // SKIP
t.Fatalf("Error getting the response: %s", err) // SKIP
} // SKIP
defer res.Body.Close() // SKIP
// end:44dfac5bc3131014e2c6bb1ebc76b33d[]
} | 669,548 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: list_dataset_groups.rs
path of file: ./repos/aws-sdk-rust/sdk/personalize/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 `ListDatasetGroups`.
#[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)]
#[non_exhaustive]
pub struct ListDatasetGroups;
impl ListDatasetGroups {
/// Creates a new `ListDatasetGroups`
pub fn new() -> Self {
Self
}
pub(crate) async fn orchestrat
| fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
match self {
Self::InvalidNextTokenException(_inner) => _inner.fmt(f),
Self::Unhandled(_inner) => {
if let ::std::option::Option::Some(code) = ::aws_smithy_types::error::metadata::ProvideErrorMetadata::code(self) {
write!(f, "unhandled error ({code})")
} else {
f.write_str("unhandled error")
}
}
}
} | 803,281 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: admin.go
path of file: ./repos/slack
the code of the file until where you have to start completion: package slack
import (
"context"
"fmt"
"net/url"
"strings"
)
func (api *Client) adminRequest(ctx context.Context, method string, teamName string, values url.Values) error {
resp := &SlackResponse{}
err := parseAdminResponse(ctx, api.httpclient, method, teamName, values, resp, api)
| func (api *Client) InviteGuestContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error {
values := url.Values{
"email": {emailAddress},
"channels": {channel},
"first_name": {firstName},
"last_name": {lastName},
"ultra_restricted": {"1"},
"token": {api.token},
"resend": {"true"},
"set_active": {"true"},
"_attempts": {"1"},
}
err := api.adminRequest(ctx, "invite", teamName, values)
if err != nil {
return fmt.Errorf("Failed to invite single-channel guest: %s", err)
}
return nil
} | 558,541 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: localsdk_test.go
path of file: ./repos/agones/pkg/sdkserver
the code of the file until where you have to start completion: // Copyright 2018 Google LLC All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specif
| func TestLocalSDKServerPlayerConnectAndDisconnectWithoutPlayerTracking(t *testing.T) {
t.Parallel()
runtime.FeatureTestMutex.Lock()
defer runtime.FeatureTestMutex.Unlock()
assert.NoError(t, runtime.ParseFeatures(string(runtime.FeaturePlayerTracking)+"=false"))
l, err := NewLocalSDKServer("", "")
assert.Nil(t, err)
e := &alpha.Empty{}
capacity, err := l.GetPlayerCapacity(context.Background(), e)
assert.Nil(t, capacity)
assert.Error(t, err)
count, err := l.GetPlayerCount(context.Background(), e)
assert.Error(t, err)
assert.Nil(t, count)
list, err := l.GetConnectedPlayers(context.Background(), e)
assert.Error(t, err)
assert.Nil(t, list)
id := &alpha.PlayerID{PlayerID: "test-player"}
ok, err := l.PlayerConnect(context.Background(), id)
assert.Error(t, err)
assert.False(t, ok.Bool)
ok, err = l.IsPlayerConnected(context.Background(), id)
assert.Error(t, err)
assert.False(t, ok.Bool)
ok, err = l.PlayerDisconnect(context.Background(), id)
assert.Error(t, err)
assert.False(t, ok.Bool)
} | 447,564 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: element_from.rs
path of file: ./repos/mybatis/mybatis-macro/src
the code of the file until where you have to start completion: use crate::html_loader::Element;
use crate::py_sql::NodeType;
use std::collections::HashMap;
pub fn a
| pub fn as_elements(arg: Vec<NodeType>) -> Vec<Element> {
let mut res = vec![];
for x in arg {
res.push(Element::from(x));
}
res
} | 237,042 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: cronjob.go
path of file: ./repos/agones/vendor/k8s.io/client-go/listers/batch/v1beta1
the code of the file until where you have to start completion: /*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain
| func (s cronJobNamespaceLister) Get(name string) (*v1beta1.CronJob, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1beta1.Resource("cronjob"), name)
}
return obj.(*v1beta1.CronJob), nil
} | 446,256 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: find_extrema.m
path of file: ./repos/brainstorm3/external/other
the code of the file until where you have to start completion: function [xmax,imax,xmin,imin] = find_extrema(x)
% Ge
| function at which the function takes a largest value
% (maximum) or smallest value (minimum), either within a given
% neighbourhood (local extrema) or on the function domain in its entirety
% (global extrema).
%
% AUTHORS:
% Carlos Adrián Vargas Aguilera, nubeobscura@hotmail.com, 2004
% Physical Oceanography MS candidate
% UNIVERSIDAD DE GUADALAJARA
xmax = [];
imax = [];
xmin = [];
imin = [];
% Vector input?
Nt = numel(x);
if Nt ~= length(x)
error('Entry must be a vector.')
end | 151,464 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: configuration.rs
path of file: ./repos/bevy_xpbd/src/plugins/debug
the code of the file until where you have to start completion: use crate::prelude::*;
use bevy::prelude::*
| pub fn none() -> Self {
Self {
axis_lengths: None,
aabb_color: None,
collider_color: None,
sleeping_color_multiplier: None,
contact_point_color: None,
contact_normal_color: None,
contact_normal_scale: ContactGizmoScale::default(),
joint_anchor_color: None,
joint_separation_color: None,
raycast_color: None,
raycast_point_color: None,
raycast_normal_color: None,
shapecast_color: None,
shapecast_shape_color: None,
shapecast_point_color: None,
shapecast_normal_color: None,
hide_meshes: false,
}
} | 534,589 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: large_tree_digital_object.rb
path of file: ./repos/archivesspace/backend/app/model
the code of the file until where you have to start completion: class LargeTreeDigitalObject
def root(response, root_record)
response['digital_object_type'] = root_record.digital_object_type
response['file_uri_summary'] = root_record.file_version.map {|file_version|
file_version[:file_uri]
}.join(", ")
response
end
def node(response, node_record)
response
end
def waypoint(response, record_ids)
file_uri_by_digital_object_component = {}
DigitalObjectComponent
.filter(:digital_object_component__id => record_ids)
.where(Sequel.~(:digital_object_component__label => nil))
.select(Sequel.as(:digital_object_component__id, :id),
Sequel.as(:digital_object_component__label, :label))
.each do |row|
id = row[:id]
result_for_record = response.fetch(record_ids.index(id))
result_for_record['label'] = row[:label]
end
ASDate
.left_join(Sequel.as(:enumeration_value, :date_type), :id => :date__date_type_id)
.left_join(Sequel.as(:enumeration_value, :date_label), :id => :date__label_id)
.filter(:digital_object_component_id => record_ids)
.select(:digital_object_component_id,
Sequel.as(:date_type__value, :type),
Sequel.as(:date_label__value, :label),
:expression,
:begin,
:end)
.each do |row|
id = row[:digital_object_component_id]
result_for_record = response.fetch(record_ids.index(id))
result_for_record['dates'] ||= []
date_data = {}
date_data['type'] = row[:type] if row[:type]
date_data['label'] = row[:label] if row[:label]
date_data['expression'] = row[:expression]
| def waypoint(response, record_ids)
file_uri_by_digital_object_component = {}
DigitalObjectComponent
.filter(:digital_object_component__id => record_ids)
.where(Sequel.~(:digital_object_component__label => nil))
.select(Sequel.as(:digital_object_component__id, :id),
Sequel.as(:digital_object_component__label, :label))
.each do |row|
id = row[:id]
result_for_record = response.fetch(record_ids.index(id))
result_for_record['label'] = row[:label]
end
ASDate
.left_join(Sequel.as(:enumeration_value, :date_type), :id => :date__date_type_id)
.left_join(Sequel.as(:enumeration_value, :date_label), :id => :date__label_id)
.filter(:digital_object_component_id => record_ids)
.select(:digital_object_component_id,
Sequel.as(:date_type__value, :type),
Sequel.as(:date_label__value, :label),
:expression,
:begin,
:end)
.each do |row|
id = row[:digital_object_component_id]
result_for_record = response.fetch(record_ids.index(id))
result_for_record['dates'] ||= []
date_data = {}
date_data['type'] = row[:type] if row[:type]
date_data['label'] = row[:label] if row[:label]
date_data['expression'] = row[:expression] if row[:expression]
date_data['begin'] = row[:begin] if row[:begin]
date_data['end'] = row[:end] if row[:end]
result_for_record['dates'] << date_data
end
FileVersion.filter(:digital_object_component_id => record_ids)
.select(:digital_object_component_id,
:file_uri)
.each do |row|
id = row[:digital_object_component_id]
file_uri_by_digital_object_component[id] ||= []
file_uri_by_digital_object_component[id] << row[:file_uri]
end
file_uri_by_digital_object_component.each do |id, file_uris|
result_for_record = response.fetch(record_ids.index(id))
result_for_record['file_uri_summary'] = file_uris.compact.join(", ")
end
response
end | 583,839 |
You are an expert in writing code in many different languages. Your goal is 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/materialize/src/rocksdb/src
the code of the file until where you have to start completion: // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
/
| pub async fn close(self) -> Result<(), Error> {
let (tx, rx) = oneshot::channel();
self.tx
.send(Command::Shutdown { done_sender: tx })
.await
.map_err(|_| Error::RocksDBThreadGoneAway)?;
let _ = rx.await;
Ok(())
} | 370,534 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: corrdim.m
path of file: ./repos/hctsa/Toolboxes/OpenTSTOOL/tstoolbox/@signal
the code of the file until where you have to start completion: function rs = corrdim(s, bins)
%tstoolbox/@signal/corrdim
% Syntax:
% * rs = corrdim(s, bins)
%
| function rs = corrdim(s, bins)
%tstoolbox/@signal/corrdim
% Syntax:
% * rs = corrdim(s, bins)
%
% Input arguments:
% * s - data points (row vectors)
% * bins - maximal number of partition per axis (optional)
%
% Compute the correlation dimension of a time-delay reconstructed
% timeseries s for dimensions from 1 to D, where D is the dimension of
% the input vectors using boxcounting approach. The default number of
% bins is 100.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt
narginchk(1,2);
if ndim(s) ~= 2
error('Signal must contain vector data');
end | 503,115 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: java_tester.rb
path of file: ./repos/metasploit-framework/test/modules/exploits/test
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
##
require 'rex'
class MetasploitModule < Msf::Exploit::Remote
Rank = ManualRanking
def initialize(info = {})
super(
update_info(
info,
'Name' => 'Exec',
'Description' => %q{ },
'License' => MSF_LICENSE,
'Author' => [ 'egypt' ],
'References' => [ ],
| def initialize(info = {})
super(
update_info(
info,
'Name' => 'Exec',
'Description' => %q{ },
'License' => MSF_LICENSE,
'Author' => [ 'egypt' ],
'References' => [ ],
'Platform' => [ 'java', 'linux' ],
'Arch' => ARCH_JAVA,
'Payload' => { 'Space' => 20480, 'BadChars' => '', 'DisableNops' => true },
'Targets' => [
[
'Generic (Java Payload)', {
'Arch' => ARCH_JAVA,
'Platform' => 'java'
}
],
[
'Linux', {
'Arch' => ARCH_X86,
'Platform' => 'linux'
}
],
],
'DefaultTarget' => 0
)
)
end | 739,530 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: normalizePivots.m
path of file: ./repos/chebfun/@separableApprox
the code of the file until where you have to start completion: function F = normalizePivots(F)
%NORMALIZEPIVOTS Scale rows and cols of a SEPARABLEAPPROX so that all pivots are 1.
%
% Additionally, the norm of the kth row and column will be the same.
| function F = normalizePivots(F)
%NORMALIZEPIVOTS Scale rows and cols of a SEPARABLEAPPROX so that all pivots are 1.
%
% Additionally, the norm of the kth row and column will be the same.
% Copyright 2017 by The University of Oxford and The Chebfun2 Developers.
% See http://www.chebfun.org/ for Chebfun2 information.
% TODO: Document
% TODO: is this useful?
F = normalizeRowsAndCols(F);
d = F.pivotValues(:).';
s = sign(d);
sqrtp = sqrt(abs(d));
F.cols = F.cols./(s.*sqrtp);
F.rows = F.rows./sqrtp;
F.pivotValues = ones(1, length(d));
end | 396,048 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: utils_test.go
path of file: ./repos/storj/private/date
the code of the file until where you have to start completion: // Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package date_test
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"storj.io/storj/private/date"
)
func TestMonthBoundary(t *testing.T) {
now := time.Now()
start, end := date.MonthBoundary(now)
assert.Equal(t, start, time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()))
assert.Equal(t, end, time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, -1, now.Location()))
}
func TestDayBoundary(t *testing.T) {
now := time.Now()
start, end := date.DayBoundary(now)
assert.Equal(t, start, time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()))
assert.Equal(t, end, time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, -1, now.Location()))
}
func TestPeriodToTime(t *t
| func TestMonthsBetweenDates(t *testing.T) {
testCases := [...]struct {
from time.Time
to time.Time
monthsAmount int
}{
{time.Date(2020, 2, 13, 0, 0, 0, 0, &time.Location{}), time.Date(2020, 05, 13, 0, 0, 0, 0, &time.Location{}), 3},
{time.Date(2015, 7, 30, 0, 0, 0, 0, &time.Location{}), time.Date(2020, 05, 13, 0, 0, 0, 0, &time.Location{}), 58},
{time.Date(2017, 1, 28, 0, 0, 0, 0, &time.Location{}), time.Date(2020, 05, 13, 0, 0, 0, 0, &time.Location{}), 40},
{time.Date(2016, 11, 1, 0, 0, 0, 0, &time.Location{}), time.Date(2020, 05, 13, 0, 0, 0, 0, &time.Location{}), 42},
{time.Date(2019, 4, 17, 0, 0, 0, 0, &time.Location{}), time.Date(2020, 05, 13, 0, 0, 0, 0, &time.Location{}), 13},
{time.Date(2018, 9, 11, 0, 0, 0, 0, &time.Location{}), time.Date(2020, 05, 13, 0, 0, 0, 0, &time.Location{}), 20},
}
for _, tc := range testCases {
monthDiff := date.MonthsBetweenDates(tc.from, tc.to)
require.Equal(t, monthDiff, tc.monthsAmount)
}
} | 635,363 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: fail_if_no_examples_spec.rb
path of file: ./repos/rspec-core/spec/integration
the code of the file until where you have to start completion: require 'support/aruba_support'
RSpec.describe 'Fail if no examples' do
inc
| def no_examples_custom_failure_exit_code(fail_if_no_examples)
"
RSpec.configure do |c|
c.fail_if_no_examples = #{fail_if_no_examples}
c.failure_exit_code = 15
end
RSpec.describe 'something' do
end
"
end | 160,093 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: dashboard_send_event.go
path of file: ./repos/octant/pkg/plugin/javascript
the code of the file until where you have to start completion: /*
* Copyright (c) 2020 the Octant contributors. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package javascript
import (
"context"
"fmt"
"github.com/dop251/goja"
ocontext "github.com/vmware-tanzu/octant/internal/context"
"github.com/vmware-tanzu/octant/internal/octant"
"github.com/vmware-tanzu/octant/pkg/action"
"github.com/vmware-tanzu/octant/pkg/event"
)
// DashboardList is a function that lists objects by key.
type DashboardSendEvent struct {
WebsocketClientManager event.WSClientGetter
}
var _ octant.DashboardClientFunction = &DashboardSendEvent{}
// NewDashboardSendEvent create
| func (d *DashboardSendEvent) Call(ctx context.Context, vm *goja.Runtime) func(c goja.FunctionCall) goja.Value {
// clientID string, event EventType, payload action.Payload
return func(c goja.FunctionCall) goja.Value {
clientID := c.Argument(0).String()
if clientID == "" {
panic(panicMessage(vm, fmt.Errorf("clientID is empty"), ""))
}
eventType := event.EventType(c.Argument(1).String())
if eventType == "" {
panic(panicMessage(vm, fmt.Errorf("eventType is empty"), ""))
}
var payload action.Payload
obj := c.Argument(2).ToObject(vm)
// This will never error since &key is a pointer to a type.
_ = vm.ExportTo(obj, &payload)
event := event.CreateEvent(eventType, payload)
if d.WebsocketClientManager == nil {
panic(panicMessage(vm, fmt.Errorf("websocket client manager is nil"), ""))
}
sender := d.WebsocketClientManager.Get(clientID)
if sender == nil {
clientID := ocontext.ClientStateFrom(ctx).ClientID
panic(panicMessage(vm, fmt.Errorf("unable to find ws client %s", clientID), ""))
}
sender.Send(event)
return goja.Undefined()
}
} | 198,921 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: mandelbrot.rb
path of file: ./repos/truffleruby/test/truffle/metrics
the code of the file until where you have to start completion: # Copyright (c) 2016, 2024 Oracle and/or its affiliates. All rights reserved. This
# code is released under a tri EPL/GPL/LGPL license. You can use it,
# redistribute it and/or modify it under the terms of the:
#
# Eclipse Public License version 2.0, or
# GNU General Public License version 2, or
# GNU Lesser General Public
| def mandelbrot(size)
sum = 0
byte_acc = 0
bit_num = 0
y = 0
while y < size
ci = (2.0*y/size)-1.0
x = 0
while x < size
zrzr = zr = 0.0
zizi = zi = 0.0
cr = (2.0*x/size)-1.5
escape = 0b1
z = 0
while z < 50
tr = zrzr - zizi + cr
ti = 2.0*zr*zi + ci
zr = tr
zi = ti
# preserve recalculation
zrzr = zr*zr
zizi = zi*zi
if zrzr+zizi > 4.0
escape = 0b0
break
end | 177,490 |
You are an expert in writing code in many different languages. Your goal is 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/cloudwatch/src/operation/delete_alarms
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,
}
} | 761,264 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: undefined_variable_detection.rs
path of file: ./repos/solang/tests
the code of the file until where you have to start completion: // SPDX-License-Identifier: Apache-2.0
use solang::codegen::{codegen, OptimizationLevel, Options};
use solang::file_resolver::FileResolver;
use solang::sema::ast::Diagnostic;
use solang::sema::ast::Namespace;
use solang::{parse_and_resolve, Target};
use std::ffi::OsStr;
fn parse_and_codegen(src: &'static str) -> Namespace {
let mut cache = FileResolver::default();
cache.set_file_contents("test.sol", src.to_string());
let mut ns = parse_and_resolve(
OsStr::new("test.sol"),
&mut cache,
Target::default_polkadot(),
);
let opt = Options {
dead_storage: false,
constant_folding: false,
strength_reduce: false,
vector_to_slice: false,
common_subexpression_elimination: false,
opt_level: OptimizationLevel::Default,
generate_debug_information:
| fn while_loop() {
let file = r#"
contract testing {
function test(int x) public pure returns (string) {
string s;
while(x > 0){
s = "testing_string";
x--;
}
return s;
}
}
"#;
let ns = parse_and_codegen(file);
let errors = ns.diagnostics.errors();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].message, "Variable 's' is undefined");
assert_eq!(errors[0].notes.len(), 1);
assert_eq!(
errors[0].notes[0].message,
"Variable read before being defined"
);
let file = r#"
contract testing {
function test(int x) public pure returns (string) {
string s;
while(x > 0){
s = "testing_string";
x--;
}
if(x < 0) {
s = "another_test";
}
return s;
}
}
"#;
let ns = parse_and_codegen(file);
let errors = ns.diagnostics.errors();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].message, "Variable 's' is undefined");
assert_eq!(errors[0].notes.len(), 1);
assert_eq!(
errors[0].notes[0].message,
"Variable read before being defined"
);
let file = r#"
contract testing {
function test(int x) public pure returns (string) {
string s;
while(x > 0){
s = "testing_string";
x--;
}
if(x < 0) {
s = "another_test";
} else {
s = "should_work";
}
return s;
}
}
"#;
let ns = parse_and_codegen(file);
let errors = ns.diagnostics.errors();
assert_eq!(errors.len(), 0);
} | 539,532 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: headers.rs
path of file: ./repos/tungstenite-rs/src/handshake
the code of the file until where you have to start completion: //! HTTP Request and response header handling.
use http::header::{HeaderMap, H
| fn headers_incomplete() {
const DATA: &[u8] = b"Host: foo.com\r\n\
Connection: Upgrade\r\n\
Upgrade: websocket\r\n";
let hdr = HeaderMap::try_parse(DATA).unwrap();
assert!(hdr.is_none());
} | 82,783 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: from_polar.rs
path of file: ./repos/oso/languages/rust/oso/src/host
the code of the file until where you have to start completion: #![allow(clippy::many_single_char_names, clippy::type_complexity)]
//! Trait and implementations of `FromPolar` for converting from
//! Polar types back to Rust types.
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::hash::Hash;
use impl_trait_for_tuples::*;
use super::class::
| fn from_polar(val: PolarValue) -> crate::Result<Self> {
// if the value is a Option<PolarValue>, convert from PolarValue
if let PolarValue::Instance(ref instance) = &val {
if let Ok(opt) = instance.downcast::<Option<PolarValue>>(None) {
return opt.clone().map(T::from_polar).transpose();
}
}
T::from_polar(val).map(Some)
} | 57,455 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: internal_stanza.rb
path of file: ./repos/brew/Library/Homebrew/cask/cmd
the code of the file until where you have to start completion: module Cask
class Cmd
class InternalStanza < AbstractInternalCommand
# Syntax
#
# brew cask _stanza <stanza_name> [ --quiet ] [ --table | --yaml ] [
| def initialize(*)
super
raise ArgumentError, "No stanza given." if args.empty?
@stanza = args.shift.to_sym
@format = :to_yaml if yaml?
return if DSL::DSL_METHODS.include?(stanza)
raise ArgumentError,
<<~EOS
Unknown/unsupported stanza: '#{stanza}'
Check Cask reference for supported stanzas.
EOS
end | 18,212 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: dataset.go
path of file: ./repos/google-cloud-go/bigquery
the code of the file until where you have to start completion: // Copyright 2015 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Licen
| func (e *AccessEntry) toBQ() (*bq.DatasetAccess, error) {
q := &bq.DatasetAccess{Role: string(e.Role)}
switch e.EntityType {
case DomainEntity:
q.Domain = e.Entity
case GroupEmailEntity:
q.GroupByEmail = e.Entity
case UserEmailEntity:
q.UserByEmail = e.Entity
case SpecialGroupEntity:
q.SpecialGroup = e.Entity
case ViewEntity:
q.View = e.View.toBQ()
case IAMMemberEntity:
q.IamMember = e.Entity
case RoutineEntity:
q.Routine = e.Routine.toBQ()
case DatasetEntity:
q.Dataset = e.Dataset.toBQ()
default:
return nil, fmt.Errorf("bigquery: unknown entity type %d", e.EntityType)
}
return q, nil
} | 275,306 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: timestamping.rs
path of file: ./repos/exonum/exonum-node/src/sandbox
the code of the file until where you have to start completion: // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not
| pub fn with_keypair(data_size: usize, keypair: KeyPair) -> Self {
let rand = thread_rng();
Self {
rand,
data_size,
keypair,
instance_id: TimestampingService::ID,
}
} | 4,038 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: debug.rs
path of file: ./repos/parity-ethereum/rpc/src/v1/tests/mocked
the code of the file until where you have to start completion: // Copyright 2015-2020
| fn io() -> IoHandler {
let client = Arc::new(TestBlockChainClient::new());
let mut io = IoHandler::new();
io.extend_with(DebugClient::new(client).to_delegate());
io
} | 73,615 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: _db_cluster_quota_exceeded_fault.rs
path of file: ./repos/aws-sdk-rust/sdk/rds/src/types/error
the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NO
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
::std::write!(f, "DbClusterQuotaExceededFault [DBClusterQuotaExceededFault]")?;
if let ::std::option::Option::Some(inner_1) = &self.message {
{
::std::write!(f, ": {}", inner_1)?;
}
}
Ok(())
} | 772,768 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: drop_item_menu.rs
path of file: ./repos/rustrogueliketutorial/chapter-72-textlayers/src/gui
the code of the file until where you have to start completion: use rltk::prelude::*;
use specs::prelude::*;
use crate::{State, InBackpack};
use super::{get_item_display_name, ItemMenuResult, item_result_menu};
pub fn drop_item_menu(gs : &mut State, ctx : &mut Rltk) -> (ItemMenuResult, Option<Entity>) {
let mut draw_batch = DrawBatch::new();
let player_entity = gs.ecs.fetch::<Entity>();
let backpack = gs.ecs.read_storage::<InBackpack>();
let entities = gs.ecs.entities();
let mut items : Vec<(Entity, String)> = Vec::new();
(&entities, &backpack).join()
.filter(|ite
| pub fn drop_item_menu(gs : &mut State, ctx : &mut Rltk) -> (ItemMenuResult, Option<Entity>) {
let mut draw_batch = DrawBatch::new();
let player_entity = gs.ecs.fetch::<Entity>();
let backpack = gs.ecs.read_storage::<InBackpack>();
let entities = gs.ecs.entities();
let mut items : Vec<(Entity, String)> = Vec::new();
(&entities, &backpack).join()
.filter(|item| item.1.owner == *player_entity )
.for_each(|item| {
items.push((item.0, get_item_display_name(&gs.ecs, item.0)))
});
let result = item_result_menu(
&mut draw_batch,
"Drop which item?",
items.len(),
&items,
ctx.key
);
draw_batch.submit(6000);
result
} | 36,957 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: user_import_files_controller.rb
path of file: ./repos/enju_leaf/app/controllers
the code of the file until where you have to start completion: class UserImportFilesController < Application
| def destroy
@user_import_file.destroy
respond_to do |format|
format.html { redirect_to(user_import_files_url) }
format.json { head :no_content }
end
end | 448,462 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: transposition.rs
path of file: ./repos/Rust/src/ciphers
the code of the file until where you have to start completion: //! Transposition Cipher
//!
//! The Transposition Cipher is a method of encryption by which a message is shifted
//! according to a regular system, so that the ciphertext is a rearrangement of the
//! original message. The most commonly referred to Transposition Cipher is the
//! COLUMNAR TRANSPOSITION cipher, which is demonstrated below.
use std::ops::Range;
/// Encrypts or decrypts a message, using multiple keys. The
/// encryption is based on the columnar transposition method.
pub fn transposition(decrypt_mode: bool, msg: &str, key: &str) -> String {
let key_uppercase: String = key.to_uppercase();
let mut cipher_msg: String = msg.to_string();
let keys: Vec<&str> = match decrypt_mode {
false => key_uppercase.split_whitespace().collect(),
true => key_uppercase.split_whitespace().rev().collect(),
};
for cipher_key in keys.iter() {
let mut key_order: Vec<usize> = Vec::new();
let mut counter: u8 = 0;
// Removes any non-alphabet characters from 'msg'
cipher_msg = cipher_msg
.to_uppercase()
.chars()
.filter(|&c| c.is_ascii_alphabetic())
| fn decrypt(mut msg: String, key_order: Vec<usize>) -> String {
let mut decrypted_msg: String = String::from("");
let mut decrypted_vec: Vec<String> = Vec::new();
let mut indexed_vec: Vec<(usize, String)> = Vec::new();
let msg_len: usize = msg.len();
let key_len: usize = key_order.len();
// Split the message into columns, determined by 'message length divided by keyword length'.
// Some columns are larger by '+1', where the prior calculation leaves a remainder.
let split_size: usize = (msg_len as f64 / key_len as f64) as usize;
let msg_mod: usize = msg_len % key_len;
let mut counter: usize = msg_mod;
let mut key_split: Vec<usize> = key_order.clone();
let (split_large, split_small) = key_split.split_at_mut(msg_mod);
split_large.sort_unstable();
split_small.sort_unstable();
split_large.iter_mut().rev().for_each(|key_index| {
counter -= 1;
let range: Range<usize> =
((*key_index * split_size) + counter)..(((*key_index + 1) * split_size) + counter + 1);
let slice: String = msg[range.clone()].to_string();
indexed_vec.push((*key_index, slice));
msg.replace_range(range, "");
});
split_small.iter_mut().for_each(|key_index| {
let (slice, rest_of_msg) = msg.split_at(split_size);
indexed_vec.push((*key_index, (slice.to_string())));
msg = rest_of_msg.to_string();
});
indexed_vec.sort();
key_order.into_iter().for_each(|key| {
if let Some((_, column)) = indexed_vec.iter().find(|(key_index, _)| key_index == &key) {
decrypted_vec.push(column.to_string());
}
});
// Concatenate the columns into a string, determined by the
// alphabetical order of the keyword's characters
for _ in 0..split_size {
decrypted_vec.iter_mut().for_each(|column| {
decrypted_msg.push(column.remove(0));
})
}
if !decrypted_vec.is_empty() {
decrypted_vec.into_iter().for_each(|chars| {
decrypted_msg.push_str(&chars);
})
}
decrypted_msg
} | 368,759 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: ft_write_spike.m
path of file: ./repos/bspm/thirdparty/spm12/external/fieldtrip/fileio
the code of the file until where you have to start completion: function ft_write_spike(filename, spike, varargin)
% FT_WRITE_SPIKE writes animal electrophysiology spike timestamps and/or waveforms
% to file
%
% Use as
% ft_write_spike(filename, spike, ...)
%
% Additional options should be specified in key-value pairs and can be
% 'dataformat' string, see below
% 'fsample' sampling frequency of the waveforms
% 'chanindx' index of selected channels
% 'TimeStampPerSample' number of timestamps per sample
%
% The supported dataformats are
% neuralynx_nse
% neuralynx_nts
% plexon_nex
% matlab
%
% See also FT_READ_SPIKE
% Copyright (C) 2007-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
| function ft_write_spike(filename, spike, varargin)
% FT_WRITE_SPIKE writes animal electrophysiology spike timestamps and/or waveforms
% to file
%
% Use as
% ft_write_spike(filename, spike, ...)
%
% Additional options should be specified in key-value pairs and can be
% 'dataformat' string, see below
% 'fsample' sampling frequency of the waveforms
% 'chanindx' index of selected channels
% 'TimeStampPerSample' number of timestamps per sample
%
% The supported dataformats are
% neuralynx_nse
% neuralynx_nts
% plexon_nex
% matlab
%
% See also FT_READ_SPIKE
% Copyright (C) 2007-2012, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$
% get the options
dataformat = ft_getopt(varargin, 'dataformat');
fsample = ft_getopt(varargin, 'fsample');
chanindx = ft_getopt(varargin, 'chanindx');
% FIXME rename the option TimeStampPerSample to ftimestamp, c.f. fsample
TimeStampPerSample = keyval('TimeStampPerSample', varargin);
% optionally select channels
if ~isempty(chanindx)
spike.label = spike.label(chanindx);
spike.waveform = spike.waveform(chanindx);
spike.timestamp = spike.timestamp(chanindx);
end | 518,132 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: system_snapshots.rs
path of file: ./repos/cube/rust/cubestore/cubestore/src/queryplanner/info_schema
the code of the file until where you have to start completion: use crate::metastore::snapshot_info::SnapshotInfo;
use crate::queryplanner::{InfoSchemaTableDef, InfoSchemaTableDefContext};
use crate::CubeError;
use arrow::array::{ArrayRef, BooleanArray, StringArray, TimestampNanosecondArray};
use arrow::datatypes::{DataType, Field, TimeUnit};
use async_trait::async_trait;
use std::sync::Arc;
pu
| fn columns(&self) -> Vec<Box<dyn Fn(Arc<Vec<Self::T>>) -> ArrayRef>> {
vec![
Box::new(|snapshots| {
Arc::new(StringArray::from(
snapshots
.iter()
.map(|row| format!("{}", row.id))
.collect::<Vec<_>>(),
))
}),
Box::new(|snapshots| {
Arc::new(TimestampNanosecondArray::from(
snapshots
.iter()
.map(|row| (row.id * 1000000) as i64)
.collect::<Vec<_>>(),
))
}),
Box::new(|snapshots| {
Arc::new(BooleanArray::from(
snapshots.iter().map(|row| row.current).collect::<Vec<_>>(),
))
}),
]
} | 693,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: vifm.rb
path of file: ./repos/homebrew-core/Formula/v
the code of the file until where you have to start completion: class Vifm < Formula
desc "Ncurses-based file manager with vi-like keybindings"
homepage "https://vifm.info/"
url "https://github.com/vifm/vifm/releases/download/v0.13/vifm-0.13.tar.bz2"
sha256 "0d9293749a794076ade967ecdc47d141d85e450370594765391bdf1a9bd45075"
license "GPL-2.0-or-later"
head "https://github.com/vifm/
| def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--with-curses=#{Formula["ncurses"].opt_prefix}",
"--without-gtk",
"--without-libmagic",
"--without-X11"
system "make"
system "make", "check"
ENV.deparallelize { system "make", "install" }
end | 695,628 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: cluster_test.go
path of file: ./repos/learning/golang/practice/go-crontab/gopath/src/github.com/coreos/etcd/etcdserver/api/membership
the code of the file until where you have to start completion: // Copyright 2015 The etcd 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 membership
import (
"encoding/json"
"fmt"
"path"
"reflect"
"testing"
"github.com/coreos/etcd/etcdserver/api/v2store"
"github.com/coreos/etcd/pkg/mock/mockstore"
"github.com/coreos/etcd/pkg/testutil"
"github.com/coreos/etcd/pkg/types"
"github.com/coreos/etcd/raft/raftpb"
"go.uber.org/zap"
)
func TestClusterMember(t *testing.T) {
membs := []*Member{
newTestMember(1, nil, "node1", nil),
newTestMember(2, nil, "node2", nil),
}
tests := []struct {
id
| func TestIsReadyToRemoveMember(t *testing.T) {
tests := []struct {
members []*Member
removeID uint64
want bool
}{
{
// 1/1 members ready, should fail
[]*Member{
newTestMember(1, nil, "1", nil),
},
1,
false,
},
{
// 0/3 members ready, should fail
[]*Member{
newTestMember(1, nil, "", nil),
newTestMember(2, nil, "", nil),
newTestMember(3, nil, "", nil),
},
1,
false,
},
{
// 1/2 members ready, should be fine to remove unstarted member
// (isReadyToRemoveMember() logic should return success, but operation itself would fail)
[]*Member{
newTestMember(1, nil, "1", nil),
newTestMember(2, nil, "", nil),
},
2,
true,
},
{
// 2/3 members ready, should fail
[]*Member{
newTestMember(1, nil, "1", nil),
newTestMember(2, nil, "2", nil),
newTestMember(3, nil, "", nil),
},
2,
false,
},
{
// 3/3 members ready, should be fine to remove one member and retain quorum
[]*Member{
newTestMember(1, nil, "1", nil),
newTestMember(2, nil, "2", nil),
newTestMember(3, nil, "3", nil),
},
3,
true,
},
{
// 3/4 members ready, should be fine to remove one member
[]*Member{
newTestMember(1, nil, "1", nil),
newTestMember(2, nil, "2", nil),
newTestMember(3, nil, "3", nil),
newTestMember(4, nil, "", nil),
},
3,
true,
},
{
// 3/4 members ready, should be fine to remove unstarted member
[]*Member{
newTestMember(1, nil, "1", nil),
newTestMember(2, nil, "2", nil),
newTestMember(3, nil, "3", nil),
newTestMember(4, nil, "", nil),
},
4,
true,
},
}
for i, tt := range tests {
c := newTestCluster(tt.members)
if got := c.IsReadyToRemoveMember(tt.removeID); got != tt.want {
t.Errorf("%d: isReadyToAddNewMember returned %t, want %t", i, got, tt.want)
}
}
} | 555,553 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: kmeans_pp.m
path of file: ./repos/CaImAn-MATLAB/utilities
the code of the file until where you have to start completion: function [L,C] = kmeans_pp(X,k)
%KMEANS_PP Cluster multivariate data using the k-means++ algorithm.
% [L,C] = kmeans_pp(X,k) produces a 1-by-size(X,2) vector L with one class
% label per column in X and a size(X,1)-by-k matrix C containing the
% centers corresponding to each class.
% Version: 2013-02-08
% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)
%
% References:
% [1] J. B. MacQueen, "Some Methods for Classification and Analysis of
% MultiVariate Observations", in Proc. of the fifth Berkeley
% Symposium on Mathematical Statistics and Probability, L. M. L. Cam
% and J. Neyman, eds., vol. 1, UC Press, 1967, pp. 281-297.
% [2] D. Arthur and S. Vassilvitskii, "k-means++: The Advantages of
% Careful Seeding", Technical Report 2006-13, Stanford InfoLab, 2006.
% Copyright (c) 2013, Laurent Sorber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
| function [L,C] = kmeans_pp(X,k)
%KMEANS_PP Cluster multivariate data using the k-means++ algorithm.
% [L,C] = kmeans_pp(X,k) produces a 1-by-size(X,2) vector L with one class
% label per column in X and a size(X,1)-by-k matrix C containing the
% centers corresponding to each class.
% Version: 2013-02-08
% Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)
%
% References:
% [1] J. B. MacQueen, "Some Methods for Classification and Analysis of
% MultiVariate Observations", in Proc. of the fifth Berkeley
% Symposium on Mathematical Statistics and Probability, L. M. L. Cam
% and J. Neyman, eds., vol. 1, UC Press, 1967, pp. 281-297.
% [2] D. Arthur and S. Vassilvitskii, "k-means++: The Advantages of
% Careful Seeding", Technical Report 2006-13, Stanford InfoLab, 2006.
% Copyright (c) 2013, Laurent Sorber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
L = [];
L1 = 0;
while length(unique(L)) ~= k
% The k-means++ initialization.
C = X(:,1+round(rand*(size(X,2)-1)));
L = ones(1,size(X,2));
for i = 2:k
D = bsxfun(@minus, X, C); % D = X-C(:,L);
D = cumsum(sqrt(dot(D, D, 1)));
if D(end | 255,915 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: letter.go
path of file: ./repos/gccrs/libgo/go/unicode
the code of the file until where you have to start completion: // Copyright 2009 The Go Aut
| func ToUpper(r rune) rune {
if r <= MaxASCII {
if 'a' <= r && r <= 'z' {
r -= 'a' - 'A'
}
return r
}
return To(UpperCase, r)
} | 746,818 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: auth.rs
path of file: ./repos/spacedrive/core/src/api
the code of the file until where you have to start completion: use std::time::Duration;
use reqwest::StatusCode;
use rspc::alpha::AlphaRouter;
use serde::{Deserialize, Serialize};
use specta::Type;
use super::{Ctx, R};
pub(crate) fn mount() -> AlphaRouter<Ctx> {
R.router()
.procedure("loginSession", {
#[derive(Serialize, Type)]
#[specta(inline)]
enum Response {
Start {
user_code: String,
verification_url: String,
verification_url_complete: String,
},
Complete,
Error(String),
}
R.subscription(|node, _: ()| async move {
#[derive(Deserialize, Type)]
struct DeviceAuthorizationResponse {
device_code: String,
user_code: String,
verification_url: String,
verification_uri_complete: String,
}
async_stream::stream! {
let auth_response = match match node
.http
.post(&format!(
"{}/login/device/code",
&node.env.api_url.lock().await
))
.form(&[("client_id", &node.env.client_id)])
.send()
.await
.map_err(|e| e.to_string())
{
Ok(r) => r.json::<DeviceAuthorizationResponse>().await.map_err(|e| e.to_string()),
Err(e) => {
yield Response::Error(e.to_string());
return
},
} {
Ok(v) => v,
Err(e) => {
yield Response::Error(e.to_string());
return
},
};
yield Response::Start {
user_code: auth_response.user_code.clone(),
verification_url: auth_response.verification_url.clone(),
verification_url_complete: auth_response.verification_uri_complete.clone(),
};
yield loop {
tokio::time::sleep(Duration::from_secs(5)).await;
let token_resp = match node.http
.post(&format!("{}/login/oauth/access_token", &node.env.api_url.lock().await))
.form(&[
("grant_type", sd_cloud_api::auth::DEVICE_CODE_URN),
("device_code", &auth_response.device_code),
("client_id", &node.env.client_id)
])
.send()
.await {
Ok(v) => v,
Err(e) => break Response::Error(e.to_string())
};
match token_resp.status() {
StatusCode::OK => {
let token = match token_resp.json().await {
Ok(v) => v,
Err(e) => break Response::Error(e.to_string())
};
if let Err(e) = node.config
.write(|c| c.auth_token = Some(token))
.await {
break Response::Error(e.to_string());
};
break Response::Complete;
},
StatusCode::BAD_REQUEST => {
#[derive(Debug, Deserialize)]
struct OAuth400 {
error:
| pub(crate) fn mount() -> AlphaRouter<Ctx> {
R.router()
.procedure("loginSession", {
#[derive(Serialize, Type)]
#[specta(inline)]
enum Response {
Start {
user_code: String,
verification_url: String,
verification_url_complete: String,
},
Complete,
Error(String),
}
R.subscription(|node, _: ()| async move {
#[derive(Deserialize, Type)]
struct DeviceAuthorizationResponse {
device_code: String,
user_code: String,
verification_url: String,
verification_uri_complete: String,
}
async_stream::stream! {
let auth_response = match match node
.http
.post(&format!(
"{}/login/device/code",
&node.env.api_url.lock().await
))
.form(&[("client_id", &node.env.client_id)])
.send()
.await
.map_err(|e| e.to_string())
{
Ok(r) => r.json::<DeviceAuthorizationResponse>().await.map_err(|e| e.to_string()),
Err(e) => {
yield Response::Error(e.to_string());
return
},
} {
Ok(v) => v,
Err(e) => {
yield Response::Error(e.to_string());
return
},
};
yield Response::Start {
user_code: auth_response.user_code.clone(),
verification_url: auth_response.verification_url.clone(),
verification_url_complete: auth_response.verification_uri_complete.clone(),
};
yield loop {
tokio::time::sleep(Duration::from_secs(5)).await;
let token_resp = match node.http
.post(&format!("{}/login/oauth/access_token", &node.env.api_url.lock().await))
.form(&[
("grant_type", sd_cloud_api::auth::DEVICE_CODE_URN),
("device_code", &auth_response.device_code),
("client_id", &node.env.client_id)
])
.send()
.await {
Ok(v) => v,
Err(e) => break Response::Error(e.to_string())
};
match token_resp.status() {
StatusCode::OK => {
let token = match token_resp.json().await {
Ok(v) => v,
Err(e) => break Response::Error(e.to_string())
};
if let Err(e) = node.config
.write(|c| c.auth_token = Some(token))
.await {
break Response::Error(e.to_string());
};
break Response::Complete;
},
StatusCode::BAD_REQUEST => {
#[derive(Debug, Deserialize)]
struct OAuth400 {
error: String
}
let resp = match token_resp.json::<OAuth400>().await {
Ok(v) => v,
Err(e) => break Response::Error(e.to_string())
};
match resp.error.as_str() {
"authorization_pending" => continue,
e => {
break Response::Error(e.to_string())
}
}
},
s => {
break Response::Error(s.to_string());
}
}
}
}
})
})
.procedure(
"logout",
R.mutation(|node, _: ()| async move {
node.config
.write(|c| c.auth_token = None)
.await
.map(|_| ())
.map_err(|_| {
rspc::Error::new(
rspc::ErrorCode::InternalServerError,
"Failed to write config".to_string(),
)
})
}),
)
.procedure("me", {
R.query(|node, _: ()| async move {
let resp = sd_cloud_api::user::me(node.cloud_api_config().await).await?;
Ok(resp)
})
})
} | 119,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: view-config.go
path of file: ./repos/erda/internal/tools/monitor/core/dataview/v1-chart-block
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
| func (vc *ViewConfigDTO) replaceWithQuery(query url.Values) {
if vc == nil {
return
}
data := []*ViewConfigItem(*vc)
for i := 0; i < len(data); i++ {
data[i].View.dynamicReplaceView(query)
}
return
} | 711,587 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: operations_client_example_test.go
path of file: ./repos/azure-sdk-for-go/sdk/resourcemanager/loadtesting/armloadtesting
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 armloadtesting_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/loadtesting/armloadtesting"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/blob/630ec444f8dd7c09b9cdd5fa99951f8a0d1ad41f/specification/loadtestservice/resource-manager/Microsoft.LoadTestService/stable/2022-12-01/examples/Operations_List.json
func ExampleOperationsClient_NewListPager() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armloadtesting.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
pager := clientFactory.NewOperationsClient().NewListPager(nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance page: %v", err)
}
for _, v := range page.Value {
// You could use page here. We use blank identifier for just demo purposes.
_ = v
}
// If the HTTP response code is 200
| func ExampleOperationsClient_NewListPager() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
clientFactory, err := armloadtesting.NewClientFactory("<subscription-id>", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
pager := clientFactory.NewOperationsClient().NewListPager(nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance page: %v", err)
}
for _, v := range page.Value {
// You could use page here. We use blank identifier for just demo purposes.
_ = v
}
// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.
// page.OperationListResult = armloadtesting.OperationListResult{
// Value: []*armloadtesting.Operation{
// {
// Name: to.Ptr("Microsoft.LoadTestService/loadTests/Write"),
// Display: &armloadtesting.OperationDisplay{
// Description: to.Ptr("Set LoadTests"),
// Operation: to.Ptr("Creates or updates the LoadTests"),
// Provider: to.Ptr("Microsoft.LoadTestService"),
// Resource: to.Ptr("loadTests"),
// },
// IsDataAction: to.Ptr(false),
// },
// {
// Name: to.Ptr("Microsoft.LoadTestService/loadTests/Delete"),
// Display: &armloadtesting.OperationDisplay{
// Description: to.Ptr("Delete LoadTests"),
// Operation: to.Ptr("Deletes the LoadTests"),
// Provider: to.Ptr("Microsoft.LoadTestService"),
// Resource: to.Ptr("loadTests"),
// },
// IsDataAction: to.Ptr(false),
// },
// {
// Name: to.Ptr("Microsoft.LoadTestService/loadTests/Read"),
// Display: &armloadtesting.OperationDisplay{
// Description: to.Ptr("Read LoadTests"),
// Operation: to.Ptr("Reads the LoadTests"),
// Provider: to.Ptr("Microsoft.LoadTestService"),
// Resource: to.Ptr("loadTests"),
// },
// IsDataAction: to.Ptr(false),
// }},
// }
}
} | 270,261 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: generated.pb.go
path of file: ./repos/hubble-ui/backend/vendor/k8s.io/api/autoscaling/v2beta1
the code of the file until where you have to start completion: /*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance w
| func (m *ResourceMetricSource) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Name)
n += 1 + l + sovGenerated(uint64(l))
if m.TargetAverageUtilization != nil {
n += 1 + sovGenerated(uint64(*m.TargetAverageUtilization))
}
if m.TargetAverageValue != nil {
l = m.TargetAverageValue.Size()
n += 1 + l + sovGenerated(uint64(l))
}
return n
} | 380,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: lz4.go
path of file: ./repos/scan4all/vendor/github.com/pierrec/lz4
the code of the file until where you have to start completion: // Package lz4 implements reading and writ
| func newBufferPool(size int) *sync.Pool {
return &sync.Pool{
New: func() interface{} {
return make([]byte, size)
},
}
} | 142,717 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: change_materialized_view.rb
path of file: ./repos/pg_trunk/lib/pg_trunk/operations/materialized_views
the code of the file until where you have to start completion: # frozen_string_literal: false
# @!p
| def changes
@changes ||= {
columns: columns.presence,
cluster_on: cluster_on,
comment: comment,
}.compact
end | 66,292 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: endpoints.go
path of file: ./repos/buildkit/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints
the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT.
package endpoints
import (
"github.com/aws/aws-sd
| func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) {
if len(region) == 0 {
return endpoint, &aws.MissingRegionError{}
}
opt := transformToSharedOptions(options)
return r.partitions.ResolveEndpoint(region, opt)
} | 653,714 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: schemaio.go
path of file: ./repos/beam/sdks/go/pkg/beam/io/xlang/schemaio
the code of the file until where you have to start completion: // Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 re
| func EncodePayload(location string, config any, dataSchema reflect.Type) ([]byte, error) {
encCfg, err := encodeAsRow(config)
if err != nil {
err = errors.WithContext(err, "encoding config for SchemaIO payload")
return nil, err
}
pl := Payload{
Location: location,
Config: encCfg,
}
if dataSchema != nil {
encScm, err := encodeAsSchema(dataSchema)
if err != nil {
err = errors.WithContext(err, "encoding dataSchema for SchemaIO payload")
return nil, err
}
pl.DataSchema = &encScm
}
return beam.CrossLanguagePayload(pl), err
} | 462,928 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: fancy.rs
path of file: ./repos/bracket-lib/bracket-terminal/examples
the code of the file until where you have to start completion: bracket_terminal::add_wasm_support!();
use bracket_terminal::prelude::*;
struct State {
x: f32,
}
impl GameState for State {
fn tick(&mut self, ctx: &mut BTerm) {
let mut draw_batch = DrawBatch::new();
draw_batch.target(1);
draw_batch.cls();
let simple_x = self.x as i32;
let fancy_x = self.x + 20.0;
draw_batch.print(Point::new(0, 0), format!("Simple Console"));
draw_batch.print(Point::new(0, 1), format!("X={}", simple_x));
draw_batch.print(Point::new(20, 0), format!("Fancy Console"));
draw_batch.print(Point::new(20, 1), format!("X={:2}", fancy
| fn tick(&mut self, ctx: &mut BTerm) {
let mut draw_batch = DrawBatch::new();
draw_batch.target(1);
draw_batch.cls();
let simple_x = self.x as i32;
let fancy_x = self.x + 20.0;
draw_batch.print(Point::new(0, 0), format!("Simple Console"));
draw_batch.print(Point::new(0, 1), format!("X={}", simple_x));
draw_batch.print(Point::new(20, 0), format!("Fancy Console"));
draw_batch.print(Point::new(20, 1), format!("X={:2}", fancy_x));
draw_batch.print(Point::new(simple_x, 3), "@");
draw_batch.set_fancy(
PointF::new(fancy_x, 4.0),
1,
Degrees::new(0.0),
PointF::new(1.0, 1.0),
ColorPair::new(WHITE, BLACK),
to_cp437('@'),
);
draw_batch.submit(0).expect("Batch error");
render_draw_buffer(ctx).expect("Render error");
self.x += 0.05;
if self.x > 10.0 {
self.x = 0.0;
}
} | 116,276 |
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
Metadata details:
filename: watcher.go
path of file: ./repos/kratos/contrib/registry/eureka
the code of the file until where you have to start completion: package eureka
import (
"context"
"github.com/go-kratos/kratos/v2/registry"
)
var _ registry.Watcher = (*watcher)(nil)
type watcher
| func newWatch(ctx context.Context, cli *API, serverName string) (*watcher, error) {
w := &watcher{
ctx: ctx,
cli: cli,
serverName: serverName,
watchChan: make(chan struct{}, 1),
}
w.ctx, w.cancel = context.WithCancel(ctx)
e := w.cli.Subscribe(
serverName,
func() {
w.watchChan <- struct{}{}
},
)
return w, e
} | 441,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: b_test.go
path of file: ./repos/codeforces-go/leetcode/biweekly/39/b
the code of the file until where you have to start completion: // Code generated by copypasta/template/leetcode/generator_test.go
package main
import (
"github.com/EndlessCheng/codeforces-go/leetcode/
| func Test(t *testing.T) {
t.Log("Current test is [b]")
examples := [][]string{
{
`"aababbab"`,
`2`,
},
{
`"bbaaaaabb"`,
`2`,
},
}
targetCaseNum := 0
if err := testutil.RunLeetCodeFuncWithExamples(t, minimumDeletions, examples, targetCaseNum); err != nil {
t.Fatal(err)
}
} | 132,459 |
You are an expert in writing code in many different languages. Your goal is 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/textract/src/operation/analyze_document
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,
}
} | 796,051 |