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: model.go path of file: ./repos/ZeroBot-Plugin/plugin/vtbquotation/model the code of the file until where you have to start completion: // Package model vtb数据库操作 package model import ( "io" "math/rand"
func (vdb *VtbDB) RandomVtb() ThirdCategory { db := (*gorm.DB)(vdb) var count int var tc ThirdCategory db.Model(&ThirdCategory{}).Count(&count).Offset(rand.Intn(count)).Take(&tc) return tc }
10,549
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: context.rs path of file: ./repos/neon/pageserver/src the code of the file until where you have to start completion: //! This module defines `RequestContext`, a structure that we
pub fn new(task_kind: TaskKind) -> Self { Self { inner: RequestContext { task_kind, download_behavior: DownloadBehavior::Download, access_stats_behavior: AccessStatsBehavior::Update, page_content_kind: PageContentKind::Unknown, micros_spent_throttled: Default::default(), }, } }
678,641
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: unmarshaller.go path of file: ./repos/kuma/pkg/core/resources/model/rest the code of the file until where you have to start completion: package rest import ( "encoding/json" "fmt" "net/url" "strings" "github.com/pkg/errors" "k8s.io/kube-openapi/pkg/validation/strfmt" "k8s.io/kube-openapi/pkg/validation/validate" "sigs.k8s.io/yaml" core_model "github.com/kumahq/kuma/pkg/core/resources/model" "github.com/kumahq/kuma/pkg/core/resources/model/rest/v1alpha1" "github.com/kumahq/ku
func toValidationError(res *validate.Result) *validators.ValidationError { verr := &validators.ValidationError{} for _, e := range res.Errors { parts := strings.Split(e.Error(), " ") if len(parts) > 1 && strings.HasPrefix(parts[0], "spec.") { verr.AddViolation(parts[0], strings.Join(parts[1:], " ")) } else { verr.AddViolation("", e.Error()) } } return verr }
54,931
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: path.go path of file: ./repos/kubeedge/vendor/github.com/google/go-cmp/cmp the code of the file until where you have to start completion: // Copyright 2017, 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 cmp import ( "fmt" "reflect" "strings" "unicode" "unicode/utf8" "github.com/google/go-cmp/cmp/internal/value" ) // Path is a list of PathSteps describing the s
func (sf StructField) Values() (vx, vy reflect.Value) { if !sf.unexported { return sf.vx, sf.vy // CanInterface reports true } // Forcibly obtain read-write access to an unexported struct field. if sf.mayForce { vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr) vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr) return vx, vy // CanInterface reports true } return sf.vx, sf.vy // CanInterface reports false }
414,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: dmperm_test.m path of file: ./repos/SuiteSparse/CSparse/MATLAB/Test the code of the file until where you have to start completion: function dmperm_test %DMPERM_TEST test cs_dmperm % % Example: % dmperm_test % See also: testall % CSparse, Copyright (c) 2006-2022, Timothy A. Davis. All Rights Reserved. % SPDX-License-Identifier: LGPL-2.1+ index = ssget ; f = find (index.nrows ~= index.ncols) ; [ignore i] = sort (index.nrows(f) ./ index.ncols(f)) ; f = [209:211 f(i)] ;
function dmperm_test %DMPERM_TEST test cs_dmperm % % Example: % dmperm_test % See also: testall % CSparse, Copyright (c) 2006-2022, Timothy A. Davis. All Rights Reserved. % SPDX-License-Identifier: LGPL-2.1+ index = ssget ; f = find (index.nrows ~= index.ncols) ; [ignore i] = sort (index.nrows(f) ./ index.ncols(f)) ; f = [209:211 f(i)] ; nmat = length(f) ; tt1 = zeros (1,nmat) ; tt2 = zeros (1,nmat) ; tt3 = zeros (1,nmat) ; tt4 = zeros (1,nmat) ; mm = zeros (1,nmat) ; nn = zeros (1,nmat) ; ss = zeros (1,nmat) ; me = zeros (1,nmat) ; ne = zeros (1,nmat) ; p = cs_dmperm (sparse (1)) ; for k = 1:length(f) i = f(k) ; Prob = ssget (i) %#ok A = Prob.A ; [m n] = size (A) ; if (m > n) % make sure A is short and fat A = A' ; end
192,089
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: line.rs path of file: ./repos/tui-rs/src/widgets/canvas the code of the file until where you have to start completion: use crate::{ style::Color, widgets::canvas::{Painter, Shape}, }; /// Shape to draw a line from (x1, y1) to (x2, y2) with the given color #[derive(Debug, Clone)] pub struct Line { pub x1: f64, pub y1: f64, pub x2: f64,
fn draw(&self, painter: &mut Painter) { let (x1, y1) = match painter.get_point(self.x1, self.y1) { Some(c) => c, None => return, }; let (x2, y2) = match painter.get_point(self.x2, self.y2) { Some(c) => c, None => return, }; let (dx, x_range) = if x2 >= x1 { (x2 - x1, x1..=x2) } else { (x1 - x2, x2..=x1) }; let (dy, y_range) = if y2 >= y1 { (y2 - y1, y1..=y2) } else { (y1 - y2, y2..=y1) }; if dx == 0 { for y in y_range { painter.paint(x1, y, self.color); } } else if dy == 0 { for x in x_range { painter.paint(x, y1, self.color); } } else if dy < dx { if x1 > x2 { draw_line_low(painter, x2, y2, x1, y1, self.color); } else { draw_line_low(painter, x1, y1, x2, y2, self.color); } } else if y1 > y2 { draw_line_high(painter, x2, y2, x1, y1, self.color); } else { draw_line_high(painter, x1, y1, x2, y2, self.color); } }
727,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: builders.rs path of file: ./repos/aws-sdk-rust/sdk/transcribe/src/operation/delete_medical_transcription_job the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub(crate) fn new(handle: ::std::sync::Arc<crate::client::Handle>) -> Self { Self { handle, inner: ::std::default::Default::default(), config_override: ::std::option::Option::None, } }
756,996
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: contact_total_other.rb path of file: ./repos/xero-ruby/lib/xero-ruby/models/finance the code of the file until where you have to start completion: =begin #Xero Finance API #The Finance API is a collectio
def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(parse_date(value)) when :Date Date.parse(parse_date(value)) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BigDecimal BigDecimal(value.to_s) when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end
239,836
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: hash.rb path of file: ./repos/mutant/lib/mutant/mutator/node/literal the code of the file until where you have to start completion: # frozen_string_literal: true module Mutant class Mutator class Node class Literal
def mutate_body children.each_index do |index| mutate_child(index) dup_children = children.dup dup_children.delete_at(index) emit_type(*dup_children) end end
334,082
You are an expert in writing code in many different languages. Your goal is 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_components.rs path of file: ./repos/aws-sdk-rust/sdk/ssmsap/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 `ListComponents`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct ListComponents; impl ListComponents
fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> { match self { Self::InternalServerException(_inner) => ::std::option::Option::Some(_inner), Self::ResourceNotFoundException(_inner) => ::std::option::Option::Some(_inner), Self::UnauthorizedException(_inner) => ::std::option::Option::Some(_inner), Self::ValidationException(_inner) => ::std::option::Option::Some(_inner), Self::Unhandled(_inner) => ::std::option::Option::Some(&*_inner.source), } }
766,485
You are an expert in writing code in many different languages. Your goal is 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_platform_supports.m path of file: ./repos/fieldtrip/preproc/private the code of the file until where you have to start completion: function tf = ft_platform_supports(what, varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Use as % status = ft_platform_supports(what) % or % status = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter, which means means that % the specific feature explained on the right is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics system is object-oriented % 'libmx_c_interface' libmx is supported through mex in the C-language (recent MATLAB versions only support C++) % 'images' all image processing functions in FieldTrip's external/images directory % 'signal' all signal processing functions in FieldTrip's external/signal directory % 'stats' all statistical functions in FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start MATLAB with -singleCompThread % 'nosplash' start MATLAB with -nosplash % 'nodisplay' start MATLAB with -nodisplay % 'nojvm' start MATLAB with -nojvm % 'no-gui' start GNU Octave with --no-gui
function tf = ft_platform_supports(what, varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Use as % status = ft_platform_supports(what) % or % status = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter, which means means that % the specific feature explained on the right is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics system is object-oriented % 'libmx_c_interface' libmx is supported through mex in the C-language (recent MATLAB versions only support C++) % 'images' all image processing functions in FieldTrip's external/images directory % 'signal' all signal processing functions in FieldTrip's external/signal directory % 'stats' all statistical functions in FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start MATLAB with -singleCompThread % 'nosplash' start MATLAB with -nosplash % 'nodisplay' start MATLAB with -nodisplay % 'nojvm' start MATLAB with -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4') with v4 interpolation support % 'uimenu' uimenu(...) % 'weboptions' weboptions(...) % 'parula' parula(...) % 'datetime' datetime structure % 'html' html rend
683,174
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _update_bridge_source_output.rs path of file: ./repos/aws-sdk-rust/sdk/mediaconnect/src/operation/update_bridge_source the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp::PartialEq,
pub fn build(self) -> crate::operation::update_bridge_source::UpdateBridgeSourceOutput { crate::operation::update_bridge_source::UpdateBridgeSourceOutput { bridge_arn: self.bridge_arn, source: self.source, _request_id: self._request_id, } }
790,627
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: parsers.go path of file: ./repos/flyte/flytestdlib/internal/utils the code of the file until where you have to start completion: package utils import ( "net/url" "regexp" ) // A utility function to be used in tests. It parses urlStri
func MustParseURL(urlString string) url.URL { u, err := url.Parse(urlString) if err != nil { panic(err) } return *u }
92,337
You are an expert in writing code in many different languages. Your goal is 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/spyglass/apps/web/src/pages/lens_editor the code of the file until where you have to start completion: use gloo::timers::callback::{Interval, Timeout}; use strum::IntoEnumIterator; use ui_components::{ btn::{Btn, BtnSize, BtnType}, icons, results::Paginator, }; use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; use wasm_bindgen_futures::spawn_local; use web_sys::HtmlInputElement; use yew::prelude::*; use yew_router::scope_ext::RouterScopeExt; use crate::{ client::{ApiError, Lens, LensDocType, LensSource}, download_file, schema::{GetLensSourceResponse, LensSourceQueryFilter}, AuthStatus, }; mod add_source; use add_source::AddSourceComponent; const QUERY_DEBOUNCE_MS: u32 = 1_000; const REFRESH_INTERVAL_MS: u32 = 5_000; const DOWNLOAD_PREFIX: &str = "https://search.spyglass.fyi/lens"; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_name = "clearTimeout")] fn clear_timeout(handle: JsValue); } #[derive(Clone, PartialEq)] pub struct LensSourcePaginator { page: usize, num_items: usize, num_pages: usize, } pub struct CreateLensPage { pub error_msg: Option<String>, pub lens_identifier: String, pub lens_data: Option<Lens>, pub source_filter: LensSourceQueryFilter, pub lens_sources: Option<Vec<LensSource>>, pub lens_source_paginator: Option<LensSourcePaginator>, pub is_loading_lens_sources: bool, pub is_saving_name: bool, pub auth_status: AuthStatus, pub add_url_error: Option<String>, pub _refresh_interval: Option<Interval>, pub _context_listener: ContextHandle<AuthStatus>, pub _query_debounce: Option<JsValue>, pub _name_input_ref: NodeRef, } #[derive(Properties, PartialEq)] pub struct CreateLensProps { pub lens: String, } pub enum Msg { ClearError, DeleteLensSource(LensSource), Reload, ReloadCurrentSources, ReloadSources { page: usize, filter: LensSourceQueryFilter, }, Save { display_name: String, }, SaveDone, SetError(String), SetFilter(LensSourceQueryFilter), SetLensData(Lens), SetLensSources(GetLensSourceResponse), UpdateContext(AuthStatus), UpdateDisplayName, } impl Component for CreateLensPage { type Message = Msg; type Properties = CreateLensProps; fn create(ctx: &Context<Self>) -> Self { let (auth_status, context_listener) = ctx .link() .context(ctx.link().callback(Msg::UpdateContext)) .expect("No Message Context Provided"); ctx.link().send_message_batch(vec![ Msg::Reload, Msg::ReloadSources { page: 0, filter: LensSourceQueryFilter::default(), }, ]); Self { error_msg: None, lens_identifier: ctx.props().lens.clone(), lens_data: None, lens_sources: None, lens_source_paginator: None, source_filter: LensSourceQueryFilter::default(), is_saving_name: false, is_loading_lens_sources: false, auth_status, add_url_error: None, _refresh_interval: None, _context_listener: context_listener, _query_debounce: None, _name_input_ref: NodeRef::default(), } } fn changed(&mut self, ctx: &
fn view(&self, ctx: &Context<Self>) -> Html { let link = ctx.link(); html! { <div class="flex flex-col px-8 pt-6 gap-4"> {if let Some(msg) = &self.error_msg { html! { <div class="bg-red-100 border border-red-400 text-red-700 p-2 text-sm rounded-lg font-semibold relative" role="alert"> <div>{msg}</div> <span class="absolute top-0 bottom-0 right-0 p-2"> <svg onclick={link.callback(|_| Msg::ClearError)} class="fill-current h-5 w-5 text-red-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" > <path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/> </svg> </span> </div> } } else { html! {} }} <div> {if let Some(lens_data) = self.lens_data.as_ref() { html! { <div class="flex flex-row items-center"> <input class="border-b-4 border-neutral-600 pt-3 pb-1 bg-neutral-800 text-white text-2xl outline-none active:outline-none focus:outline-none caret-white" type="text" spellcheck="false" tabindex="-1" value={lens_data.display_name.to_string()} oninput={link.callback(|_| Msg::UpdateDisplayName)} ref={self._name_input_ref.clone()} /> {if self.is_saving_name { html! { <icons::RefreshIcon classes={"ml-2 text-cyan-500"} width="w-6" height="h-6" animate_spin={true} /> } } else { html! {} }} </div> } } else { html! { <h2 class="bold text-xl ">{"Loading..."}</h2> } }} </div> <div class="mt-4"> <AddSourceComponent on_error={link.callback(Msg::SetError)} on_update={link.callback(|_| Msg::Reload)} lens_identifier={self.lens_identifier.clone()} /> </div> <div class="mt-8"> {if let Some(paginator) = self.lens_source_paginator.clone() { let filter = self.source_filter; html! { <SourceTable sources={self.lens_sources.clone().unwrap_or_default()} paginator={paginator.clone()} selected_filter={self.source_filter} is_loading={self.is_loading_lens_sources} on_delete={link.callback(Msg::DeleteLensSource)} on_refresh={link.callback(move |_| Msg::ReloadSources { page: paginator.page, filter })} on_select_page={link.callback(move |page| Msg::ReloadSources { page, filter })} on_select_filter={link.callback(Msg::SetFilter)} /> } } else { html! {} }} </div> </div> } }
77,726
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ShapeFunctionProjector_ForTriangles.m path of file: ./repos/Swan/Topology Optimization/Filters/ShapeFunctionProjector the code of the file until where you have to start completion: classdef ShapeFunctionProjector_ForTr
function [F,aire] = faireF2(p,t,psi) np = size(p,2); nt = size(t,2); F = zeros(np,1); p1 = t(1,:); p2 = t(2,:); p3 = t(3,:); x1 = p(1,p1); y1 = p(2,p1); x2 = p(1,p2); y2 = p(2,p2); x3 = p(1,p3); y3 = p(2,p3); A = 0.5*abs((x2-x1).*(y3-y1)-(x3-x1).*(y2-y1)); beta = (psi<0); beta = pdeintrp(p,t,beta); k = find(beta>0.5); F = F+accumarray(p1(k)',A(k)/3',[np,1],@sum,0); F = F+accumarray(p2(k)',A(k)/3',[np,1],@sum,0); F = F+accumarray(p3(k)',A(k)/3',[np,1],@sum,0); aire = sum(A(k)); k = find(abs(beta-1/3)<0.01); p1 = t(1,k); p2 = t(2,k); p3 = t(3,k); psi1 = psi(p1)'; psi2 = psi(p2)'; psi3 = psi(p3)'; [psis,is] = sort([psi1;psi2;psi3],1); is = is+3*ones(3,1)*[0:length(k)-1]; pl = [p1;p2;p3]; ps = pl(is); x1 = p(1,ps(1,:)); y1 = p(2,ps(1,:)); x2 = p(1,ps(2,:)); y2 = p(2,ps(2,:)); x3 = p(1,ps(3,:)); y3 = p(2,ps(3,:)); x12 = (psis(1,:).*x2-psis(2,:).*x1)./(psis(1,:)-psis(2,:)); y12 = (psis(1,:).*y2-psis(2,:).*y1)./(psis(1,:)-psis(2,:)); x13 = (psis(1,:).*x3-psis(3,:).*x1)./(psis(1,:)-psis(3,:)); y13 = (psis(1,:).*y3-psis(3,:).*y1)./(psis(1,:)-psis(3,:)); A = 0.5*abs(((x12-x1).*(y13-y1)-(x13-x1).*(y12-y1))); F = F+accumarray(ps(1,:)',((1+psis(2,:)./(psis(2,:)-psis(1,:))+psis(3,:)./(psis(3,:)-psis(1,:))).*A/3)',[np,1],@sum,0); F = F+accumarray(ps(2,:)',((psis(1,:)./(psis(1,:)-psis(2,:))).*A/3)',[np,1],@sum,0); F = F+accumarray(ps(3,:)',((psis(1,:)./(psis(1,:)-psis(3,:))).*A/3)',[np,1],@sum,0); aire = aire+sum(A); k = find(abs(beta-2/3)<0.01); p1 = t(1,k); p2 = t(2,k); p3 = t(3,k); psi1 = psi(p1)'; psi2 = psi(p2)'; psi3 = psi(p3)'; [psis,is] = sort([psi1;psi2;psi3],1,'descend
307,690
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: terminal_check_notappengine.go path of file: ./repos/delve/vendor/github.com/sirupsen/logrus the code of the file until where you have to start completion: // +build !appengine,!js,!windows,!nacl,!plan9 package logrus i
func checkIfTerminal(w io.Writer) bool { switch v := w.(type) { case *os.File: return isTerminal(int(v.Fd())) default: return false } }
620,096
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: dot_helper.rb path of file: ./repos/huginn/app/helpers the code of the file until where you have to start completion: module DotHelper def render_agents_diagram(agents, layout: nil) if svg = dot_to_svg(agents_dot(agents, rich: true, layout:)) decorate_svg(svg, agents).html_safe else # Google chart request url
def escape(string) # Backslash escaping seems to work for the backslash itself, # though it's not documented in the DOT language docs. string.gsub(/[\\"\n]/, "\\" => "\\\\", "\"" => "\\\"", "\n" => "\\n") end def id(value) case string = value.to_s when /\A(?!\d)\w+\z/, /\A(?:\.\d+|\d+(?:\.\d*)?)\z/ raw string else raw '"' raw escape(string) raw '"' end end
178,598
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: DEM_demo_contact_lens.m path of file: ./repos/bspm/thirdparty/spm12/toolbox/DEM the code of the file until where you have to start completion: function DEM_demo_contact_lens % This demo illustrates tracking under the contact lens problem: % The contact lens refers to the
function of K %========================================================================== K = -0:1/2:12; for i = 1:length(K) % DEM and EKF (linear) %---------------------------------------------------------------------- DEM.M(1).E.K = exp(K(i)); DEM = spm_DEM(DEM); % mean square error %---------------------------------------------------------------------- kse(i,1) = mean(mean((DEM.pU.x{1} - DEM.qU.x{1}).^2)); end
519,789
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: floatOrStr.go path of file: ./repos/bk-cmdb/src/common/metric the code of the file until where you have to start completion: /* * Tencent is pleased to support the open source community by making 蓝鲸 available. * Copyright (C)
func (fs *FloatOrString) UnmarshalJSON(b []byte) error { f, err := strconv.ParseFloat(string(b), 10) if nil == err { fs.Type = Float fs.Float = f return nil } fs.Type = String fs.String = string(b) return nil }
372,521
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: url_manager.go path of file: ./repos/scan4all/webScan/config the code of the file until where you have to start completion: package Configs import ( "fmt" "net/url" "strings" ) func Get_Url(urls string, port_split bool) string { if !st
func Get_Url(urls string, port_split bool) string { if !strings.HasPrefix(urls, "http") { urls = "http://" + urls } urls = strings.Trim(urls, " ") if strings.HasPrefix(urls, "http") { url_tmp, err := url.Parse(urls) if err != nil { fmt.Println("url.Parse err", err) } if port_split == true { if url_tmp.Port() != "" { url_tmp_host := strings.Split(url_tmp.Host, ":")[0] return url_tmp_host } else { return url_tmp.Host } } else { return url_tmp.Host } } return "nil" }
140,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: dual.go path of file: ./repos/gonum/num/dualquat the code of the file until where you have to start completion: // Copyright ©2018 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package dualquat import ( "fmt" "strings" "gonum.or
func fmtString(fs fmt.State, c rune, prec, width int, wantPlus bool) string { var b strings.Builder b.WriteByte('%') for _, f := range "0+- " { if fs.Flag(int(f)) || (f == '+' && wantPlus) { b.WriteByte(byte(f)) } } if width >= 0 { fmt.Fprint(&b, width) } if prec >= 0 { b.WriteByte('.') if prec > 0 { fmt.Fprint(&b, prec) } } b.WriteRune(c) return b.String() }
690,694
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: execabs.go path of file: ./repos/scan4all/vendor/golang.org/x/sys/execabs the code of the file until where you have to start completion: // Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found i
func LookPath(file string) (string, error) { path, err := exec.LookPath(file) if err != nil && !isGo119ErrDot(err) { return "", err } if filepath.Base(file) == file && !filepath.IsAbs(path) { return "", relError(file, path) } return path, nil }
144,995
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: setup_test.go path of file: ./repos/magistrala/internal/groups/postgres the code of the file until where you have to start completion: // Copyright (c) Abstract Machines // SPDX-License-Identifier: Apache-2.0 package postgres_test import ( "database/sql" "fmt" "log" "os" "testing" "time" pgclient "github.com/absmach/magistrala/internal/clients/postgres" gpostgres "github.com/absmach/magistrala/internal/groups/postgres" "github.com/absmach/magistrala/internal/postgres" "github.com/jmoiron/sqlx" "github.com/ory/dockertest/v3" "github.com/ory/dockertest/v3/docker" "go.opentelemetry.io/otel" ) var ( db *sqlx.DB database postgres.Database tracer = otel.Tracer("repo_tests") ) func TestMain(m *testing.M) { pool, err := dockertest.NewPool("") if err != nil { log.Fatalf("Could not connect to docker: %s", err) } container, err := pool.RunWithOptions(&dockertest.RunOptions{ Repository: "postgres", Tag: "16.1-alpine", Env: []string{ "POSTGRES_USER=test", "POSTGRES_PASSWORD=test", "POSTGRES_DB=test", "listen_addresses = '*'", }, }, func(config *docker.HostConfig) { config.AutoRemove = true config.RestartPolicy = docker.RestartPolicy{Name: "no"} }) if err != nil { log.Fatalf("Could not start container: %s", err) } port := container.GetPort("5432/tcp") // exponential backoff-retry, because the application in the container might not be ready to accept connections yet pool.MaxWait = 120 * time.Second if err := pool.Retry(func() error { url := fmt.Sprintf("host=localhost port=%s user=test dbname=test p
func TestMain(m *testing.M) { pool, err := dockertest.NewPool("") if err != nil { log.Fatalf("Could not connect to docker: %s", err) } container, err := pool.RunWithOptions(&dockertest.RunOptions{ Repository: "postgres", Tag: "16.1-alpine", Env: []string{ "POSTGRES_USER=test", "POSTGRES_PASSWORD=test", "POSTGRES_DB=test", "listen_addresses = '*'", }, }, func(config *docker.HostConfig) { config.AutoRemove = true config.RestartPolicy = docker.RestartPolicy{Name: "no"} }) if err != nil { log.Fatalf("Could not start container: %s", err) } port := container.GetPort("5432/tcp") // exponential backoff-retry, because the application in the container might not be ready to accept connections yet pool.MaxWait = 120 * time.Second if err := pool.Retry(func() error { url := fmt.Sprintf("host=localhost port=%s user=test dbname=test password=test sslmode=disable", port) db, err := sql.Open("pgx", url) if err != nil { return err } return db.Ping() }); err != nil { log.Fatalf("Could not connect to docker: %s", err) } dbConfig := pgclient.Config{ Host: "localhost", Port: port, User: "test", Pass: "test", Name: "test", SSLMode: "disable", SSLCert: "", SSLKey: "", SSLRootCert: "", } if db, err = pgclient.Setup(dbConfig, *gpostgres.Migration()); err != nil { log.Fatalf("Could not setup test DB connection: %s", err) } database = postgres.NewDatabase(db, dbConfig, tracer) code := m.Run() // Defers will not be run when using os.Exit db.Close() if err := pool.Purge(container); err != nil { log.Fatalf("Could not purge container: %s", err) } os.Exit(code) }
693,157
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: elproj.m path of file: ./repos/fieldtrip/fileio/private the code of the file until where you have to start completion: function [proj] = elproj(pos, method) % ELPROJ makes a azimuthal projection of a 3D electrode cloud % on a plane tangent to the sphere fitted through the electrodes % the projection is along the z-axis %
function [proj] = elproj(pos, method) % ELPROJ makes a azimuthal projection of a 3D electrode cloud % on a plane tangent to the sphere fitted through the electrodes % the projection is along the z-axis % % [proj] = elproj([x, y, z], 'method'); % % Method should be one of these: % 'gnomic' % 'stereographic' % 'orthographic' % 'inverse' % 'polar' % % Imagine a plane being placed against (tangent to) a globe. If % a light source inside the globe projects the graticule onto % the plane the result would be a planar, or azimuthal, map % projection. If the imaginary light is inside the globe a Gnomonic % projection results, if the light is antipodal a Sterographic, % and if at infinity, an Orthographic. % % The default projection is a polar projection (BESA like). % An inverse projection is the opposite of the default polar projection. % % See also PROJECTTRI % Copyright (C) 2000-2008, 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$ x = pos(:,1); y = pos(:,2); if size(pos, 2)==3 z = pos(:,3); end
683,670
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _entity_status.rs path of file: ./repos/aws-sdk-rust/sdk/machinelearning/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// When writing a match expression against `EntityStatus`, it is importan
pub fn as_str(&self) -> &str { match self { EntityStatus::Completed => "COMPLETED", EntityStatus::Deleted => "DELETED", EntityStatus::Failed => "FAILED", EntityStatus::Inprogress => "INPROGRESS", EntityStatus::Pending => "PENDING", EntityStatus::Unknown(value) => value.as_str(), } }
807,442
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: authsession.bindAuthKeyUser_handler.go path of file: ./repos/teamgram-server/app/service/authsession/internal/core the code of the file until where you have to start completion: /* * Created from 'scheme.tl' by 'mtprotoc' * * Copyright (c) 2021-present, Teamgram Studio (https://teamgram.io). * All rights reserved. * * Author: teamgramio (teamgram.io@gmail.com) */ package core import ( "gith
func (c *AuthsessionCore) AuthsessionBindAuthKeyUser(in *authsession.TLAuthsessionBindAuthKeyUser) (*mtproto.Int64, error) { var ( inKeyId = in.GetAuthKeyId() ) keyData, err := c.svcCtx.Dao.QueryAuthKeyV2(c.ctx, inKeyId) if err != nil { c.Logger.Errorf("queryAuthKeyV2(%d) is error: %v", inKeyId, err) return nil, err } else if keyData.PermAuthKeyId == 0 { c.Logger.Errorf("queryAuthKeyV2(%d) - PermAuthKeyId is empty", inKeyId) return nil, mtproto.ErrAuthKeyPermEmpty } hash := c.svcCtx.Dao.BindAuthKeyUser(c.ctx, keyData.PermAuthKeyId, in.GetUserId()) return &mtproto.Int64{V: hash}, nil }
83,349
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: flow_control_replica_integration.go path of file: ./repos/cockroach/pkg/kv/kvserver the code of the file until where you have to start completion: // Copyright 2023 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package kvserver import ( "context" "sort" "github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvflowcontrol" "github.com/cockroachdb/cockroach/pkg/roachpb" "github.com/cockroachdb/cockroach/pkg/util/buildutil" "github.com/cockroachdb/cockroach/pkg/util/log" ) // replicaFlowControlIntegrationImpl is the canonical implementation of the // replicaFlowControlIntegration interface. type replicaFlowControlIntegrationImpl struct { replicaForFlowControl replicaForFlowControl handleFactory kvflowcontrol.HandleFactory knobs *kvflowcontrol.TestingKnobs // The fields below are non-nil iff the replica is a raft leader and part of // the range. // innerHandle is the underlying kvflowcontrol.Handle, which we // deduct/return flow tokens to, and inform of connected/disconnected // replication streams. innerHandle kvflowcontrol.Handle // lastKnownReplicas tracks the set of last know replicas in the range. This
func (f *replicaFlowControlIntegrationImpl) onDescChanged(ctx context.Context) { f.replicaForFlowControl.assertLocked() if f.innerHandle == nil { return // nothing to do } addedReplicas, removedReplicas := f.lastKnownReplicas.Difference( f.replicaForFlowControl.getDescriptor().Replicas(), ) ourReplicaID := f.replicaForFlowControl.getReplicaID() for _, repl := range removedReplicas { if repl.ReplicaID == ourReplicaID { // We're observing ourselves get removed from the raft group, but // are still retaining raft leadership. Close the underlying handle // and bail. See TestFlowControlRaftMembershipRemoveSelf. f.clearState(ctx) return } } // See I10 from kvflowcontrol/doc.go. We stop deducting flow tokens for // replicas that are no longer part of the raft group, free-ing up all // held tokens. f.disconnectStreams(ctx, removedReplicas, "removed replicas") for _, repl := range removedReplicas { // We'll not reconnect to these replicas either, so untrack them. delete(f.disconnectedStreams, repl.ReplicaID) } // Start off new replicas as disconnected. We'll subsequently try to // re-add them, once we know their log positions and consider them // sufficiently caught up. See I3a from kvflowcontrol/doc.go. f.disconnectStreams(ctx, addedReplicas, "newly added replicas") if len(addedReplicas) > 0 || len(removedReplicas) > 0 { log.VInfof(ctx, 1, "desc changed from %s to %s: added=%s removed=%s", f.lastKnownReplicas, f.replicaForFlowControl.getDescriptor(), addedReplicas, removedReplicas, ) } f.lastKnownReplicas = f.replicaForFlowControl.getDescriptor().Replicas() }
701,653
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: api_op_GetLinkAssociations.go path of file: ./repos/aws-sdk-go-v2/service/networkmanager the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package networkmanager import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws
func newServiceMetadataMiddleware_opGetLinkAssociations(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "GetLinkAssociations", } }
228,760
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: undelta_store_test.go path of file: ./repos/gitkube/vendor/k8s.io/client-go/tools/cache the code of the file until where you have to start completion: /* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not u
func TestReadsDoNotCallPush(t *testing.T) { push := func(m []interface{}) { t.Errorf("Unexpected call to push!") } u := NewUndeltaStore(push, testUndeltaKeyFunc) // These should not call push. _ = u.List() _, _, _ = u.Get(testUndeltaObject{"a", ""}) }
507,237
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: firewalld_test.go path of file: ./repos/docker-ce/components/engine/libnetwork/iptables the code of the file until where you have to start completion: //go:build linux // +build linux package iptables import ( "net" "strconv" "testing" ) func
func TestFirewalldInit(t *testing.T) { if !checkRunning() { t.Skip("firewalld is not running") } if err := FirewalldInit(); err != nil { t.Fatal(err) } }
564,643
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: swarm_service.go path of file: ./repos/sealer/vendor/github.com/fsouza/go-dockerclient the code of the file until where you have to start completion: // Copyright 2016 go-dockerclient 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 docker import ( "context" "encoding/json" "errors" "io" "net/http" "time" "github.com/docker/docker/api/types/swarm" ) // NoSuchService is the error returned when a given service does not exist. type N
func (c *Client) CreateService(opts CreateServiceOptions) (*swarm.Service, error) { headers, err := headersWithAuth(opts.Auth) if err != nil { return nil, err } path := "/services/create?" + queryString(opts) resp, err := c.do(http.MethodPost, path, doOptions{ headers: headers, data: opts.ServiceSpec, forceJSON: true, context: opts.Context, }) if err != nil { return nil, err } defer resp.Body.Close() var service swarm.Service if err := json.NewDecoder(resp.Body).Decode(&service); err != nil { return nil, err } return &service, nil }
723,622
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: properties.go path of file: ./repos/lazydocker/vendor/github.com/rivo/uniseg the code of the file until where you have to start completion: package uniseg // The Unicode properties as used in the various parsers. Only the ones needed // in the context of this package are included. const
func propertySearch[E interface{ [3]int | [4]int }](dictionary []E, r rune) (result E) { // Run a binary search. from := 0 to := len(dictionary) for to > from { middle := (from + to) / 2 cpRange := dictionary[middle] if int(r) < cpRange[0] { to = middle continue } if int(r) > cpRange[1] { from = middle + 1 continue } return cpRange } return }
584,420
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: getdimord.m path of file: ./repos/spm12/external/fieldtrip/forward/private the code of the file until where you have to start completion: function dimord = getdimord(data, field, varargin) % GETDIMORD determine the dimensions and order of a data field in a
function isequalwithoutnans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = check_trailingdimsunitlength(data, dimtok) ok = false; for k = 1:numel(dimtok) switch dimtok{k} case 'chan' ok = numel(data.label)==1; otherwise if isfield(data, dimtok{k}) % check whether field exists ok = numel(data.(dimtok{k}))==1; end
330,392
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: coldfusion_locale_traversal.rb path of file: ./repos/metasploit-framework/modules/auxiliary/scanner/http the code of the file until where you have to start completion: ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.co
def initialize super( 'Name' => 'ColdFusion Server Check', 'Description' => %q{ This module attempts to exploit the directory traversal in the 'locale' attribute. According to the advisory the following versions are vulnerable: ColdFusion MX6 6.1 base patches, ColdFusion MX7 7,0,0,91690 base patches, ColdFusion MX8 8,0,1,195765 base patches, ColdFusion MX8 8,0,1,195765 with Hotfix4. Adobe released patches for ColdFusion 8.0, 8.0.1, and 9 but ColdFusion 9 is reported to have directory traversal protections in place, subsequently this module does NOT work against ColdFusion 9. Adobe did not release patches for ColdFusion 6.1 or ColdFusion 7. It is not recommended to set FILE when doing scans across a group of servers where the OS may vary; otherwise, the file requested may not make sense for the OS }, 'Author' => [ 'CG', 'nebulus' ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2010-2861' ], [ 'BID', '42342' ], [ 'OSVDB', '67047' ], [ 'URL', 'https://www.gnucitizen.org/blog/coldfusion-directory-traversal-faq-cve-2010-2861/' ], [ 'URL', 'https://www.adobe.com/support/security/bulletins/apsb10-18.html' ], ] ) register_options( [ OptString.new('FILE', [ false, 'File to retrieve', '']), OptBool.new('FINGERPRINT', [true, 'Only fingerprint endpoints', false]) ]) end def fingerprint(response) if(response.headers.has_key?('Server') ) if(response.headers['Server'] =~ /IIS/ or response.headers['Server'] =~ /\(Windows/) os = "Windows (#{response.headers['Server']})" elsif(response.headers['Server'] =~ /Apache\//) os = "Unix (#{response.headers['Server']})" else os = response.headers['Server'] end end return nil if response.body.length < 100 title = "Not Found" response.body.gsub!(/[\r\n]/, '') if(response.body =~ /<title.*\/?>(.+)<\/title\/?>/i) title = $1 title.gsub!(/\s/, '') end
741,244
You are an expert in writing code in many different languages. Your goal is 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/skynet/No 32 - Who are you Rust/src/structs/src the code of the file until where you have to start completion: /* OOP'taki gibi bir varlığı ve niteliklerin
fn write_to_console(p: Product) { println!( "\n{} ({})\n{} dalır.\nStokta {} adet var.\nŞu an satışta mı? {}", p.title, p.company, p.unit_price, p.stock_level, if p.is_usable { "evet" } else { "hayır" } ); }
33,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: zip.go path of file: ./repos/ipatool/pkg/util the code of the file until where you have to start completion: package util import "errors" type Pair[T, U any] struct { First T Second U } func Zip[T, U any](ts []T, us []U) ([]Pair[T, U], error) { if len(ts) != len(us) { return nil, errors.New("slices have different lengths") } pairs := make([]Pair[T, U], len(ts)) for i := 0; i
func Zip[T, U any](ts []T, us []U) ([]Pair[T, U], error) { if len(ts) != len(us) { return nil, errors.New("slices have different lengths") } pairs := make([]Pair[T, U], len(ts)) for i := 0; i < len(ts); i++ { pairs[i] = Pair[T, U]{ First: ts[i], Second: us[i], } } return pairs, nil }
319,855
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: activity.go path of file: ./repos/temporal/tests the code of the file until where you have to start completion: // The MIT License // // Copyright (c) 2020 Temporal Technologies Inc. All rights reserved. // // Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package tests import ( "bytes" "context" "encoding/binary" "errors" "time" "go.temporal.io/sdk/activity" sdkclient "go.temporal.io/sdk/client" "go.temporal.io/sdk/workflow" "google.golang.org/protobuf/types/known/durationpb" "go.temporal.io/server/common/convert" "go.temporal.io/server/service/history/consts" "github.com/pborman/uuid" enumspb "go.temporal.io/api/enums/v1" "go.temporal.io/sdk/temporal" commandpb "go.temporal.io/api/command/v1" commonpb "go.temporal.io/api/common/v1" historypb "go.temporal.io/api/history/v1" taskqueuepb "go.temporal.io/api/taskqueue/v1" "go.temporal.io/api/workflowservice/v1" "go.temporal.io/server/common/log/tag" "go.temporal.io/server/common/payload" "go.temporal.io/server/common/payloads" ) func (s *FunctionalSuite) TestActivityHeartBeatWorkflow_Success() { id := "functional-heartbeat-test" wt := "functional-heartbeat-test-type" tl := "functional-heartbeat-test-taskqueue" identity := "worker1" activityName := "activity_timer" workflowType := &commonpb.WorkflowType{Name: wt} taskQueue := &taskqueuepb.TaskQueue{Name: tl, Kind: enumspb.TASK_QUEUE_KIND_NORMAL} header := &commonpb.Header{ Fields: map[string]*commonpb.Payload{"tracing": payload.EncodeString("sample data")}, } request := &workflowservice.StartWorkflowExecutionRequest{ RequestId: uuid.New(), Namespace: s.namespace, WorkflowId: id, WorkflowType: workflowType, TaskQueue: taskQueue, Input: nil, Header: header, WorkflowRunTimeout: durationpb.New(100 * time.Second), WorkflowTaskTimeout: durationpb.New(1 * time.Second), Identity: identity, } we, err0 := s.engine.StartWorkflowExecution(NewContext(), request) s.NoError(err0) s.Logger.Info("StartWorkflowExecution", tag.WorkflowRunID(we.RunId)) workflowComplete := false activityCount := int32(1) activityCounter := int32(0) wtHandler := func(execution *commonpb.WorkflowExecuti
func (s *FunctionalSuite) TestActivityRetry_Infinite() { id := "functional-activity-retry-test" wt := "functional-activity-retry-type" tl := "functional-activity-retry-taskqueue" identity := "worker1" activityName := "activity_retry" workflowType := &commonpb.WorkflowType{Name: wt} taskQueue := &taskqueuepb.TaskQueue{Name: tl, Kind: enumspb.TASK_QUEUE_KIND_NORMAL} request := &workflowservice.StartWorkflowExecutionRequest{ RequestId: uuid.New(), Namespace: s.namespace, WorkflowId: id, WorkflowType: workflowType, TaskQueue: taskQueue, Input: nil, WorkflowRunTimeout: durationpb.New(100 * time.Second), WorkflowTaskTimeout: durationpb.New(1 * time.Second), Identity: identity, } we, err0 := s.engine.StartWorkflowExecution(NewContext(), request) s.NoError(err0) s.Logger.Info("StartWorkflowExecution", tag.WorkflowRunID(we.RunId)) workflowComplete := false activitiesScheduled := false wtHandler := func(execution *commonpb.WorkflowExecution, wt *commonpb.WorkflowType, previousStartedEventID, startedEventID int64, history *historypb.History) ([]*commandpb.Command, error) { if !activitiesScheduled { activitiesScheduled = true return []*commandpb.Command{{ CommandType: enumspb.COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK, Attributes: &commandpb.Command_ScheduleActivityTaskCommandAttributes{ ScheduleActivityTaskCommandAttributes: &commandpb.ScheduleActivityTaskCommandAttributes{ ActivityId: "A", ActivityType: &commonpb.ActivityType{Name: activityName}, TaskQueue: &taskqueuepb.TaskQueue{Name: tl, Kind: enumspb.TASK_QUEUE_KIND_NORMAL}, Input: payloads.EncodeString("1"), StartToCloseTimeout: durationpb.New(100 * time.Second), RetryPolicy: &commonpb.RetryPolicy{ MaximumAttempts: 0, BackoffCoefficient: 1, }, }}, }}, nil } workflowComplete = true return []*commandpb.Command{{ CommandType: enumspb.COMMAND_TYPE_COMPLETE_WORKFLOW_EXECUTION, Attributes: &commandpb.Command_CompleteWorkflowExecutionCommandAttributes{ CompleteWorkflowExecutionCommandAttributes: &commandpb.CompleteWorkflowExecutionCommandAttributes{ Result: payloads.EncodeString("Done"), }, }, }}, nil } activityExecutedCount := 0 activityExecutedLimit := 4 atHandler := func(execution *commonpb.WorkflowExecution, activityType *commonpb.ActivityType, activityID string, input *commonpb.Payloads, taskToken []byte) (*commonpb.Payloads, bool, error) { s.Equal(id, execution.GetWorkflowId()) s.Equal(activityName, activityType.GetName()) var err error if activityExecutedCount < activityExecutedLimit { err = errors.New("retry-error") } else if activityExecutedCount == activityExecutedLimit { err = nil } activityExecutedCount++ return nil, false, err } poller := &TaskPoller{ Engine: s.engine, Namespace: s.namespace, TaskQueue: taskQueue, Identity: identity, WorkflowTaskHandler: wtHandler, ActivityTaskHandler: atHandler, Logger: s.Logger, T: s.T(), } _, err := poller.PollAndProcessWorkflowTask() s.NoError(err) for i := 0; i <= activityExecutedLimit; i++ { err = poller.PollAndProcessActivityTask(false) s.NoError(err) } _, err = poller.PollAndProcessWorkflowTask(WithRetries(1)) s.NoError(err) s.True(workflowComplete) }
200,197
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _offering_class.rs path of file: ./repos/aws-sdk-rust/sdk/applicationdiscovery/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// When writing a match expression against `OfferingClass`, it is important to
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self { OfferingClass::Convertible => write!(f, "CONVERTIBLE"), OfferingClass::Standard => write!(f, "STANDARD"), OfferingClass::Unknown(value) => write!(f, "{}", value), } }
779,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: log.go path of file: ./repos/7days-golang/gee-orm/day1-database-sql/log the code of the file until where you have to start completion: package log import ( "io/ioutil" "log" "os" "sync" ) var ( errorLog = log.New(os.Stdout, "\033[31m[error]\033[0m ", lo
func SetLevel(level int) { mu.Lock() defer mu.Unlock() for _, logger := range loggers { logger.SetOutput(os.Stdout) } if ErrorLevel < level { errorLog.SetOutput(ioutil.Discard) } if InfoLevel < level { infoLog.SetOutput(ioutil.Discard) } }
40,405
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: import_archival_objects.rb path of file: ./repos/archivesspace/backend/app/lib/bulk_import the code of the file until where you have to start completion: require_relative "bulk_import_parser" class ImportArchivalObjects < BulkImportParser START_MARKER = /ArchivesSpace field code/.freeze def initialize(input_file, content_type, current_user, opts, log_method = nil) s
def process_subjects ret_subjs = [] repo_id = @repository.split("/")[2] (1..10).each do |num| unless @row_hash["subject_#{num}_record_id"].nil? && @row_hash["subject_#{num}_term"].nil? subj = nil begin subj = @sh.get_or_create(@row_hash["subject_#{num}_record_id"], @row_hash["subject_#{num}_term"], @row_hash["subject_#{num}_type"], @row_hash["subject_#{num}_source"], repo_id, @report) ret_subjs.push subj if subj rescue Exception => e @report.add_errors(I18n.t("bulk_import.error.process_error", :type => "Subject", :num => num, :why => e.message)) end end
583,720
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ipnet.go path of file: ./repos/agones/vendor/k8s.io/utils/net the code of the file until where you have to start completion: /* Copyright 2016 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 ParseIPNets(specs ...string) (IPNetSet, error) { ipnetset := make(IPNetSet) for _, spec := range specs { spec = strings.TrimSpace(spec) _, ipnet, err := ParseCIDRSloppy(spec) if err != nil { return nil, err } k := ipnet.String() // In case of normalization ipnetset[k] = ipnet } return ipnetset, nil }
446,406
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: lmtest1.m path of file: ./repos/malini/Codes/FC_EC_calculation code/DynamicFC/jplv7/Ucsd_garch/Tests the code of the file until where you have to start completion: function results = lmtest1(data,q) % PURPOSE: % Performs an LM test for the presense of autocorrelation in q lags % Under the null of no serial correlation, this is asymptotically % distributed X2(q) % % USAGE: % results = lmtest1(data,q) % % INPUTS: % data - A set of deviates from a process with or without mean % q- The maximum number of lags to regress on. The statistic and pval will be returned for all sets of % lagged squarrd residuals up to and including q % % OUTPUTS: % results, a structure with fields: % % statistic - A Qx1 vector of statistics % pval - A Qx1 set of appropriate pvals % % % COMMENTS: % % % Author: Kevin Sheppard % kevin.sheppard@economics.ox.ac.uk
function results = lmtest1(data,q) % PURPOSE: % Performs an LM test for the presense of autocorrelation in q lags % Under the null of no serial correlation, this is asymptotically % distributed X2(q) % % USAGE: % results = lmtest1(data,q) % % INPUTS: % data - A set of deviates from a process with or without mean % q- The maximum number of lags to regress on. The statistic and pval will be returned for all sets of % lagged squarrd residuals up to and including q % % OUTPUTS: % results, a structure with fields: % % statistic - A Qx1 vector of statistics % pval - A Qx1 set of appropriate pvals % % % COMMENTS: % % % Author: Kevin Sheppard % kevin.sheppard@economics.ox.ac.uk % Revision: 2 Date: 12/31/2001 statistic=zeros(q,1); pval=zeros(q,1); for i=1:q [y,x]=newlagmatrix(data,i,1); beta = x\y; rsquared=1-((y-x*beta)'*(y-x*beta)/((y-mean(y))'*(y-mean(y)))); statistic(i)=length(y)*rsquared; end
386,154
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: container_prune_test.go path of file: ./repos/moby/client the code of the file until where you have to start completion: package client // import "github.com/docker/docker/client" import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "testing" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/errdefs" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" ) func TestContainersPruneError(t *testing.T) { client := &Client{ client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), version: "1.25", } _, err := client.ContainersPrune(context.Background(), filters.Args{}) assert.Check(t, is.ErrorType(err, errdefs.IsSystem)) } func TestContainersPrune(t *testing.T) { expectedURL := "/v1.25/containers/prune" listCases := []struct { filters filters.Args expectedQueryParams map[string]string }{ { filters: filters.Args{}, expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": "", }, }, { filters: filters.NewArgs(filters.Arg("dangling", "true")), expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": `{"dangling":{"true":true}}`, }, }, { filters: filters.NewArgs( filters.Arg("dangling", "true"), filters.Arg("until", "2016-12-15T14:00"), ), expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": `{"dangling":{"true":true},"until":{"2016-12-15T14:00":true}}`, }, }, { filters: filters.NewArgs(filters.Arg("dangling", "false")), expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": `{"dangling":{"false":true}}`, }, }, { filters: filters.NewArgs( filters.Arg("dangling", "true"), filters.Arg("label", "label1=foo"), filters.Arg("label", "label2!=bar"), ),
func TestContainersPrune(t *testing.T) { expectedURL := "/v1.25/containers/prune" listCases := []struct { filters filters.Args expectedQueryParams map[string]string }{ { filters: filters.Args{}, expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": "", }, }, { filters: filters.NewArgs(filters.Arg("dangling", "true")), expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": `{"dangling":{"true":true}}`, }, }, { filters: filters.NewArgs( filters.Arg("dangling", "true"), filters.Arg("until", "2016-12-15T14:00"), ), expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": `{"dangling":{"true":true},"until":{"2016-12-15T14:00":true}}`, }, }, { filters: filters.NewArgs(filters.Arg("dangling", "false")), expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": `{"dangling":{"false":true}}`, }, }, { filters: filters.NewArgs( filters.Arg("dangling", "true"), filters.Arg("label", "label1=foo"), filters.Arg("label", "label2!=bar"), ), expectedQueryParams: map[string]string{ "until": "", "filter": "", "filters": `{"dangling":{"true":true},"label":{"label1=foo":true,"label2!=bar":true}}`, }, }, } for _, listCase := range listCases { client := &Client{ client: newMockClient(func(req *http.Request) (*http.Response, error) { if !strings.HasPrefix(req.URL.Path, expectedURL) { return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) } query := req.URL.Query() for key, expected := range listCase.expectedQueryParams { actual := query.Get(key) assert.Check(t, is.Equal(expected, actual)) } content, err := json.Marshal(types.ContainersPruneReport{ ContainersDeleted: []string{"container_id1", "container_id2"}, SpaceReclaimed: 9999, }) if err != nil { return nil, err } return &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(content)), }, nil }), version: "1.25", } report, err := client.ContainersPrune(context.Background(), listCase.filters) assert.Check(t, err) assert.Check(t, is.Len(report.ContainersDeleted, 2)) assert.Check(t, is.Equal(uint64(9999), report.SpaceReclaimed)) } }
656,229
You are an expert in writing code in many different languages. Your goal is 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_models.rs path of file: ./repos/aws-sdk-rust/sdk/apigateway/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 `GetModels`. #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug)] #[non_exhaustive] pub struct GetModels; impl GetModels { /// Creates
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::BadRequestException(_inner) => _inner.fmt(f), Self::NotFoundException(_inner) => _inner.fmt(f), Self::TooManyRequestsException(_inner) => _inner.fmt(f), Self::UnauthorizedException(_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") } } } }
786,750
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: logger_test.go path of file: ./repos/martian/martianlog the code of the file until where you have to start completion: // Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LI
func TestLoggerFromJSON(t *testing.T) { msg := []byte(`{ "log.Logger": { "scope": ["request", "response"], "headersOnly": true, "decode": true } }`) r, err := parse.FromJSON(msg) if err != nil { t.Fatalf("parse.FromJSON(): got %v, want no error", err) } reqmod := r.RequestModifier() if reqmod == nil { t.Fatal("r.RequestModifier(): got nil, want not nil") } if _, ok := reqmod.(*Logger); !ok { t.Error("reqmod.(*Logger): got !ok, want ok") } resmod := r.ResponseModifier() if resmod == nil { t.Fatal("r.ResponseModifier(): got nil, want not nil") } l, ok := resmod.(*Logger) if !ok { t.Error("resmod.(*Logger); got !ok, want ok") } if !l.headersOnly { t.Error("l.headersOnly: got false, want true") } if !l.decode { t.Error("l.decode: got false, want true") } }
173,787
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _get_image_frame_output.rs path of file: ./repos/aws-sdk-rust/sdk/medicalimaging/src/operation/get_image_frame the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exha
pub fn build(self) -> crate::operation::get_image_frame::GetImageFrameOutput { crate::operation::get_image_frame::GetImageFrameOutput { image_frame_blob: self.image_frame_blob.unwrap_or_default(), content_type: self.content_type, _request_id: self._request_id, } }
765,656
You are an expert in writing code in many different languages. Your goal is 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.pb.go path of file: ./repos/simplebank/pb the code of the file until where you have to start completion: // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // pr
func (x *User) Reset() { *x = User{} if protoimpl.UnsafeEnabled { mi := &file_user_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
139,234
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: subject_fixtures.go path of file: ./repos/photoprism/internal/entity the code of the file until where you have to start completion: package entity type SubjectMap map[string]Subject func (m SubjectMap) Get(name string) Subjec
func (m SubjectMap) Get(name string) Subject { if result, ok := m[name]; ok { return result } return Subject{} }
400,221
You are an expert in writing code in many different languages. Your goal is 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/vpclattice/src/operation/batch_update_rule 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, } }
776,497
You are an expert in writing code in many different languages. Your goal is 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.pb.go path of file: ./repos/teller/vendor/go.etcd.io/etcd/api/v3/authpb the code of the file until where you have to start completion: // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: auth.proto package authpb import ( fmt "fmt" io "io" math "math" math_bits "math/bits" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/golang/protobuf/proto" ) // Reference imports to suppress er
func (m *UserAddOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_UserAddOptions.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } }
527,136
You are an expert in writing code in many different languages. Your goal is 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_QueryLists.go path of file: ./repos/aws-sdk-go-v2/internal/protocoltest/ec2query the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package ec2query import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/internal/protocoltest/ec2query/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // This test serializes simple and complex lists. func (c *Client) QueryLists(ctx context.Context, params *QueryListsInput, optFns ...func(*Options)) (*QueryListsOutput, error) { if params == nil { params = &QueryListsInput{} } result, metadata, err := c.invokeOperation(ctx, "QueryLists", params, optFns, c.addOperationQueryListsMiddlewares) if err != nil { return nil, err } out := result.(*QueryListsOutput) out.ResultMetadata = metadata return out, nil } type QueryListsInput struct { ComplexListArg []types.GreetingStruct ListArg []string ListArgWithXmlName []string ListArgWithXmlNameMember []string NestedWithList *types.NestedStru
func (c *Client) addOperationQueryListsMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsEc2query_serializeOpQueryLists{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsEc2query_deserializeOpQueryLists{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "QueryLists"); err != nil { return fmt.Errorf("add protocol finalizers: %v", err) } if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = addClientRequestID(stack); err != nil { return err } if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addComputePayloadSHA256(stack); err != nil { return err } if err = addRetry(stack, options); err != nil { return err } if err = addRawResponseToMetadata(stack); err != nil { return err } if err = addRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opQueryLists(options.Region), middleware.Before); err != nil { return err } if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } if err = addDisableHTTPSMiddleware(stack, options); err != nil { return err } return nil }
215,443
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: fake.go path of file: ./repos/agones/vendor/k8s.io/client-go/tools/record the code of the file until where you have to start completion: /* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License
func annotationsString(annotations map[string]string) string { if len(annotations) == 0 { return "" } else { return " " + fmt.Sprint(annotations) } }
446,353
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: transformer.rs path of file: ./repos/sea-orm/sea-orm-codegen/src/entity the code of the file until where you have to start completion: use crate::{ util::unpack_table_ref, ActiveEnum, Column, ConjunctRelation, Entity, EntityWriter, Error, PrimaryKey, Relation, RelationType, }; use sea_query::{ColumnSpec, TableCreateStatement}; use std::collections::{BTreeMap, HashMap}; #[derive(Clone, Debug)] pub struct EntityTransformer; impl EntityTransformer { pub fn transform(table_create_stmts: Vec<TableCreateStatement>) -> Result<EntityWriter, Error
fn many_to_many() -> Result<(), Box<dyn Error>> { use crate::tests_cfg::many_to_many::*; let schema = Schema::new(DbBackend::Postgres); validate_compact_entities( vec![ schema.create_table_from_entity(bills::Entity), schema.create_table_from_entity(users::Entity), schema.create_table_from_entity(users_votes::Entity), ], vec![ ("bills", include_str!("../tests_cfg/many_to_many/bills.rs")), ("users", include_str!("../tests_cfg/many_to_many/users.rs")), ( "users_votes", include_str!("../tests_cfg/many_to_many/users_votes.rs"), ), ], ) }
499,477
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: terraform_azure_servicebus_example_test.go path of file: ./repos/terratest/test/azure the code of the file until where you have to start completion: //go:build azure // +build azure // NOTE: We use build tags t
func getMapKeylist(mapList map[string]interface{}) []string { names := make([]string, 0) for key := range mapList { names = append(names, key) } return names }
672,629
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _region.rs path of file: ./repos/aws-sdk-rust/sdk/ec2/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Describes a Region.</p> #[no
pub fn build(self) -> crate::types::Region { crate::types::Region { endpoint: self.endpoint, region_name: self.region_name, opt_in_status: self.opt_in_status, } }
804,511
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: leaveflash.m path of file: ./repos/supermodeling/算法代码案例/蒙特卡罗算法/蒙特卡洛法/蒙特卡洛法 the code of the file until where you have to start completion: function leaveflash(xx,yy,zz)
function leaveflash(xx,yy,zz) global man1 mana1 mana2 mana3 mana4 mana5 global manb1 manb2 manb3 manb4 manb5 global manc1 manc2 manc3 manc4 manc5 global mand1 mand2 mand3 mand4 mand5 global mane1 mane2 mane3 mane4 mane5 switch xx case 1 for ii = 10:-1:1 face(:,1)=man1(:,1)+yy*(ii-1); face(:,3)=man1(:,3)+yy*(ii-1); face(:,2)=man1(:,2)+zz*(ii-1); face(:,4)=man1(:,4)+zz*(ii-1); face(1,3)=0.0982; face(1,4)=0.1381; set(mana1,'position',[face(1,1) face(1,2) face(1,3) face(1,4)]); set(mana2,'X',[face(2,1);face(2,3)],'Y',[face(2,2);face(2,4)]); set(mana3,'X',[face(3,1);face(3,3)],'Y',[face(3,2);face(3,4)]); set(mana4,'X',[face(4,1);face(4,3)],'Y',[face(4,2);face(4,4)]); set(mana5,'X',[face(5,1);face(5,3)],'Y',[face(5,2);face(5,4)]); MM(ii)=getframe; end
155,662
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: grpc_query_test.go path of file: ./repos/cosmos-sdk/tests/integration/distribution/keeper the code of the file until where you have to start completion: package keeper_test import ( "fmt" "testing" "gotest.tools/v3/assert" "cosmossdk.io/collections" "cosmossdk.io/math" "cosmossdk.io/x/distribution/types" stakingtestutil "cosmossdk.io/x/staking/testutil" stakingtypes "cosmossdk.io/x/staking/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" ) func TestGRPCParams(t *testing.T) { t.Parallel() f := initFixture(t) assert.NilError(t, f.distrKeeper.Params.Set(f.sdkCtx,
func TestGRPCValidatorCommission(t *testing.T) { t.Parallel() f := initFixture(t) // set module account coins initTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) assert.NilError(t, f.bankKeeper.MintCoins(f.sdkCtx, types.ModuleName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)))) // Set default staking params assert.NilError(t, f.stakingKeeper.Params.Set(f.sdkCtx, stakingtypes.DefaultParams())) qr := f.app.QueryHelper() queryClient := types.NewQueryClient(qr) // send funds to val addr funds := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, int64(1000)) assert.NilError(t, f.bankKeeper.SendCoinsFromModuleToAccount(f.sdkCtx, types.ModuleName, sdk.AccAddress(f.valAddr), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, funds)))) f.accountKeeper.SetAccount(f.sdkCtx, f.accountKeeper.NewAccountWithAddress(f.sdkCtx, sdk.AccAddress(f.valAddr))) initialStake := int64(10) tstaking := stakingtestutil.NewHelper(t, f.sdkCtx, f.stakingKeeper) tstaking.Commission = stakingtypes.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)) tstaking.CreateValidator(f.valAddr, valConsPk0, math.NewInt(initialStake), true) commission := sdk.DecCoins{sdk.DecCoin{Denom: "token1", Amount: math.LegacyNewDec(4)}, {Denom: "token2", Amount: math.LegacyNewDec(2)}} assert.NilError(t, f.distrKeeper.ValidatorsAccumulatedCommission.Set(f.sdkCtx, f.valAddr, types.ValidatorAccumulatedCommission{Commission: commission})) testCases := []struct { name string msg *types.QueryValidatorCommissionRequest expPass bool expErrMsg string }{ { name: "empty request", msg: &types.QueryValidatorCommissionRequest{}, expPass: false, expErrMsg: "empty validator address", }, { name: "invalid validator", msg: &types.QueryValidatorCommissionRequest{ValidatorAddress: sdk.ValAddress("addr1_______________").String()}, expPass: false, expErrMsg: "validator does not exist", }, { name: "valid request", msg: &types.QueryValidatorCommissionRequest{ValidatorAddress: f.valAddr.String()}, expPass: true, }, } for _, testCase := range testCases { tc := testCase t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { commissionRes, err := queryClient.ValidatorCommission(f.sdkCtx, tc.msg) if tc.expPass { assert.NilError(t, err) assert.Assert(t, commissionRes != nil) assert.DeepEqual(t, commissionRes.Commission.Commission, commission) } else { assert.ErrorContains(t, err, tc.expErrMsg) assert.Assert(t, commissionRes == nil) } }) } }
29,017
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: oracle9i_xdb_pass.rb path of file: ./repos/metasploit-framework/modules/exploits/windows/http the code of the file until where you have to start completion: ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = GreatRanking include Msf::Exploit::
def initialize(info = {}) super(update_info(info, 'Name' => 'Oracle 9i XDB HTTP PASS Overflow (win32)', 'Description' => %q{ This module exploits a stack buffer overflow in the authorization code of the Oracle 9i HTTP XDB service. David Litchfield, has illustrated multiple vulnerabilities in the Oracle 9i XML Database (XDB), during a seminar on "Variations in exploit methods between Linux and Windows" presented at the Blackhat conference. }, 'Author' => [ 'MC' ], 'License' => MSF_LICENSE, 'References' => [ ['CVE', '2003-0727'], ['OSVDB', '2449'], ['BID', '8375'], ['URL', 'http://www.blackhat.com/presentations/bh-usa-03/bh-us-03-litchfield-paper.pdf'], ], 'DefaultOptions' => { 'EXITFUNC' => 'thread', }, 'Privileged' => true, 'Payload' => { 'Space' => 400, 'BadChars' => "\x00", 'PrependEncoder' => "\x81\xc4\xff\xef\xff\xff\x44", }, 'Platform' => 'win', 'Targets' => [ [ 'Oracle 9.2.0.1 Universal', { 'Ret' => 0x60616d46 } ], ], 'DefaultTarget' => 0, 'DisclosureDate' => '2003-08-18')) register_options( [ Opt::RPORT(8080) ]) end
743,881
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: services.go path of file: ./repos/kubernetes/pkg/quota/v1/evaluator/core the code of the file until where you have to start completion: /* Copyright 2016 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 ob
func toExternalServiceOrError(obj runtime.Object) (*corev1.Service, error) { svc := &corev1.Service{} switch t := obj.(type) { case *corev1.Service: svc = t case *api.Service: if err := k8s_api_v1.Convert_core_Service_To_v1_Service(t, svc, nil); err != nil { return nil, err } default: return nil, fmt.Errorf("expect *api.Service or *v1.Service, got %v", t) } return svc, nil }
359,319
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: types.go path of file: ./repos/fibratus/pkg/outputs/amqp/_fixtures/garagemq/amqp the code of the file until where you have to start completion: package amqp import ( "bytes" "github.com/rabbitstack/fibratus/pkg/outputs/amqp/_fixtures/garagemq/pool" "sync/atomic" "time" ) var emptyMessageBufferPool = pool.NewBufferPool(0) // Table - simple amqp-table implementation type Table map[string]interface{} // Decimal represents amqp-decimal data type Decimal struct { Scale uint8 Value int32 } // Frame is raw frame type Frame struct { ChannelID uint16 Type byte CloseAfter bool Sync boo
func (m *Message) Marshal(protoVersion string) (data []byte, err error) { buffer := emptyMessageBufferPool.Get() defer emptyMessageBufferPool.Put(buffer) if err = WriteLonglong(buffer, m.ID); err != nil { return nil, err } if err = WriteContentHeader(buffer, m.Header, protoVersion); err != nil { return nil, err } if err = WriteShortstr(buffer, m.Exchange); err != nil { return nil, err } if err = WriteShortstr(buffer, m.RoutingKey); err != nil { return nil, err } for _, frame := range m.Body { if err = WriteFrame(buffer, frame); err != nil { return nil, err } } data = make([]byte, buffer.Len()) copy(data, buffer.Bytes()) return }
548,966
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: meeg.m path of file: ./repos/spm/@meeg the code of the file until where you have to start completion: function D = meeg(varargin) % Function for creating meeg objects. % FORMAT % D = meeg; % returns an empty object % D = meeg(D); % converts a D struct to object or does nothing if already % object % D = meeg(nchannels, nsamples, ntrials) % return a time dataset with default settings % D = meeg(nchannels, nfrequencies, nsamples, ntrials) % return TF time dataset with default settings % % SPM MEEG format consists of a header object optionally linked to % binary data file. The object is usually saved in the header mat file % % The header file will contain a struct called D. All % information other than data is contained in this struct and access to the % data is via methods of the object. Also, arbitrary data can be stored % inside the object if their field names do not conflict with existing % methods' names. % % The following is a description of the internal implementation of meeg. % % Fields of meeg: % .type - type of data in the file: 'continuous', 'single', 'evoked' % .Fsample - sampling rate % % .data - file_array object linking to the data or empty if unlinked % % % .Nsamples - length of the trial (whole data if the file is continuous). % .timeOnset - the peri-stimulus time of the first sample in the trial (in sec) % % .fname, .path - strings added by spm_eeg_load to keep track of where a % header struct was loaded from. % % .trials - this describes the segments of the epoched file and is also a % structure array. % % Subfields of .trials % % .label - user-specified string for the condition % .onset - time of the first sample in seconds in terms of the % original file % .bad - 0 or 1 flag to allow rejection of trials. % .repl - for epochs that are averages - number of replications used % for the average. % .tag - the user can put any data here that will be attached to
function D = meeg(varargin) % Function for creating meeg objects. % FORMAT % D = meeg; % returns an empty object % D = meeg(D); % converts a D struct to object or does nothing if already % object % D = meeg(nchannels, nsamples, ntrials) % return a time dataset with default settings % D = meeg(nchannels, nfrequencies, nsamples, ntrials) % return TF time dataset with default settings % % SPM MEEG format consists of a header object optionally linked to % binary data file. The object is usually saved in the header mat file % % The header file will contain a struct called D. All % information other than data is contained in this struct and access to the % data is via methods of the object. Also, arbitrary data can be stored % inside the object if their field names do not conflict with existing % methods' names. % % The following is a description of the internal implementation of meeg. % % Fields of meeg: % .type - type of data in the file: 'continuous', 'single', 'evoked' % .Fsample - sampling rate % % .data - file_array object linking to the data or empty if unlinked % % % .Nsamples - length of the trial (whole data if the file is continuous). % .timeOnset - the peri-stimulus time of the first sample in the trial (in sec) % % .fname, .path - strings added by spm_eeg_load to keep track of where a % header struct was loaded from. % % .trials - this describes the segments of the epoched file and is also a % structure array. % % Subfields of .trials % % .label - user-specified string for the condition % .onset - time of the first sample in seconds in terms of the % original file % .bad - 0 or 1 flag to allow rejection of trials. % .repl - for epochs that are averages - number of replications used % for the average. % .tag - the user can put any data here that will be attached to % the respective trial. This is useful e.g. to make sure the % relation between regressors and data is not broken when % removing bad trials or merging files. % .events - this is a structure array describing events related to % each trial. % % Subfields of .events % % .type - string (e.g. 'front panel trigger') % .value - number or string, can be empty (e.g. 'Trig 1'). % .time - in seconds in terms of the original file % .duration - in seconds % % .channels - This is a structure array which is a field of meeg. % length(channels) should equal size(.data.y, 1) and the order % must correspond to the order of channels in the data. % % Subfields of .channels % % .label - channel label which is always a string % .type - a string, possible values - 'MEG', 'EEG', 'VEOG', 'HEOG', % 'EMG' ,'LFP' etc. % .units - units of the data in the channel. % .bad - 0 or 1 flag to mark channels as bad. % .X_plot2D, .Y_plot2D - positions on 2D plane (formerly in ctf). NaN % for channels that should not be plotted. % % .sensors % % % Subfields of .sensors (optional) % .meg - struct with sensor positions for MEG (subfields: .pnt .ori .tra .label) % .eeg - struct with sensor positions for MEG (subfields: .pnt .tra .label) % % .fiducials - headshape and fiducials for coregistration with sMRI % % Subfiels of .fiducials (optional) % .pnt - headshape points % .fid.pnt - fiducial points % .fid.label - fiducial labels % % .transform - additional information for transformed (most commonly time-frequency) data % Subfields of .transform % .ID - 'time', 'TF', or 'TFphase' % .frequencies (optional) % % .history - structure array describing commands that modified the file. % % Subfields of .history: % % .function - string, the function name % .arguments - cell array, the function arguments % .time - when function call was made % % .other - structure used to store other information bits, not fitting the % object structure at the moment, % for example: % .inv - structure array corresponding to the forw/inv problem in MEEG. % .val - index of the 'inv' solution currently used. % % .condlist - cell array of unique condition labels defining the proper % condition order % % .montage - structure used to store info on on-line montage used % .M contains transformation matrix of the montage and names of % original and new channels (+ new channels definition) % .Mind indicates which montage to use %__________________________________________________________________________ % Vladimir Litvak % Copyright (C) 2008-2022 Wellcome Centre for Human Neuroimaging switch nargin case 0 D = struct('Nsamples', 0); case 1 D = varargin{1}; case 2 error('Illegal number of arguments'); case 3 D = struct('Nsamples', varargin{2}, ... 'channels', struct('bad', num2cell(zeros(1, varargin{1}))), ... 'trials', struct('bad', num2cell(zeros(1, varargin{3})))); case 4 D = struct('Nsamples', varargin{3}, ... 'channels', struct('bad', num2cell(zeros(1, varargin{1}))), ... 'trials', struct('bad', num2cell(zeros(1, varargin{4})))); D.transform.ID = 'TF'; D.transform.frequencies = 1:varargin{2}; end
718,742
You are an expert in writing code in many different languages. Your goal is 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_start_trial.go path of file: ./repos/go-elasticsearch/typedapi/license/poststarttrial the code of the file until where you have to start completion: // Licensed to Elasticsearch B.V. under one or more contributor // license agre
func (r PostStartTrial) IsSuccess(providedCtx context.Context) (bool, error) { var ctx context.Context r.spanStarted = true if instrument, ok := r.instrument.(elastictransport.Instrumentation); ok { ctx = instrument.Start(providedCtx, "license.post_start_trial") defer instrument.Close(ctx) } if ctx == nil { ctx = providedCtx } res, err := r.Perform(ctx) if err != nil { return false, err } io.Copy(ioutil.Discard, res.Body) err = res.Body.Close() if err != nil { return false, err } if res.StatusCode >= 200 && res.StatusCode < 300 { return true, nil } if res.StatusCode != 404 { err := fmt.Errorf("an error happened during the PostStartTrial query execution, status code: %d", res.StatusCode) if instrument, ok := r.instrument.(elastictransport.Instrumentation); ok { instrument.RecordError(ctx, err) } return false, err } return false, nil }
671,721
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: add.go path of file: ./repos/rancher/pkg/data/management the code of the file until where you have to start completion: package management import ( "context" "github.com/rancher/rancher/pkg/auth/data" "github.com/rancher/rancher/pkg/types/config" "github.com/rancher/rancher/pkg/wrangl
func Add(ctx context.Context, wrangler *wrangler.Context, management *config.ManagementContext) error { if err := sshKeyCleanup(management); err != nil { return err } _, err := addRoles(wrangler, management) if err != nil { return err } if err := addClusterRoleForNamespacedCRDs(management); err != nil { return err } if err := data.AuthConfigs(management); err != nil { return err } if err := syncCatalogs(management); err != nil { return err } if err := addDefaultPodSecurityPolicyTemplates(management); err != nil { return err } if err = addDefaultPodSecurityAdmissionConfigurationTemplates(management); err != nil { return err } if err := addKontainerDrivers(management); err != nil { return err } if err := addCattleGlobalNamespaces(management); err != nil { return err } return addMachineDrivers(management) }
681,411
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: with_feature_flag_actors.rb path of file: ./repos/gitlabhq/lib/gitlab/gitaly_client the code of the file until where you have to start completion: # frozen_string_literal: true module Gitlab module GitalyClient # This module is responsible for collecting feature flag actors in Gitaly Client. Unlike normal feature flags used # in
def gitaly_feature_flag_actors(repository) container = find_repository_container(repository) { repository: repository, user: Feature::Gitaly.user_actor, project: Feature::Gitaly.project_actor(container), group: Feature::Gitaly.group_actor(container) } end
297,672
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: transformation_matrix.rb path of file: ./repos/hexapdf/lib/hexapdf/content the code of the file until where you have to start completion: # -*- encoding: utf-8; frozen_string_literal: true -*- # #-- # This f
def premultiply(a, b, c, d, e, f) a1 = a * @a + b * @c b1 = a * @b + b * @d c1 = c * @a + d * @c d1 = c * @b + d * @d @e = e * @a + f * @c + @e @f = e * @b + f * @d + @f @a = a1 @b = b1 @c = c1 @d = d1 self end
362,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: _byoasn.rs path of file: ./repos/aws-sdk-rust/sdk/ec2/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.
pub fn build(self) -> crate::types::Byoasn { crate::types::Byoasn { asn: self.asn, ipam_id: self.ipam_id, status_message: self.status_message, state: self.state, } }
804,776
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: role.go path of file: ./repos/agones/vendor/k8s.io/client-go/kubernetes/typed/rbac/v1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not 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" B
func (c *roles) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RoleList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.RoleList{} err = c.client.Get(). Namespace(c.ns). Resource("roles"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return }
445,980
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: reko_maker.m path of file: ./repos/OMEGA/source the code of the file until where you have to start completion: function rekot = reko_maker(options) % Form the boolean vector that tells what algorithms and/or priors are used % Indices: % 1 = MLEM, 2 = OSEM, 3 = MRAMLA, 4 = RAMLA, 5 = ROSEM, 6 = RBI, 7 = DRAMA, % 8 = COSEM, 9 = ECOSEM, 10 = ACOSEM, 11 = OSL-OSEM MRP, 12 = OSL-MLEM MRP, % 13 = BSREM MRP, 14 = MBSREM MRP, 15 = ROSEM-MAP MRP, 16 = RBI-OSL MRP, 17 % - 22 = Quadratic, 23 - 28 = L-filter, 29 - 34 = FMH, 35 - 40 = Weighted % mean, 41 - 46 = TV, 47 - 52 = AD, 53 - 58 = APLS % Total ML-methods + Total MAP-methods * Total number of priors + extra % space for image properties
function rekot = reko_maker(options) % Form the boolean vector that tells what algorithms and/or priors are used % Indices: % 1 = MLEM, 2 = OSEM, 3 = MRAMLA, 4 = RAMLA, 5 = ROSEM, 6 = RBI, 7 = DRAMA, % 8 = COSEM, 9 = ECOSEM, 10 = ACOSEM, 11 = OSL-OSEM MRP, 12 = OSL-MLEM MRP, % 13 = BSREM MRP, 14 = MBSREM MRP, 15 = ROSEM-MAP MRP, 16 = RBI-OSL MRP, 17 % - 22 = Quadratic, 23 - 28 = L-filter, 29 - 34 = FMH, 35 - 40 = Weighted % mean, 41 - 46 = TV, 47 - 52 = AD, 53 - 58 = APLS % Total ML-methods + Total MAP-methods * Total number of priors + extra % space for image properties % % % % Copyright (C) 2020 Ville-Veikko Wettenhovi % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <https://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ML-methods = 10, MAP-methods = 8, Priors = 11 + custom if ~isfield(options,'custom') options.custom = false; end
495,758
You are an expert in writing code in many different languages. Your goal is 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/cleanrooms/src/operation/get_protected_query the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use crate::operation::get_prote
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, } }
797,801
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: command.go path of file: ./repos/seaweedfs/weed/command the code of the file until where you have to start completion: package command import ( "fmt" "os" "strings" flag "github.com/seaweedfs/seaweedfs/weed/util/fla9" ) var Commands = []*Command{ cmdAutocomplete, c
func (c *Command) Usage() { fmt.Fprintf(os.Stderr, "Example: weed %s\n", c.UsageLine) fmt.Fprintf(os.Stderr, "Default Usage:\n") c.Flag.PrintDefaults() fmt.Fprintf(os.Stderr, "Description:\n") fmt.Fprintf(os.Stderr, " %s\n", strings.TrimSpace(c.Long)) os.Exit(2) }
274,169
You are an expert in writing code in many different languages. Your goal is 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_test.go path of file: ./repos/nanobox/models the code of the file until where you have to start completion: package models import ( "testing" ) type data struct { Name string Number int } func init()
func TestTruncate(t *testing.T) { mickey := data{Name: "Mickey"} minnie := data{Name: "Minnie"} put("user", "1", mickey) put("user", "2", minnie) if err := truncate("users"); err != nil { t.Errorf("failed to truncate users: %s", err.Error()) } users, err := keys("users") if err != nil { t.Errorf("failed to list keys for 'user' bucket: %s", err.Error()) } if len(users) != 0 { t.Errorf("'users' bucket was not truncated") } }
120,801
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ephemeralcontainer.go path of file: ./repos/hubble-ui/backend/vendor/k8s.io/client-go/applyconfigurations/core/v1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain
func (b *EphemeralContainerApplyConfiguration) WithEnv(values ...*EnvVarApplyConfiguration) *EphemeralContainerApplyConfiguration { for i := range values { if values[i] == nil { panic("nil value passed to WithEnv") } b.Env = append(b.Env, *values[i]) } return b }
379,877
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: record.rs path of file: ./repos/tremor-runtime/tremor-script/src/std_lib the code of the file until where you have to start completion: // Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2
fn is_empty() { let f = fun("record", "is_empty"); let v = literal!({ "this": "is", "a": "test" }); assert_val!(f(&[&v]), false); let v = Value::object(); assert_val!(f(&[&v]), true); }
752,016
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: deployment.go path of file: ./repos/faas-netes/vendor/k8s.io/client-go/listers/apps/v1 the code of the file until where you have to start completion: /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compli
func (s deploymentNamespaceLister) Get(name string) (*v1.Deployment, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1.Resource("deployment"), name) } return obj.(*v1.Deployment), nil }
426,122
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: order_clause.rb path of file: ./repos/activeadmin/lib/active_admin the code of the file until where you have to start completion: # frozen_string_literal: true module ActiveAdmin class OrderClause attr_reader :field, :order, :active_admin_config def in
def initialize(active_admin_config, clause) clause =~ /^([\w\.]+)(->'\w+')?_(desc|asc)$/ @column = $1 @op = $2 @order = $3 @active_admin_config = active_admin_config @field = [@column, @op].compact.join end
40,780
You are an expert in writing code in many different languages. Your goal is 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_DescribeBillingGroup.go path of file: ./repos/aws-sdk-go-v2/service/iot the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package iot import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/service/iot/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Returns information about a billing group. Requires permission to access the // DescribeBillingGroup (https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions) // action. func (c *Client) DescribeBillingGroup(ctx context.Context, params *DescribeBillingGroupInput, optFns ...func(*Options)) (*DescribeBillingGroupOutput, error) { if params == nil { params = &DescribeBillingGroupInput{} } result, metadata, err := c.invokeOperation(ctx, "Descr
func (c *Client) addOperationDescribeBillingGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { return err } err = stack.Serialize.Add(&awsRestjson1_serializeOpDescribeBillingGroup{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpDescribeBillingGroup{}, middleware.After) if err != nil { return err } if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeBillingGroup"); err != nil { return fmt.Errorf("add protocol finalizers: %v", err) } if err = addlegacyEndpointContextSetter(stack, options); err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = addClientRequestID(stack); err != nil { return err } if err = addComputeContentLength(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addComputePayloadSHA256(stack); err != nil { return err } if err = addRetry(stack, options); err != nil { return err } if err = addRawResponseToMetadata(stack); err != nil { return err } if err = addRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { return err } if err = addOpDescribeBillingGroupValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeBillingGroup(options.Region), middleware.Before); err != nil { return err } if err = addRecursionDetection(stack); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } if err = addDisableHTTPSMiddleware(stack, options); err != nil { return err } return nil }
226,877
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: polaris_discovery.go path of file: ./repos/gf/contrib/registry/polaris the code of the file until where you have to start completion: // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. package polaris import ( "bytes" "context" "fmt" "strings" "github.com/polarismesh/polaris-go" "github.com/polarismesh/polaris-go/pkg/
func instancesToServiceInstances(instances []model.Instance) []gsvc.Service { var ( serviceInstances = make([]gsvc.Service, 0, len(instances)) endpointStr bytes.Buffer ) for _, instance := range instances { if instance.IsHealthy() { endpointStr.WriteString(fmt.Sprintf("%s:%d%s", instance.GetHost(), instance.GetPort(), gsvc.EndpointsDelimiter)) } } if endpointStr.Len() > 0 { for _, instance := range instances { if instance.IsHealthy() { serviceInstances = append(serviceInstances, instanceToServiceInstance(instance, gstr.TrimRight(endpointStr.String(), gsvc.EndpointsDelimiter), "")) } } } return serviceInstances }
164,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: yandex.rb path of file: ./repos/geocoder/lib/geocoder/results the code of the file until where you have to start completion: require 'geocoder/results/base' module Geocoder::Result class Yandex < Base # Yandex result has difficult tree structure, # and presence of some n
def city result = if state.empty? find_in_hash(@data, *COUNTRY_LEVEL, 'Locality', 'LocalityName') elsif sub_state.empty? find_in_hash(@data, *ADMIN_LEVEL, 'Locality', 'LocalityName') else find_in_hash(@data, *SUBADMIN_LEVEL, 'Locality', 'LocalityName') end
609,771
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: expander.go path of file: ./repos/gotosocial/vendor/github.com/go-openapi/spec the code of the file until where you have to start completion: // Copyright 2015 go-swagger maintainers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distr
func expandItems(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { if target.Items == nil { return &target, nil } // array if target.Items.Schema != nil { t, err := expandSchema(*target.Items.Schema, parentRefs, resolver, basePath) if err != nil { return nil, err } *target.Items.Schema = *t } // tuple for i := range target.Items.Schemas { t, err := expandSchema(target.Items.Schemas[i], parentRefs, resolver, basePath) if err != nil { return nil, err } target.Items.Schemas[i] = *t } return &target, nil }
25,518
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: header_test.go path of file: ./repos/gout/encode the code of the file until where you have to start completion: package encode import ( "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" ) type testH map[s
func TestHeaderStruct(t *testing.T) { req, _ := http.NewRequest("GET", "/", nil) p := &testHeader2{H7: "h7"} err := Encode(testHeader{ H1: "test-header-1", H2: 2, H3: 3.3, testHeader1: testHeader1{ H4: int64(4), H5: int32(5), }, H: &p, }, NewHeaderEncode(req, false), ) assert.NoError(t, err) needVal := []string{"test-header-1", "2", "3.3", "4", "5", "", "h7"} for k, v := range needVal { s := fmt.Sprintf("h%d", k+1) assert.Equal(t, req.Header.Get(s), v) } }
376,830
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: esapi.response_example_test.go path of file: ./repos/go-elasticsearch/esapi the code of the file until where you have to start completion: // Licensed to Elasticsearch B.V
func ExampleResponse_Status() { es, _ := elasticsearch.NewDefaultClient() res, _ := es.Info() log.Println(res.Status()) // 200 OK }
671,969
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: _network_file_definition.rs path of file: ./repos/aws-sdk-rust/sdk/iotfleetwise/src/types the code of the file until where you have to start completion: // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Specifications for defining a vehicle network.</p> #[non_exhaustive] #[derive(::std::clone::Clone, ::std::cmp:
pub fn as_can_dbc(&self) -> ::std::result::Result<&crate::types::CanDbcDefinition, &Self> { if let NetworkFileDefinition::CanDbc(val) = &self { ::std::result::Result::Ok(val) } else { ::std::result::Result::Err(self) } }
815,304
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: setfilesemaphore.m path of file: ./repos/Robotics-Toolbox/rvcdlcs/src/thirdparty/differential-evolution the code of the file until where you have to start completion: function semaphoreCell = setfilesemaphore(fileList, se
function [randomNr, randomStr] = generaterandomnumber %GENERATERANDOMNUMBER % In very unlikely cases, it might happen that the random states of rand % and randn are equal in two Matlab processes calling function % SETFILESEMAPHORE. For this reason, the system and cpu time are used to % create different random numbers even in this unlikely case. % % This all would not be necessary if it were possible to get some sort of a % Matlab process ID. nOfDigits = 8; % length of random string will be 4*nOfDigits randNr = rand; randnNr = mod(randn+0.5, 1); cputimeNr = mod(cputime, 100)/100; nowNr = mod(rem(now,1)*3600*24, 100)/100; % random number is used for random pause after conflict randomNr = 0.25 * (randNr + randnNr + cputimeNr + nowNr); % random string is used for the semaphore file name if nargout > 1 ee = 10^nOfDigits; randomStr = sprintf(... '%0.0f%0.0f%0.0f%0.0f', ... ee * randNr, ... ee * randnNr, ... ee * cputimeNr, ... ee * nowNr ... ); end
78,556
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: config_fuzzer.rb path of file: ./repos/leftovers/spec/support the code of the file until where you have to start completion: # frozen_string_literal: true require 'yaml' module Leftovers class ConfigLoader class Fuzzer # rubocop:disable Metrics/ClassLength def initialize(iteration) srand ::RSpec.configuration.seed + iteration end def to_yaml fuzz_object(DocumentSchema).to_yaml end private def fuzz(schema, nesting = 0) # rubocop:disable Metrics case schema
def fuzz(schema, nesting = 0) # rubocop:disable Metrics case schema when ValueOrArraySchema then fuzz_value_or_array(schema, nesting) when ArraySchema then fuzz_array(schema, nesting) when ValueOrObjectSchema then fuzz_value_or_object(schema, nesting) when ObjectSchema then fuzz_object(schema, nesting) when StringEnumSchema then fuzz_string_enum(schema) when RegexpSchema then fuzz_regexp when StringSchema then fuzz_string when ScalarValueSchema then fuzz_scalar when TrueSchema then fuzz_true when ScalarArgumentSchema then fuzz_string_or_integer when BoolSchema then fuzz_bool else raise UnexpectedCase, "Unhandled value #{schema.inspect}" end
341,484
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: po_parser.rb path of file: ./repos/brew/Library/Homebrew/vendor/bundle-standalone/ruby/2.3.0/gems/i18n-1.5.3/lib/i18n/gettext the code of the file until where you have to start completion: =begin poparser.rb - Generate a .mo Copyright (C) 2003-2009 Masao Mutoh <mutoh at highway.ne.jp> You may redistribute it and/or modify it under the same license terms as Ruby. =end #MODIFIED # removed include GetText etc # added stub translation method _(x) require 'racc/parser' module GetText class PoParser < Racc::Parser def _(x) x end module_eval <<'..end src/poparser.ry modeval..id7a99570e05', 'src/poparser.ry', 108 def unescape(orig) ret = orig.gsub(/\\n/, "\n") ret.gsub!(/\\t/, "\t") ret.gsub!(/\\r/, "\r")
def parse(str, data, ignore_fuzzy = true) @comments = [] @data = data @fuzzy = false @msgctxt = "" $ignore_fuzzy = ignore_fuzzy str.strip! @q = [] until str.empty? do case str when /\A\s+/ str = $' when /\Amsgctxt/ @q.push [:MSGCTXT, $&] str = $' when /\Amsgid_plural/ @q.push [:MSGID_PLURAL, $&] str = $' when /\Amsgid/ @q.push [:MSGID, $&] str = $' when /\Amsgstr/ @q.push [:MSGSTR, $&] str = $' when /\A\[(\d+)\]/ @q.push [:PLURAL_NUM, $1] str = $' when /\A\#~(.*)/ $stderr.print _("Warning: obsolete msgid exists.\n") $stderr.print " #{$&}\n" @q.push [:COMMENT, $&] str = $' when /\A\#(.*)/ @q.push [:COMMENT, $&] str = $' when /\A\"(.*)\"/ @q.push [:STRING, $1] str = $' else #c = str[0,1] #@q.push [:STRING, c] str = str[1..-1] end end
17,893
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: generic_multicast_protocol.go path of file: ./repos/sliver/implant/vendor/gvisor.dev/gvisor/pkg/tcpip/network/internal/ip the code of the file until where you have to start completion: // Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You ma
func (g *GenericMulticastProtocolState) initializeNewMemberLocked(groupAddress tcpip.Address, info *multicastGroupState, callersV2ReportBuilder MulticastGroupProtocolV2ReportBuilder) { if !g.shouldPerformForGroup(groupAddress) { return } info.lastToSendReport = false switch g.mode { case protocolModeV2: info.transmissionLeft = g.robustnessVariable if callersV2ReportBuilder == nil { g.sendV2ReportAndMaybeScheduleChangedTimer(groupAddress, info, MulticastGroupProtocolV2ReportRecordChangeToExcludeMode) } else { callersV2ReportBuilder.AddRecord(MulticastGroupProtocolV2ReportRecordChangeToExcludeMode, groupAddress) info.transmissionLeft-- } case protocolModeV1Compatibility, protocolModeV1: info.transmissionLeft = unsolicitedTransmissionCount g.maybeSendReportLocked(groupAddress, info) default: panic(fmt.Sprintf("unrecognized mode = %d", g.mode)) } }
451,508
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ldap_conn.go path of file: ./repos/chainlink/core/sessions/ldapauth/mocks the code of the file until where you have to start completion: // Code generated by mockery v2.38.0. DO NOT EDIT. package mocks import ( ldap "github.com/go-ldap/ldap/v3" mock "github.
func (_m *LDAPConn) Bind(username string, password string) error { ret := _m.Called(username, password) if len(ret) == 0 { panic("no return value specified for Bind") } var r0 error if rf, ok := ret.Get(0).(func(string, string) error); ok { r0 = rf(username, password) } else { r0 = ret.Error(0) } return r0 }
493,641
You are an expert in writing code in many different languages. Your goal is 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/kubernetes/staging/src/k8s.io/metrics/pkg/apis/custom_metrics/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, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: k8s.io/metrics/pkg/apis/custom_metrics/v1beta1/generated.proto package v1beta1 import ( fmt "fmt" io "io" proto "github.com/gogo/protobuf/proto" v11 "k8s.io/apimachinery/pkg/apis/meta/v1" math "math" math_bits "math/bits" reflect "reflect" strings "strings" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package func (m *MetricListOptions) Rese
func (m *MetricListOptions) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: MetricListOptions: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: MetricListOptions: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field LabelSelector", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.LabelSelector = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field MetricLabelSelector", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } m.MetricLabelSelector = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
355,361
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: uniform_test.go path of file: ./repos/gonum/stat/distmv the code of the file until where you have to start completion: // Copyright ©2017 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package distmv import ( "math" "test
func TestUniformEntropy(t *testing.T) { for _, test := range []struct { Uniform *Uniform Entropy float64 }{ { NewUniform([]r1.Interval{{Min: 0, Max: 1}, {Min: 0, Max: 1}}, nil), 0, }, { NewUniform([]r1.Interval{{Min: -1, Max: 3}, {Min: 2, Max: 8}, {Min: -5, Max: -3}}, nil), math.Log(48), }, } { ent := test.Uniform.Entropy() if math.Abs(ent-test.Entropy) > 1e-14 { t.Errorf("Entropy mismatch. Got %v, want %v", ent, test.Entropy) } } }
690,621
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: powershell_completions.go path of file: ./repos/devspace/vendor/github.com/spf13/cobra the code of the file until where you have to start completion: // Copyright 2013-2022 The Cobra Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compli
func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error { outFile, err := os.Create(filename) if err != nil { return err } defer outFile.Close() return c.genPowerShellCompletion(outFile, includeDesc) }
466,030
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: component.go path of file: ./repos/dapr/pkg/client/listers/components/v1alpha1 the code of the file until where you have to start completion: /* Copyright The Dapr 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
func (s componentNamespaceLister) Get(name string) (*v1alpha1.Component, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1alpha1.Resource("component"), name) } return obj.(*v1alpha1.Component), nil }
89,113
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: parser_test.go path of file: ./repos/minicron/client/vendor/github.com/hashicorp/hcl/hcl/parser the code of the file until where you have to start completion: package parser import ( "fmt" "io/ioutil" "path/filepath" "reflect" "runtime" "strings" "testing" "github.com/hashicorp/hcl/hcl/ast" "github.com/hashicorp/hcl/hcl/token" ) func TestType(t *testing.T) { var literals = []struct { typ token.Type src string }{ {token.STRING, `foo = "foo"`}, {token.NUMBER, `foo = 123`}, {token.NUMBER, `foo = -29`}, {token.FLOAT, `foo = 123.12`}, {token.FLOAT, `foo = -123.12`}, {token.BOOL, `foo = true`}, {token.HEREDOC, "
func TestListOfMaps(t *testing.T) { src := `foo = [ {key = "bar"}, {key = "baz", key2 = "qux"}, ]` p := newParser([]byte(src)) file, err := p.Parse() if err != nil { t.Fatalf("err: %s", err) } // Here we make all sorts of assumptions about the input structure w/ type // assertions. The intent is only for this to be a "smoke test" ensuring // parsing actually performed its duty - giving this test something a bit // more robust than _just_ "no error occurred". expected := []string{`"bar"`, `"baz"`, `"qux"`} actual := make([]string, 0, 3) ol := file.Node.(*ast.ObjectList) objItem := ol.Items[0] list := objItem.Val.(*ast.ListType) for _, node := range list.List { obj := node.(*ast.ObjectType) for _, item := range obj.List.Items { val := item.Val.(*ast.LiteralType) actual = append(actual, val.Token.Text) } } if !reflect.DeepEqual(expected, actual) { t.Fatalf("Expected: %#v, got %#v", expected, actual) } }
349,701
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mq.go path of file: ./repos/terraformer/providers/aws the code of the file until where you have to start completion: // Copyright 2020 The Terraformer Authors. // // Licensed under the Apache License, Version 2.0 (the "Lic
func (g *MQGenerator) InitResources() error { config, e := g.generateConfig() if e != nil { return e } svc := mq.NewFromConfig(config) err := g.loadBrokers(svc) if err != nil { return err } return nil }
531,170
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mergestruct.m path of file: ./repos/matlab-snippets/jsonlab-1.5 the code of the file until where you have to start completion: function s=mergestruct(s1,s2) % % s=mergestruct(s1,s2) % % merge two struct objects into one % % authors:Qianqian Fang (q.fang <at> neu.edu) % date: 2012/12/22 % % input: % s1,s2: a struct object, s1 and s2 can not be arrays % % output: % s: the merged struct object. fields in s1 and s2 will be combined in s. % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) %
function s=mergestruct(s1,s2) % % s=mergestruct(s1,s2) % % merge two struct objects into one % % authors:Qianqian Fang (q.fang <at> neu.edu) % date: 2012/12/22 % % input: % s1,s2: a struct object, s1 and s2 can not be arrays % % output: % s: the merged struct object. fields in s1 and s2 will be combined in s. % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(~isstruct(s1) || ~isstruct(s2)) error('input parameters contain non-struct'); end
148,562
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: PasswordField.m path of file: ./repos/widgets-toolbox/widgets/+wt the code of the file until where you have to start completion: classdef PasswordField < m
function end %methods %% Private methods methods (Access = private) function onPasswordChanged(obj,evt) % Triggered on interaction % Grab the data in string format newValue = string(evt.Data); oldValue = obj.Value; % Look at the states if end
367,337
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: ethereum.rs path of file: ./repos/trezor-firmware/rust/trezor-client/src/client the code of the file until where you have to start completion: use super::{handle_interaction, Trezor}; use crate::{ error::Result, protos::{self, ethereum_sign_tx_eip1559::EthereumAccessList, EthereumTxRequest}, Error, }; /// Access list item. #[derive(Debu
pub fn ethereum_get_address(&mut self, path: Vec<u32>) -> Result<String> { let mut req = protos::EthereumGetAddress::new(); req.address_n = path; let address = handle_interaction( self.call(req, Box::new(|_, m: protos::EthereumAddress| Ok(m.address().into())))?, )?; Ok(address) }
626,724
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: main.go path of file: ./repos/google-cloud-go/internal/generated/snippets/dataproc/apiv1/SessionControllerClient/CancelOperation the code of the file until where you have to start completion: // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain
func main() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in: // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options c, err := dataproc.NewSessionControllerClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &longrunningpb.CancelOperationRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/cloud.google.com/go/longrunning/autogen/longrunningpb#CancelOperationRequest. } err = c.CancelOperation(ctx, req) if err != nil { // TODO: Handle error. } }
283,307
You are an expert in writing code in many different languages. Your goal is 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_CopyObject.go path of file: ./repos/aws-sdk-go-v2/service/s3 the code of the file until where you have to start completion: // Code generated by smithy-go-codegen DO NOT EDIT. package s3 import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sd
func newServiceMetadataMiddleware_opCopyObject(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, OperationName: "CopyObject", } }
233,825
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: mocklogrecord.go path of file: ./repos/fabio/vendor/github.com/opentracing/opentracing-go/mocktracer the code of the file until where you have to start completion: package mocktracer import ( "fmt" "reflect" "time" "github.com/opentracing/opentracing-go/log
func (m *MockKeyValue) EmitLazyLogger(value log.LazyLogger) { var meta MockKeyValue value(&meta) m.Key = meta.Key m.ValueKind = meta.ValueKind m.ValueString = meta.ValueString }
596,321
You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data. Metadata details: filename: context_test.go path of file: ./repos/erda/internal/tools/gittar/webcontext 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.
func TestContext_GetOrgByDomain(t *testing.T) { type fields struct { orgClient org.ClientInterface } type args struct { domain string userID string } tests := []struct { name string fields fields args args want *orgpb.Org wantErr bool }{ { name: "test with error", fields: fields{ orgClient: orgMock{}, }, args: args{ domain: "", }, want: nil, wantErr: true, }, { name: "test with no error", fields: fields{ orgClient: orgMock{}, }, args: args{ domain: "erda", }, want: &orgpb.Org{}, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c := &Context{ orgClient: tt.fields.orgClient, } got, err := c.GetOrgByDomain(tt.args.domain, tt.args.userID) if (err != nil) != tt.wantErr { t.Errorf("GetOrgByDomain() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("GetOrgByDomain() got = %v, want %v", got, tt.want) } }) } }
712,547