file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
test_all.py
# Copyright The PyTorch Lightning team. # # 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. from pytorch_lightning import Callback, Trainer from tests.helpers import BoringModel from tests.helpers.runif import RunIf class BatchHookObserverCallback(Callback): def on_train_batch_start(self, trainer, pl_module, batch, *args): assert batch.device == pl_module.device def on_train_batch_end(self, trainer, pl_module, outputs, batch, *args): assert batch.device == pl_module.device def
(self, trainer, pl_module, batch, *args): assert batch.device == pl_module.device def on_validation_batch_end(self, trainer, pl_module, outputs, batch, *args): assert batch.device == pl_module.device def on_test_batch_start(self, trainer, pl_module, batch, *args): assert batch.device == pl_module.device def on_test_batch_end(self, trainer, pl_module, outputs, batch, *args): assert batch.device == pl_module.device def on_predict_batch_start(self, trainer, pl_module, batch, *args): assert batch.device == pl_module.device def on_predict_batch_end(self, trainer, pl_module, outputs, batch, *args): assert batch.device == pl_module.device class BatchHookObserverModel(BoringModel): def on_train_batch_start(self, batch, *args): assert batch.device == self.device def on_train_batch_end(self, outputs, batch, *args): assert batch.device == self.device def on_validation_batch_start(self, batch, *args): assert batch.device == self.device def on_validation_batch_end(self, outputs, batch, *args): assert batch.device == self.device def on_test_batch_start(self, batch, *args): assert batch.device == self.device def on_test_batch_end(self, outputs, batch, *args): assert batch.device == self.device def on_predict_batch_start(self, batch, *args): assert batch.device == self.device def on_predict_batch_end(self, outputs, batch, *args): assert batch.device == self.device @RunIf(min_gpus=1) def test_callback_batch_on_device(tmpdir): """Test that the batch object sent to the on_*_batch_start/end hooks is on the right device.""" batch_callback = BatchHookObserverCallback() model = BatchHookObserverModel() trainer = Trainer( default_root_dir=tmpdir, max_steps=1, limit_train_batches=1, limit_val_batches=1, limit_test_batches=1, limit_predict_batches=1, accelerator="gpu", devices=1, callbacks=[batch_callback], ) trainer.fit(model) trainer.validate(model) trainer.test(model) trainer.predict(model)
on_validation_batch_start
index.ts
import * as commonPropTypes from './commonPropTypes' export { default as applyAccessibilityKeyHandlers } from './applyAccessibilityKeyHandlers' export { default as AutoControlledComponent } from './AutoControlledComponent' export { default as childrenExist } from './childrenExist' export { default as UIComponent } from './UIComponent' export { createRenderer, felaRenderer } from './felaRenderer' export { default as toCompactArray } from './toCompactArray' export { default as rtlTextContainer } from './rtlTextContainer' export { default as stringLiteralsArray } from './stringLiteralsArray' export { default as getOrGenerateIdFromShorthand } from './getOrGenerateIdFromShorthand' export * from './factories' export { default as constants } from './constants' export { default as mergeThemes } from './mergeThemes'
export { default as mergeProviderContexts } from './mergeProviderContexts' export * from './renderComponent' export { default as renderComponent } from './renderComponent' export { default as getElementProp } from './getElementProp' export { htmlImageProps, htmlInputAttrs, htmlInputEvents, htmlInputProps, partitionHTMLProps, } from './htmlPropsUtils' export { default as isBrowser } from './isBrowser' export { default as doesNodeContainClick } from './doesNodeContainClick' export { pxToRem } from './fontSizeUtility' export { default as createAnimationStyles } from './createAnimationStyles' export { default as createComponent } from './createStardustComponent' export { getKindProp } from './getKindProp' export * from './whatInput' export * from './commonPropInterfaces' export { commonPropTypes }
core.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc; use rustc::{driver, middle}; use rustc::metadata::creader::Loader; use rustc::middle::privacy; use rustc::middle::lint; use syntax::ast; use syntax::parse::token; use syntax; use std::cell::RefCell; use std::os; use collections::{HashSet, HashMap}; use visit_ast::RustdocVisitor; use clean; use clean::Clean; pub enum MaybeTyped { Typed(middle::ty::ctxt), NotTyped(driver::session::Session) } pub type ExternalPaths = RefCell<Option<HashMap<ast::DefId, (Vec<StrBuf>, clean::TypeKind)>>>; pub struct DocContext { pub krate: ast::Crate, pub maybe_typed: MaybeTyped, pub src: Path, pub external_paths: ExternalPaths, } impl DocContext { pub fn sess<'a>(&'a self) -> &'a driver::session::Session { match self.maybe_typed { Typed(ref tcx) => &tcx.sess, NotTyped(ref sess) => sess } } } pub struct CrateAnalysis { pub exported_items: privacy::ExportedItems, pub public_items: privacy::PublicItems, pub external_paths: ExternalPaths, } /// Parses, resolves, and typechecks the given crate fn
(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<StrBuf>) -> (DocContext, CrateAnalysis) { use syntax::codemap::dummy_spanned; use rustc::driver::driver::{FileInput, phase_1_parse_input, phase_2_configure_and_expand, phase_3_run_analysis_passes}; use rustc::driver::config::build_configuration; let input = FileInput(cpath.clone()); let sessopts = driver::config::Options { maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()), addl_lib_search_paths: RefCell::new(libs), crate_types: vec!(driver::config::CrateTypeDylib), lint_opts: vec!((lint::Warnings, lint::allow)), ..rustc::driver::config::basic_options().clone() }; let codemap = syntax::codemap::CodeMap::new(); let diagnostic_handler = syntax::diagnostic::default_handler(syntax::diagnostic::Auto); let span_diagnostic_handler = syntax::diagnostic::mk_span_handler(diagnostic_handler, codemap); let sess = driver::session::build_session_(sessopts, Some(cpath.clone()), span_diagnostic_handler); let mut cfg = build_configuration(&sess); for cfg_ in cfgs.move_iter() { let cfg_ = token::intern_and_get_ident(cfg_.as_slice()); cfg.push(@dummy_spanned(ast::MetaWord(cfg_))); } let krate = phase_1_parse_input(&sess, cfg, &input); let (krate, ast_map) = phase_2_configure_and_expand(&sess, &mut Loader::new(&sess), krate, &from_str("rustdoc").unwrap()); let driver::driver::CrateAnalysis { exported_items, public_items, ty_cx, .. } = phase_3_run_analysis_passes(sess, &krate, ast_map); debug!("crate: {:?}", krate); (DocContext { krate: krate, maybe_typed: Typed(ty_cx), src: cpath.clone(), external_paths: RefCell::new(Some(HashMap::new())), }, CrateAnalysis { exported_items: exported_items, public_items: public_items, external_paths: RefCell::new(None), }) } pub fn run_core(libs: HashSet<Path>, cfgs: Vec<StrBuf>, path: &Path) -> (clean::Crate, CrateAnalysis) { let (ctxt, analysis) = get_ast_and_resolve(path, libs, cfgs); let ctxt = @ctxt; super::ctxtkey.replace(Some(ctxt)); let krate = { let mut v = RustdocVisitor::new(ctxt, Some(&analysis)); v.visit(&ctxt.krate); v.clean() }; let external_paths = ctxt.external_paths.borrow_mut().take(); *analysis.external_paths.borrow_mut() = external_paths; (krate, analysis) }
get_ast_and_resolve
cos_softmax.py
# encoding: utf-8 """ @author: xingyu liao @contact: [email protected] """ import torch from torch import nn import torch.nn.functional as F from torch.nn import Parameter class CosSoftmax(nn.Module): r"""Implement of large margin cosine distance: Args: in_feat: size of each input sample num_classes: size of each output sample """ def __init__(self, cfg, in_feat, num_classes): super().__init__() self.in_features = in_feat self._num_classes = num_classes self.s = cfg.MODEL.HEADS.SCALE self.m = cfg.MODEL.HEADS.MARGIN self.weight = Parameter(torch.Tensor(num_classes, in_feat)) nn.init.xavier_uniform_(self.weight) def forward(self, features, targets): # --------------------------- cos(theta) & phi(theta) --------------------------- cosine = F.linear(F.normalize(features), F.normalize(self.weight)) phi = cosine - self.m # --------------------------- convert label to one-hot --------------------------- targets = F.one_hot(targets, num_classes=self._num_classes) output = (targets * phi) + ((1.0 - targets) * cosine) output *= self.s return output def extra_repr(self):
return 'in_features={}, num_classes={}, scale={}, margin={}'.format( self.in_feat, self._num_classes, self.s, self.m )
main.rs
use std::iter; use cgmath::prelude::*; use wgpu::util::DeviceExt; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::Window, }; mod model; mod texture; use model::{DrawLight, DrawModel, Vertex}; #[rustfmt::skip] pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = cgmath::Matrix4::new( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 1.0, ); const NUM_INSTANCES_PER_ROW: u32 = 10; struct Camera { eye: cgmath::Point3<f32>, target: cgmath::Point3<f32>, up: cgmath::Vector3<f32>, aspect: f32, fovy: f32, znear: f32, zfar: f32, } impl Camera { fn build_view_projection_matrix(&self) -> cgmath::Matrix4<f32> { let view = cgmath::Matrix4::look_at_rh(self.eye, self.target, self.up); let proj = cgmath::perspective(cgmath::Deg(self.fovy), self.aspect, self.znear, self.zfar); proj * view } } #[repr(C)] #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct Uniforms { view_position: [f32; 4], view_proj: [[f32; 4]; 4], } impl Uniforms { fn new() -> Self { Self { view_position: [0.0; 4], view_proj: cgmath::Matrix4::identity().into(), } } fn update_view_proj(&mut self, camera: &Camera) { self.view_position = camera.eye.to_homogeneous().into(); self.view_proj = (OPENGL_TO_WGPU_MATRIX * camera.build_view_projection_matrix()).into(); } } struct CameraController { speed: f32, is_up_pressed: bool, is_down_pressed: bool, is_forward_pressed: bool, is_backward_pressed: bool, is_left_pressed: bool, is_right_pressed: bool, } impl CameraController { fn new(speed: f32) -> Self { Self { speed, is_up_pressed: false, is_down_pressed: false, is_forward_pressed: false, is_backward_pressed: false, is_left_pressed: false, is_right_pressed: false, } } fn process_events(&mut self, event: &WindowEvent) -> bool { match event { WindowEvent::KeyboardInput { input: KeyboardInput { state, virtual_keycode: Some(keycode), .. }, .. } => { let is_pressed = *state == ElementState::Pressed; match keycode { VirtualKeyCode::Space => { self.is_up_pressed = is_pressed; true } VirtualKeyCode::LShift => { self.is_down_pressed = is_pressed; true } VirtualKeyCode::W | VirtualKeyCode::Up => { self.is_forward_pressed = is_pressed; true } VirtualKeyCode::A | VirtualKeyCode::Left => { self.is_left_pressed = is_pressed; true } VirtualKeyCode::S | VirtualKeyCode::Down => { self.is_backward_pressed = is_pressed; true } VirtualKeyCode::D | VirtualKeyCode::Right => { self.is_right_pressed = is_pressed; true } _ => false, } } _ => false, } } fn update_camera(&self, camera: &mut Camera) { let forward = camera.target - camera.eye; let forward_norm = forward.normalize(); let forward_mag = forward.magnitude(); // Prevents glitching when camera gets too close to the // center of the scene. if self.is_forward_pressed && forward_mag > self.speed { camera.eye += forward_norm * self.speed; } if self.is_backward_pressed { camera.eye -= forward_norm * self.speed; } let right = forward_norm.cross(camera.up); // Redo radius calc in case the up/ down is pressed. let forward = camera.target - camera.eye; let forward_mag = forward.magnitude(); if self.is_right_pressed { // Rescale the distance between the target and eye so // that it doesn't change. The eye therefore still // lies on the circle made by the target and eye. camera.eye = camera.target - (forward + right * self.speed).normalize() * forward_mag; } if self.is_left_pressed { camera.eye = camera.target - (forward - right * self.speed).normalize() * forward_mag; } } } struct Instance { position: cgmath::Vector3<f32>, rotation: cgmath::Quaternion<f32>, } impl Instance { fn to_raw(&self) -> InstanceRaw { InstanceRaw { model: (cgmath::Matrix4::from_translation(self.position) * cgmath::Matrix4::from(self.rotation)) .into(), normal: cgmath::Matrix3::from(self.rotation).into(), } } } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] #[allow(dead_code)] struct InstanceRaw { model: [[f32; 4]; 4], normal: [[f32; 3]; 3], } impl model::Vertex for InstanceRaw { fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { use std::mem; wgpu::VertexBufferLayout { array_stride: mem::size_of::<InstanceRaw>() as wgpu::BufferAddress, // We need to switch from using a step mode of Vertex to Instance // This means that our shaders will only change to use the next // instance when the shader starts processing a new instance step_mode: wgpu::InputStepMode::Instance, attributes: &[ wgpu::VertexAttribute { offset: 0, // While our vertex shader only uses locations 0, and 1 now, in later tutorials we'll // be using 2, 3, and 4, for Vertex. We'll start at slot 5 not conflict with them later shader_location: 5, format: wgpu::VertexFormat::Float32x4, }, // A mat4 takes up 4 vertex slots as it is technically 4 vec4s. We need to define a slot // for each vec4. We don't have to do this in code though. wgpu::VertexAttribute { offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress, shader_location: 6, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress, shader_location: 7, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress, shader_location: 8, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 16]>() as wgpu::BufferAddress, shader_location: 9, format: wgpu::VertexFormat::Float32x3, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 19]>() as wgpu::BufferAddress, shader_location: 10, format: wgpu::VertexFormat::Float32x3, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 22]>() as wgpu::BufferAddress, shader_location: 11, format: wgpu::VertexFormat::Float32x3, }, ], } } } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct Light { position: [f32; 3], // Due to uniforms requiring 16 byte (4 float) spacing, we need to use a padding field here _padding: u32, color: [f32; 3], } struct State { surface: wgpu::Surface, device: wgpu::Device, queue: wgpu::Queue, sc_desc: wgpu::SwapChainDescriptor, swap_chain: wgpu::SwapChain, render_pipeline: wgpu::RenderPipeline, obj_model: model::Model, camera: Camera, camera_controller: CameraController, uniforms: Uniforms, uniform_buffer: wgpu::Buffer, uniform_bind_group: wgpu::BindGroup, instances: Vec<Instance>, #[allow(dead_code)] instance_buffer: wgpu::Buffer, depth_texture: texture::Texture, size: winit::dpi::PhysicalSize<u32>, light: Light, light_buffer: wgpu::Buffer, light_bind_group: wgpu::BindGroup, light_render_pipeline: wgpu::RenderPipeline, #[allow(dead_code)] debug_material: model::Material, } fn create_render_pipeline( device: &wgpu::Device, layout: &wgpu::PipelineLayout, color_format: wgpu::TextureFormat, depth_format: Option<wgpu::TextureFormat>, vertex_layouts: &[wgpu::VertexBufferLayout], shader: wgpu::ShaderModuleDescriptor, ) -> wgpu::RenderPipeline { let shader = device.create_shader_module(&shader); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Render Pipeline"), layout: Some(layout), vertex: wgpu::VertexState { module: &shader, entry_point: "main", buffers: vertex_layouts, }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: "main", targets: &[wgpu::ColorTargetState { format: color_format, blend: Some(wgpu::BlendState { alpha: wgpu::BlendComponent::REPLACE, color: wgpu::BlendComponent::REPLACE, }), write_mask: wgpu::ColorWrite::ALL, }], }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, strip_index_format: None, front_face: wgpu::FrontFace::Ccw, cull_mode: Some(wgpu::Face::Back), // Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE polygon_mode: wgpu::PolygonMode::Fill, // Requires Features::DEPTH_CLAMPING clamp_depth: false, // Requires Features::CONSERVATIVE_RASTERIZATION conservative: false, }, depth_stencil: depth_format.map(|format| wgpu::DepthStencilState { format, depth_write_enabled: true, depth_compare: wgpu::CompareFunction::Less, stencil: wgpu::StencilState::default(), bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, }) } impl State { async fn new(window: &Window) -> Self { let size = window.inner_size(); // The instance is a handle to our GPU // BackendBit::PRIMARY => Vulkan + Metal + DX12 + Browser WebGPU let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); let surface = unsafe { instance.create_surface(window) }; let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface: Some(&surface), }) .await .unwrap(); let (device, queue) = adapter .request_device( &wgpu::DeviceDescriptor { label: None, features: wgpu::Features::empty(), limits: wgpu::Limits::default(), }, None, // Trace path ) .await .unwrap(); let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::RENDER_ATTACHMENT, format: adapter.get_swap_chain_preferred_format(&surface).unwrap(), width: size.width, height: size.height, present_mode: wgpu::PresentMode::Fifo, }; let swap_chain = device.create_swap_chain(&surface, &sc_desc); let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler { comparison: false, filtering: true, }, count: None, }, // normal map wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 3, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler { comparison: false, filtering: true, }, count: None, }, ], label: Some("texture_bind_group_layout"), }); let camera = Camera { eye: (0.0, 5.0, -10.0).into(), target: (0.0, 0.0, 0.0).into(), up: cgmath::Vector3::unit_y(), aspect: sc_desc.width as f32 / sc_desc.height as f32, fovy: 45.0, znear: 0.1, zfar: 100.0, }; let camera_controller = CameraController::new(0.2); let mut uniforms = Uniforms::new(); uniforms.update_view_proj(&camera); let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Uniform Buffer"), contents: bytemuck::cast_slice(&[uniforms]), usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, }); const SPACE_BETWEEN: f32 = 3.0; let instances = (0..NUM_INSTANCES_PER_ROW) .flat_map(|z| { (0..NUM_INSTANCES_PER_ROW).map(move |x| { let x = SPACE_BETWEEN * (x as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0); let z = SPACE_BETWEEN * (z as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0); let position = cgmath::Vector3 { x, y: 0.0, z }; let rotation = if position.is_zero() { cgmath::Quaternion::from_axis_angle( cgmath::Vector3::unit_z(), cgmath::Deg(0.0), ) } else { cgmath::Quaternion::from_axis_angle(position.normalize(), cgmath::Deg(45.0)) }; Instance { position, rotation } }) }) .collect::<Vec<_>>(); let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>(); let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Instance Buffer"), contents: bytemuck::cast_slice(&instance_data), usage: wgpu::BufferUsage::VERTEX, }); let uniform_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }], label: Some("uniform_bind_group_layout"), }); let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &uniform_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding(), }], label: Some("uniform_bind_group"), }); let res_dir = std::path::Path::new(env!("OUT_DIR")).join("res"); let obj_model = model::Model::load( &device, &queue, &texture_bind_group_layout, res_dir.join("cube.obj"), ) .unwrap(); let light = Light { position: [2.0, 2.0, 2.0], _padding: 0, color: [1.0, 1.0, 1.0], }; let light_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Light VB"), contents: bytemuck::cast_slice(&[light]), usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, }); let light_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }], label: None, }); let light_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &light_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: light_buffer.as_entire_binding(), }], label: None, }); let depth_texture = texture::Texture::create_depth_texture(&device, &sc_desc, "depth_texture"); let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Render Pipeline Layout"), bind_group_layouts: &[ &texture_bind_group_layout, &uniform_bind_group_layout, &light_bind_group_layout, ], push_constant_ranges: &[], }); let render_pipeline = { let shader = wgpu::ShaderModuleDescriptor { label: Some("Normal Shader"), flags: wgpu::ShaderFlags::all(), source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()), }; create_render_pipeline( &device, &render_pipeline_layout, sc_desc.format, Some(texture::Texture::DEPTH_FORMAT), &[model::ModelVertex::desc(), InstanceRaw::desc()], shader, ) }; let light_render_pipeline = { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Light Pipeline Layout"), bind_group_layouts: &[&uniform_bind_group_layout, &light_bind_group_layout], push_constant_ranges: &[], }); let shader = wgpu::ShaderModuleDescriptor { label: Some("Light Shader"), flags: wgpu::ShaderFlags::all(), source: wgpu::ShaderSource::Wgsl(include_str!("light.wgsl").into()), }; create_render_pipeline( &device, &layout, sc_desc.format, Some(texture::Texture::DEPTH_FORMAT), &[model::ModelVertex::desc()], shader, ) }; let debug_material = { let diffuse_bytes = include_bytes!("../res/cobble-diffuse.png"); let normal_bytes = include_bytes!("../res/cobble-normal.png"); let diffuse_texture = texture::Texture::from_bytes( &device, &queue, diffuse_bytes, "res/alt-diffuse.png", false, ) .unwrap(); let normal_texture = texture::Texture::from_bytes( &device, &queue, normal_bytes, "res/alt-normal.png", true, ) .unwrap(); model::Material::new( &device, "alt-material", diffuse_texture, normal_texture, &texture_bind_group_layout, ) }; Self { surface, device, queue, sc_desc, swap_chain, render_pipeline, obj_model, camera, camera_controller, uniform_buffer, uniform_bind_group, uniforms, instances, instance_buffer, depth_texture, size, light, light_buffer, light_bind_group, light_render_pipeline, #[allow(dead_code)] debug_material, } } fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { if new_size.width > 0 && new_size.height > 0 { self.camera.aspect = self.sc_desc.width as f32 / self.sc_desc.height as f32; self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); self.depth_texture = texture::Texture::create_depth_texture(&self.device, &self.sc_desc, "depth_texture"); } } fn
(&mut self, event: &WindowEvent) -> bool { self.camera_controller.process_events(event) } fn update(&mut self) { self.camera_controller.update_camera(&mut self.camera); self.uniforms.update_view_proj(&self.camera); self.queue.write_buffer( &self.uniform_buffer, 0, bytemuck::cast_slice(&[self.uniforms]), ); // Update the light let old_position: cgmath::Vector3<_> = self.light.position.into(); self.light.position = (cgmath::Quaternion::from_axis_angle((0.0, 1.0, 0.0).into(), cgmath::Deg(1.0)) * old_position) .into(); self.queue .write_buffer(&self.light_buffer, 0, bytemuck::cast_slice(&[self.light])); } fn render(&mut self) -> Result<(), wgpu::SwapChainError> { let frame = self.swap_chain.get_current_frame()?.output; let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Render Encoder"), }); { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[wgpu::RenderPassColorAttachment { view: &frame.view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0, }), store: true, }, }], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: &self.depth_texture.view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: true, }), stencil_ops: None, }), }); render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..)); render_pass.set_pipeline(&self.light_render_pipeline); render_pass.draw_light_model( &self.obj_model, &self.uniform_bind_group, &self.light_bind_group, ); render_pass.set_pipeline(&self.render_pipeline); render_pass.draw_model_instanced( &self.obj_model, 0..self.instances.len() as u32, &self.uniform_bind_group, &self.light_bind_group, ); } self.queue.submit(iter::once(encoder.finish())); Ok(()) } } fn main() { env_logger::init(); let event_loop = EventLoop::new(); let title = env!("CARGO_PKG_NAME"); let window = winit::window::WindowBuilder::new() .with_title(title) .build(&event_loop) .unwrap(); let mut state = pollster::block_on(State::new(&window)); event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Poll; match event { Event::MainEventsCleared => window.request_redraw(), Event::WindowEvent { ref event, window_id, } if window_id == window.id() => { if !state.input(event) { match event { WindowEvent::CloseRequested | WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => *control_flow = ControlFlow::Exit, WindowEvent::Resized(physical_size) => { state.resize(*physical_size); } WindowEvent::ScaleFactorChanged { new_inner_size, .. } => { state.resize(**new_inner_size); } _ => {} } } } Event::RedrawRequested(_) => { state.update(); match state.render() { Ok(_) => {} // Recreate the swap_chain if lost Err(wgpu::SwapChainError::Lost) => state.resize(state.size), // The system is out of memory, we should probably quit Err(wgpu::SwapChainError::OutOfMemory) => *control_flow = ControlFlow::Exit, // All other errors (Outdated, Timeout) should be resolved by the next frame Err(e) => eprintln!("{:?}", e), } } _ => {} } }); }
input
postgresql_test.go
package repository_test import ( "database/sql" "github.com/stone1549/auth-service/repository" "gopkg.in/DATA-DOG/go-sqlmock.v2" "testing" "time" ) func mockExpectExecTimes(mock sqlmock.Sqlmock, sqlRegexStr string, times int) { for i := 0; i < times; i++ { mock.ExpectExec(sqlRegexStr).WillReturnResult(sqlmock.NewResult(int64(i), 1)) } } func makeAndTestPgSmallRepo() (*sql.DB, sqlmock.Sqlmock, repository.UserRepository, error) { var err error db, mock, err := sqlmock.New() if err != nil { return nil, nil, nil, err } mock.ExpectBegin() mockExpectExecTimes(mock, "INSERT INTO login", 5) mock.ExpectCommit() repo, err := repository.MakePostgresqlUserRespository(pgSmall, db) return db, mock, repo, err } // TestMakePostgresqlUserRespository_Ds ensures that a dataset can be loaded when a pg repo is constructed. func TestMakePostgresqlUserRespository_Ds(t *testing.T) { db, mock, _, err := makeAndTestPgSmallRepo() defer db.Close() ok(t, err) ok(t, mock.ExpectationsWereMet()) } // TestMakePostgresqlUserRespository ensures that an empty pg repo can be constructed. func TestMakePostgresqlUserRespository(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { t.Fatalf("an error '%s' was not expected when opening a stub database connection", err) } defer db.Close() _, err = repository.MakePostgresqlUserRespository(pgEmpty, db) ok(t, err) ok(t, mock.ExpectationsWereMet()) } func
() []string { columns := make([]string, 0) columns = append(columns, "id") columns = append(columns, "email") columns = append(columns, "salted_hash") columns = append(columns, "created_at") columns = append(columns, "updated_at") return columns } func addExpectedUserId1Row(rows *sqlmock.Rows) *sqlmock.Rows { createdAt, _ := time.Parse("2006-01-15T15:20:59", "2017-01-01T00:00:00Z") updatedAt, _ := time.Parse("2006-01-15T15:20:59", "2018-01-01T00:00:20Z") return rows.AddRow( "1", "[email protected]", "$2a$10$EAd78WN5SS0uUP7AlEIs..fKXBs8Zj.bZrdXNVQEn.fx72MJGwXmy", createdAt, updatedAt, ) } func addExpectedUserId2Row(rows *sqlmock.Rows) *sqlmock.Rows { createdAt, _ := time.Parse("2006-01-15T15:20:59", "2017-01-01T00:00:01Z") updatedAt, _ := time.Parse("2006-01-15T15:20:59", "2018-01-01T00:00:19Z") return rows.AddRow( "2", "[email protected]", "$2a$10$EMnu7T8Nhs2o3yVv.U73mO0HY5MdjYyHFpHU8kjLUWLYOGvJJ1RrG", createdAt, updatedAt, ) } func addExpectedUserId3Row(rows *sqlmock.Rows) *sqlmock.Rows { createdAt, _ := time.Parse("2006-01-15T15:20:59", "2017-01-01T00:00:02Z") updatedAt, _ := time.Parse("2006-01-15T15:20:59", "2018-01-01T00:00:18Z") return rows.AddRow( "3", "[email protected]", "$2a$10$XdLPi4OEE1HhSgdtZekQAu.0P0W.sPn4KcojbRZr2hOfkBDFSQI0a", createdAt, updatedAt, ) } func addExpectedUserId4Row(rows *sqlmock.Rows) *sqlmock.Rows { createdAt, _ := time.Parse("2006-01-15T15:20:59", "2017-01-01T00:00:03Z") updatedAt, _ := time.Parse("2006-01-15T15:20:59", "2018-01-01T00:00:17Z") return rows.AddRow( "4", "[email protected]", "$2a$10$wjp0yIJYZ0FP/DhHbQ3kwugsPEklf15zw/oWx.0sTyjoSDIsXaF7a", createdAt, updatedAt, ) } func addExpectedUserId5Row(rows *sqlmock.Rows) *sqlmock.Rows { createdAt, _ := time.Parse("2006-01-15T15:20:59", "2017-01-01T00:00:04Z") updatedAt, _ := time.Parse("2006-01-15T15:20:59", "2018-01-01T00:00:16Z") return rows.AddRow( "5", "[email protected]", "$2a$10$rg4W8bMMqjvh4Q9AbA89qOvdh40P8tfsIhI9Dvv.IPGKcFxlwxn6C", createdAt, updatedAt, ) }
getProductColumns
pretty.rs
//! The various pretty-printing routines. use rustc_ast as ast; use rustc_ast_pretty::pprust; use rustc_errors::ErrorReported; use rustc_hir as hir; use rustc_hir::def_id::LOCAL_CRATE; use rustc_hir_pretty as pprust_hir; use rustc_middle::hir::map as hir_map; use rustc_middle::ty::{self, TyCtxt}; use rustc_mir::util::{write_mir_graphviz, write_mir_pretty}; use rustc_session::config::{Input, PpMode, PpSourceMode}; use rustc_session::Session; use rustc_span::symbol::Ident; use rustc_span::FileName; use std::cell::Cell; use std::fs::File; use std::io::Write; use std::path::Path; pub use self::PpMode::*; pub use self::PpSourceMode::*; use crate::abort_on_err; // This slightly awkward construction is to allow for each PpMode to // choose whether it needs to do analyses (which can consume the // Session) and then pass through the session (now attached to the // analysis results) on to the chosen pretty-printer, along with the // `&PpAnn` object. // // Note that since the `&PrinterSupport` is freshly constructed on each // call, it would not make sense to try to attach the lifetime of `self` // to the lifetime of the `&PrinterObject`. /// Constructs a `PrinterSupport` object and passes it to `f`. fn call_with_pp_support<'tcx, A, F>( ppmode: &PpSourceMode, sess: &'tcx Session, tcx: Option<TyCtxt<'tcx>>, f: F, ) -> A where F: FnOnce(&dyn PrinterSupport) -> A, { match *ppmode { PpmNormal | PpmEveryBodyLoops | PpmExpanded => { let annotation = NoAnn { sess, tcx }; f(&annotation)
let annotation = IdentifiedAnnotation { sess, tcx }; f(&annotation) } PpmExpandedHygiene => { let annotation = HygieneAnnotation { sess }; f(&annotation) } _ => panic!("Should use call_with_pp_support_hir"), } } fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A where F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A, { match *ppmode { PpmNormal => { let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) }; f(&annotation, tcx.hir().krate()) } PpmIdentified => { let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) }; f(&annotation, tcx.hir().krate()) } PpmTyped => { abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess); let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) }; tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir().krate())) } _ => panic!("Should use call_with_pp_support"), } } trait PrinterSupport: pprust::PpAnn { /// Provides a uniform interface for re-extracting a reference to a /// `Session` from a value that now owns it. fn sess(&self) -> &Session; /// Produces the pretty-print annotation object. /// /// (Rust does not yet support upcasting from a trait object to /// an object for one of its super-traits.) fn pp_ann(&self) -> &dyn pprust::PpAnn; } trait HirPrinterSupport<'hir>: pprust_hir::PpAnn { /// Provides a uniform interface for re-extracting a reference to a /// `Session` from a value that now owns it. fn sess(&self) -> &Session; /// Provides a uniform interface for re-extracting a reference to an /// `hir_map::Map` from a value that now owns it. fn hir_map(&self) -> Option<hir_map::Map<'hir>>; /// Produces the pretty-print annotation object. /// /// (Rust does not yet support upcasting from a trait object to /// an object for one of its super-traits.) fn pp_ann(&self) -> &dyn pprust_hir::PpAnn; /// Computes an user-readable representation of a path, if possible. fn node_path(&self, id: hir::HirId) -> Option<String> { self.hir_map().and_then(|map| map.def_path_from_hir_id(id)).map(|path| { path.data.into_iter().map(|elem| elem.data.to_string()).collect::<Vec<_>>().join("::") }) } } struct NoAnn<'hir> { sess: &'hir Session, tcx: Option<TyCtxt<'hir>>, } impl<'hir> PrinterSupport for NoAnn<'hir> { fn sess(&self) -> &Session { self.sess } fn pp_ann(&self) -> &dyn pprust::PpAnn { self } } impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> { fn sess(&self) -> &Session { self.sess } fn hir_map(&self) -> Option<hir_map::Map<'hir>> { self.tcx.map(|tcx| tcx.hir()) } fn pp_ann(&self) -> &dyn pprust_hir::PpAnn { self } } impl<'hir> pprust::PpAnn for NoAnn<'hir> {} impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> { fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) { if let Some(tcx) = self.tcx { pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested) } } } struct IdentifiedAnnotation<'hir> { sess: &'hir Session, tcx: Option<TyCtxt<'hir>>, } impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> { fn sess(&self) -> &Session { self.sess } fn pp_ann(&self) -> &dyn pprust::PpAnn { self } } impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> { fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) { if let pprust::AnnNode::Expr(_) = node { s.popen(); } } fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) { match node { pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {} pprust::AnnNode::Item(item) => { s.s.space(); s.synth_comment(item.id.to_string()) } pprust::AnnNode::SubItem(id) => { s.s.space(); s.synth_comment(id.to_string()) } pprust::AnnNode::Block(blk) => { s.s.space(); s.synth_comment(format!("block {}", blk.id)) } pprust::AnnNode::Expr(expr) => { s.s.space(); s.synth_comment(expr.id.to_string()); s.pclose() } pprust::AnnNode::Pat(pat) => { s.s.space(); s.synth_comment(format!("pat {}", pat.id)); } } } } impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> { fn sess(&self) -> &Session { self.sess } fn hir_map(&self) -> Option<hir_map::Map<'hir>> { self.tcx.map(|tcx| tcx.hir()) } fn pp_ann(&self) -> &dyn pprust_hir::PpAnn { self } } impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> { fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) { if let Some(ref tcx) = self.tcx { pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested) } } fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { if let pprust_hir::AnnNode::Expr(_) = node { s.popen(); } } fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { match node { pprust_hir::AnnNode::Name(_) => {} pprust_hir::AnnNode::Item(item) => { s.s.space(); s.synth_comment(format!("hir_id: {}", item.hir_id)); } pprust_hir::AnnNode::SubItem(id) => { s.s.space(); s.synth_comment(id.to_string()); } pprust_hir::AnnNode::Block(blk) => { s.s.space(); s.synth_comment(format!("block hir_id: {}", blk.hir_id)); } pprust_hir::AnnNode::Expr(expr) => { s.s.space(); s.synth_comment(format!("expr hir_id: {}", expr.hir_id)); s.pclose(); } pprust_hir::AnnNode::Pat(pat) => { s.s.space(); s.synth_comment(format!("pat hir_id: {}", pat.hir_id)); } pprust_hir::AnnNode::Arm(arm) => { s.s.space(); s.synth_comment(format!("arm hir_id: {}", arm.hir_id)); } } } } struct HygieneAnnotation<'a> { sess: &'a Session, } impl<'a> PrinterSupport for HygieneAnnotation<'a> { fn sess(&self) -> &Session { self.sess } fn pp_ann(&self) -> &dyn pprust::PpAnn { self } } impl<'a> pprust::PpAnn for HygieneAnnotation<'a> { fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) { match node { pprust::AnnNode::Ident(&Ident { name, span }) => { s.s.space(); s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt())) } pprust::AnnNode::Name(&name) => { s.s.space(); s.synth_comment(name.as_u32().to_string()) } pprust::AnnNode::Crate(_) => { s.s.hardbreak(); let verbose = self.sess.verbose(); s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose)); s.s.hardbreak_if_not_bol(); } _ => {} } } } struct TypedAnnotation<'tcx> { tcx: TyCtxt<'tcx>, maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>, } impl<'tcx> TypedAnnotation<'tcx> { /// Gets the type-checking results for the current body. /// As this will ICE if called outside bodies, only call when working with /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies). #[track_caller] fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> { self.maybe_typeck_results .get() .expect("`TypedAnnotation::typeck_results` called outside of body") } } impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> { fn sess(&self) -> &Session { &self.tcx.sess } fn hir_map(&self) -> Option<hir_map::Map<'tcx>> { Some(self.tcx.hir()) } fn pp_ann(&self) -> &dyn pprust_hir::PpAnn { self } fn node_path(&self, id: hir::HirId) -> Option<String> { Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id).to_def_id())) } } impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> { fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) { let old_maybe_typeck_results = self.maybe_typeck_results.get(); if let pprust_hir::Nested::Body(id) = nested { self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id))); } let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>); pprust_hir::PpAnn::nested(pp_ann, state, nested); self.maybe_typeck_results.set(old_maybe_typeck_results); } fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { if let pprust_hir::AnnNode::Expr(_) = node { s.popen(); } } fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { if let pprust_hir::AnnNode::Expr(expr) = node { s.s.space(); s.s.word("as"); s.s.space(); s.s.word(self.typeck_results().expr_ty(expr).to_string()); s.pclose(); } } } fn get_source(input: &Input, sess: &Session) -> (String, FileName) { let src_name = input.source_name(); let src = String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap()); (src, src_name) } fn write_output(out: Vec<u8>, ofile: Option<&Path>) { match ofile { None => print!("{}", String::from_utf8(out).unwrap()), Some(p) => match File::create(p) { Ok(mut w) => w.write_all(&out).unwrap(), Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e), }, } } pub fn print_after_parsing( sess: &Session, input: &Input, krate: &ast::Crate, ppm: PpMode, ofile: Option<&Path>, ) { let (src, src_name) = get_source(input, sess); let mut out = String::new(); if let PpmSource(s) = ppm { // Silently ignores an identified node. let out = &mut out; call_with_pp_support(&s, sess, None, move |annotation| { debug!("pretty printing source code {:?}", s); let sess = annotation.sess(); let parse = &sess.parse_sess; *out = pprust::print_crate( sess.source_map(), krate, src_name, src, annotation.pp_ann(), false, parse.edition, parse.injected_crate_name.get().is_some(), ) }) } else { unreachable!(); }; write_output(out.into_bytes(), ofile); } pub fn print_after_hir_lowering<'tcx>( tcx: TyCtxt<'tcx>, input: &Input, krate: &ast::Crate, ppm: PpMode, ofile: Option<&Path>, ) { if ppm.needs_analysis() { abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess); return; } let (src, src_name) = get_source(input, tcx.sess); let mut out = String::new(); match ppm { PpmSource(s) => { // Silently ignores an identified node. let out = &mut out; call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| { debug!("pretty printing source code {:?}", s); let sess = annotation.sess(); let parse = &sess.parse_sess; *out = pprust::print_crate( sess.source_map(), krate, src_name, src, annotation.pp_ann(), true, parse.edition, parse.injected_crate_name.get().is_some(), ) }) } PpmHir(s) => { let out = &mut out; call_with_pp_support_hir(&s, tcx, move |annotation, krate| { debug!("pretty printing source code {:?}", s); let sess = annotation.sess(); let sm = sess.source_map(); *out = pprust_hir::print_crate(sm, krate, src_name, src, annotation.pp_ann()) }) } PpmHirTree(s) => { let out = &mut out; call_with_pp_support_hir(&s, tcx, move |_annotation, krate| { debug!("pretty printing source code {:?}", s); *out = format!("{:#?}", krate); }); } _ => unreachable!(), } write_output(out.into_bytes(), ofile); } // In an ideal world, this would be a public function called by the driver after // analysis is performed. However, we want to call `phase_3_run_analysis_passes` // with a different callback than the standard driver, so that isn't easy. // Instead, we call that function ourselves. fn print_with_analysis( tcx: TyCtxt<'_>, ppm: PpMode, ofile: Option<&Path>, ) -> Result<(), ErrorReported> { let mut out = Vec::new(); tcx.analysis(LOCAL_CRATE)?; match ppm { PpmMir | PpmMirCFG => match ppm { PpmMir => write_mir_pretty(tcx, None, &mut out), PpmMirCFG => write_mir_graphviz(tcx, None, &mut out), _ => unreachable!(), }, _ => unreachable!(), } .unwrap(); write_output(out, ofile); Ok(()) }
} PpmIdentified | PpmExpandedIdentified => {
FocusOnValue.d.ts
import { QualifierValue } from "../../../../internal/qualifier/QualifierValue.js"; /** * @memberOf Qualifiers.FocusOn * @extends {SDK.QualifierValue} */ declare class
extends QualifierValue { readonly name: string; constructor(name?: string); toString(): string; } export { FocusOnValue };
FocusOnValue
test_keychain.py
import json import unittest from secrets import token_bytes from blspy import AugSchemeMPL, PrivateKey from thyme.util.keychain import Keychain, bytes_from_mnemonic, bytes_to_mnemonic, generate_mnemonic, mnemonic_to_seed class TesKeychain(unittest.TestCase): def test_basic_add_delete(self): kc: Keychain = Keychain(testing=True) kc.delete_all_keys() assert kc._get_free_private_key_index() == 0 assert len(kc.get_all_private_keys()) == 0 assert kc.get_first_private_key() is None assert kc.get_first_public_key() is None mnemonic = generate_mnemonic() entropy = bytes_from_mnemonic(mnemonic) assert bytes_to_mnemonic(entropy) == mnemonic mnemonic_2 = generate_mnemonic() kc.add_private_key(mnemonic, "") assert kc._get_free_private_key_index() == 1 assert len(kc.get_all_private_keys()) == 1 kc.add_private_key(mnemonic_2, "") kc.add_private_key(mnemonic_2, "") # checks to not add duplicates assert kc._get_free_private_key_index() == 2 assert len(kc.get_all_private_keys()) == 2 assert kc._get_free_private_key_index() == 2 assert len(kc.get_all_private_keys()) == 2 assert len(kc.get_all_public_keys()) == 2 assert kc.get_all_private_keys()[0] == kc.get_first_private_key() assert kc.get_all_public_keys()[0] == kc.get_first_public_key() assert len(kc.get_all_private_keys()) == 2 seed_2 = mnemonic_to_seed(mnemonic, "") seed_key_2 = AugSchemeMPL.key_gen(seed_2) kc.delete_key_by_fingerprint(seed_key_2.get_g1().get_fingerprint()) assert kc._get_free_private_key_index() == 0 assert len(kc.get_all_private_keys()) == 1 kc.delete_all_keys() assert kc._get_free_private_key_index() == 0 assert len(kc.get_all_private_keys()) == 0 kc.add_private_key(bytes_to_mnemonic(token_bytes(32)), "my passphrase") kc.add_private_key(bytes_to_mnemonic(token_bytes(32)), "") kc.add_private_key(bytes_to_mnemonic(token_bytes(32)), "third passphrase") assert len(kc.get_all_public_keys()) == 3 assert len(kc.get_all_private_keys()) == 1 assert len(kc.get_all_private_keys(["my passphrase", ""])) == 2 assert len(kc.get_all_private_keys(["my passphrase", "", "third passphrase", "another"])) == 3 assert len(kc.get_all_private_keys(["my passhrase wrong"])) == 0 assert kc.get_first_private_key() is not None assert kc.get_first_private_key(["bad passphrase"]) is None assert kc.get_first_public_key() is not None kc.delete_all_keys() kc.add_private_key(bytes_to_mnemonic(token_bytes(32)), "my passphrase") assert kc.get_first_public_key() is not None def test_bip39_eip2333_test_vector(self): kc: Keychain = Keychain(testing=True) kc.delete_all_keys() mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" passphrase = "TREZOR" print("entropy to seed:", mnemonic_to_seed(mnemonic, passphrase).hex()) master_sk = kc.add_private_key(mnemonic, passphrase) tv_master_int = 5399117110774477986698372024995405256382522670366369834617409486544348441851 tv_child_int = 11812940737387919040225825939013910852517748782307378293770044673328955938106 assert master_sk == PrivateKey.from_bytes(tv_master_int.to_bytes(32, "big")) child_sk = AugSchemeMPL.derive_child_sk(master_sk, 0) assert child_sk == PrivateKey.from_bytes(tv_child_int.to_bytes(32, "big")) def test_bip39_test_vectors_trezor(self): with open("tests/util/bip39_test_vectors.json") as f: all_vectors = json.loads(f.read()) for vector_list in all_vectors["english"]: entropy_bytes = bytes.fromhex(vector_list[0]) mnemonic = vector_list[1] seed = bytes.fromhex(vector_list[2]) assert bytes_from_mnemonic(mnemonic) == entropy_bytes assert bytes_to_mnemonic(entropy_bytes) == mnemonic assert mnemonic_to_seed(mnemonic, "TREZOR") == seed def test_utf8_nfkd(self): # Test code from trezor: # Copyright (c) 2013 Pavol Rusnak # Copyright (c) 2017 mruddy # https://github.com/trezor/python-mnemonic/blob/master/test_mnemonic.py # The same sentence in various UTF-8 forms words_nfkd = "Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a" # noqa: E501 words_nfc = "P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f" # noqa: E501 words_nfkc = "P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f" # noqa: E501 words_nfd = "Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a" # noqa: E501 passphrase_nfkd = "Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko" passphrase_nfc = "Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko" passphrase_nfkc = "Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko" passphrase_nfd = "Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko" seed_nfkd = mnemonic_to_seed(words_nfkd, passphrase_nfkd) seed_nfc = mnemonic_to_seed(words_nfc, passphrase_nfc)
assert seed_nfkd == seed_nfc assert seed_nfkd == seed_nfkc assert seed_nfkd == seed_nfd
seed_nfkc = mnemonic_to_seed(words_nfkc, passphrase_nfkc) seed_nfd = mnemonic_to_seed(words_nfd, passphrase_nfd)
compare.py
# UCF Senior Design 2017-18 # Group 38 from PIL import Image import cv2 import imagehash import math import numpy as np DIFF_THRES = 20 LIMIT = 2 RESIZE = 1000 def calc_hash(img): """ Calculate the wavelet hash of the image img: (ndarray) image file """ # resize image if height > 1000 img = resize(img) return imagehash.whash(Image.fromarray(img)) def compare(hash1, hash2): """ Calculate the difference between two images hash1: (array) first wavelet hash hash2: (array) second wavelet hash """ return hash1 - hash2 def limit(img, std_hash, count): """ Determine whether image should be removed from image dictionary in main.py img: (ndarray) image file std_hash: (array) wavelet hash of comparison standard count: (int) global count of images similar to comparison standard """ # calculate hash for given image cmp_hash = calc_hash(img) # compare to standard diff = compare(std_hash, cmp_hash) # image is similar to standard if diff <= DIFF_THRES: # if there are 3 similar images already, remove image if count >= LIMIT: return 'remove' # non-similar image found else: # update comparison standard
# else continue reading images with same standard return 'continue' def resize(img): """ Resize an image img: (ndarray) RGB color image """ # get dimensions of image width = np.shape(img)[1] height = np.shape(img)[0] # if height of image is greater than 1000, resize it to 1000 if width > RESIZE: # keep resize proportional scale = RESIZE / width resized_img = cv2.resize( img, (RESIZE, math.floor(height / scale)), cv2.INTER_AREA) # return resized image return resized_img # if height of image is less than 1000, return image unresized return img def set_standard(images, filename): """ Set new comparison standard and update information images: (dictionary) dictionary containing all the image data filename: (String) name of the image file """ return filename, calc_hash(images[filename]), 0
return 'update_std'
val_stream.rs
use crate::iterable::Iterable; use crate::misc::MatrixElement; use ark_ff::Field; use ark_std::borrow::Borrow; use ark_std::marker::PhantomData; #[derive(Clone, Copy)] pub struct SparseMatrixStream<'a, F, S> where S: Iterable, F: Field, S::Item: Borrow<MatrixElement<F>>, { matrix: &'a S, _field: PhantomData<F>, len: usize, } pub struct SparseMatrixIter<I, F> where I: Iterator, F: Field, I::Item: Borrow<MatrixElement<F>>, { it: I, row: usize, _field: PhantomData<F>, } impl<'a, F, S> SparseMatrixStream<'a, F, S> where S: Iterable, F: Field, S::Item: Borrow<MatrixElement<F>>, { fn new(matrix: &'a S, len: usize) -> Self { Self { matrix, len, _field: PhantomData, } } } impl<'a, F, S> Iterable for SparseMatrixStream<'a, F, S> where S: Iterable, F: Field, S::Item: Borrow<MatrixElement<F>>, { type Item = (usize, usize, F); type Iter = SparseMatrixIter<S::Iter, F>; fn iter(&self) -> Self::Iter { Self::Iter { it: self.matrix.iter(), row: self.len - 1, _field: self._field, } } fn len(&self) -> usize { self.matrix.len() } } impl<F, I> Iterator for SparseMatrixIter<I, F> where I: Iterator, F: Field, I::Item: Borrow<MatrixElement<F>>, { type Item = (usize, usize, F); fn next(&mut self) -> Option<Self::Item> { let e = self.it.next()?; match *e.borrow() { MatrixElement::EOL => { self.row -= 1; self.next() } MatrixElement::Element((e, i)) => Some((self.row, i, e)), } } } pub struct JointIter<IA, IB, F> where IA: Iterator<Item = (usize, usize, F)>, IB: Iterator<Item = (usize, usize, F)>, F: Field, { matrix_a: IA, matrix_b: IB, current_a: Option<(usize, usize, F)>, current_b: Option<(usize, usize, F)>, } impl<IA, IB, F> Iterator for JointIter<IA, IB, F> where IA: Iterator<Item = (usize, usize, F)>, IB: Iterator<Item = (usize, usize, F)>, F: Field, { type Item = (usize, usize, F); #[inline(always)] fn next(&mut self) -> Option<Self::Item> { match (self.current_a, self.current_b) { // If all streams are empty, return None (None, None) => None, // If only the lhs is available, stream it (Some(e), None) => {
(None, Some((i, j, _))) => { self.current_b = self.matrix_b.next(); Some((i, j, F::zero())) } // If only the two are available simultaneously, we have to make a choice: (Some((ia, ja, ea)), Some((ib, jb, _))) => { // two values on the same coordinate => advance both if ia == ib && ja == jb { self.current_a = self.matrix_a.next(); self.current_b = self.matrix_b.next(); Some((ia, ja, ea)) // lhs is ahead => advance rhs // } else if ja < jb || (ja == jb && ib > ia) { } else if ia < ib || (ia == ib && jb > ja) { self.current_b = self.matrix_b.next(); Some((ib, jb, F::zero())) // rhs is ahed => advance lhs // } else if ja > jb || (ja==jb && ia > ib) { } else if ia > ib || (ia == ib && ja > jb) { self.current_a = self.matrix_a.next(); Some((ia, ja, ea)) // it should never happen e.g. that ib > ia and jb < ja } else { panic!("Format invalid!") } } } } } #[derive(Clone, Copy)] pub struct JointValStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { matrix_a: SparseMatrixStream<'a, F, SA>, matrix_b: SparseMatrixStream<'a, F, SB>, matrix_c: SparseMatrixStream<'a, F, SC>, joint_len: usize, _field: PhantomData<F>, } impl<'a, SA, SB, SC, F> JointValStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { pub fn new( matrix_a: &'a SA, matrix_b: &'a SB, matrix_c: &'a SC, len: usize, joint_len: usize, ) -> Self { Self { matrix_a: SparseMatrixStream::new(matrix_a, len), matrix_b: SparseMatrixStream::new(matrix_b, len), matrix_c: SparseMatrixStream::new(matrix_c, len), joint_len, _field: PhantomData, } } } impl<IA, IB, F> JointIter<IA, IB, F> where IA: Iterator<Item = (usize, usize, F)>, IB: Iterator<Item = (usize, usize, F)>, F: Field, { fn new(mut matrix_a: IA, mut matrix_b: IB) -> Self { let current_a = matrix_a.next(); let current_b = matrix_b.next(); Self { matrix_a, matrix_b, current_a, current_b, } } } impl<'a, SA, SB, SC, F> Iterable for JointValStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { type Item = F; type Iter = TrimValIter< JointIter< JointIter<SparseMatrixIter<SA::Iter, F>, SparseMatrixIter<SB::Iter, F>, F>, SparseMatrixIter<SC::Iter, F>, F, >, F, >; fn iter(&self) -> Self::Iter { let matrix_a = self.matrix_a.iter(); let matrix_b = self.matrix_b.iter(); let matrix_c = self.matrix_c.iter(); TrimValIter(JointIter::new(JointIter::new(matrix_a, matrix_b), matrix_c)) } fn len(&self) -> usize { self.joint_len } } pub struct TrimValIter<I, F>(I) where I: Iterator<Item = (usize, usize, F)>, F: Field; impl<I, F> Iterator for TrimValIter<I, F> where I: Iterator<Item = (usize, usize, F)>, F: Field, { type Item = F; #[inline(always)] fn next(&mut self) -> Option<Self::Item> { Some(self.0.next()?.2) } } pub struct TrimRowIter<I, F>(I) where I: Iterator<Item = (usize, usize, F)>, F: Field; impl<I, F> Iterator for TrimRowIter<I, F> where I: Iterator<Item = (usize, usize, F)>, F: Field, { type Item = usize; #[inline(always)] fn next(&mut self) -> Option<Self::Item> { let item = self.0.next()?; Some(item.0) } } pub struct TrimColIter<I, T>(I) where I: Iterator<Item = (usize, usize, T)>; impl<I, T> Iterator for TrimColIter<I, T> where I: Iterator<Item = (usize, usize, T)>, { type Item = usize; #[inline(always)] fn next(&mut self) -> Option<Self::Item> { let item = self.0.next()?; Some(item.1) } } #[derive(Clone, Copy)] pub struct JointRowStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { matrix_a: SparseMatrixStream<'a, F, SA>, matrix_b: SparseMatrixStream<'a, F, SB>, matrix_c: SparseMatrixStream<'a, F, SC>, joint_len: usize, _field: PhantomData<F>, } impl<'a, SA, SB, SC, F> JointRowStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { pub fn new( matrix_a: &'a SA, matrix_b: &'a SB, matrix_c: &'a SC, len: usize, joint_len: usize, ) -> Self { Self { matrix_a: SparseMatrixStream::new(matrix_a, len), matrix_b: SparseMatrixStream::new(matrix_b, len), matrix_c: SparseMatrixStream::new(matrix_c, len), joint_len, _field: PhantomData, } } } impl<'a, SA, SB, SC, F> Iterable for JointRowStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { type Item = usize; type Iter = TrimRowIter< JointIter< JointIter<SparseMatrixIter<SA::Iter, F>, SparseMatrixIter<SB::Iter, F>, F>, SparseMatrixIter<SC::Iter, F>, F, >, F, >; fn iter(&self) -> Self::Iter { let matrix_a = self.matrix_a.iter(); let matrix_b = self.matrix_b.iter(); let matrix_c = self.matrix_c.iter(); TrimRowIter(JointIter::new(JointIter::new(matrix_a, matrix_b), matrix_c)) } fn len(&self) -> usize { self.joint_len } } #[derive(Clone, Copy)] pub struct JointColStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { matrix_a: SparseMatrixStream<'a, F, SA>, matrix_b: SparseMatrixStream<'a, F, SB>, matrix_c: SparseMatrixStream<'a, F, SC>, joint_len: usize, _field: PhantomData<F>, } impl<'a, SA, SB, SC, F> JointColStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { pub fn new( matrix_a: &'a SA, matrix_b: &'a SB, matrix_c: &'a SC, len: usize, joint_len: usize, ) -> Self { Self { matrix_a: SparseMatrixStream::new(matrix_a, len), matrix_b: SparseMatrixStream::new(matrix_b, len), matrix_c: SparseMatrixStream::new(matrix_c, len), joint_len, _field: PhantomData, } } } impl<'a, SA, SB, SC, F> Iterable for JointColStream<'a, SA, SB, SC, F> where SA: Iterable, SB: Iterable, SC: Iterable, F: Field, SA::Item: Borrow<MatrixElement<F>>, SB::Item: Borrow<MatrixElement<F>>, SC::Item: Borrow<MatrixElement<F>>, { type Item = usize; type Iter = TrimColIter< JointIter< JointIter<SparseMatrixIter<SA::Iter, F>, SparseMatrixIter<SB::Iter, F>, F>, SparseMatrixIter<SC::Iter, F>, F, >, F, >; fn iter(&self) -> Self::Iter { let matrix_a = self.matrix_a.iter(); let matrix_b = self.matrix_b.iter(); let matrix_c = self.matrix_c.iter(); TrimColIter(JointIter::new(JointIter::new(matrix_a, matrix_b), matrix_c)) } fn len(&self) -> usize { self.joint_len } } #[test] fn test_joint_val() { use crate::iterable::dummy::Mat; use ark_bls12_381::Fr; let a = [ MatrixElement::EOL, MatrixElement::Element((Fr::from(1u64), 1)), MatrixElement::EOL, MatrixElement::Element((Fr::from(2u64), 0)), ]; let b = [ MatrixElement::EOL, MatrixElement::Element((Fr::from(1u64), 1)), MatrixElement::EOL, MatrixElement::Element((Fr::from(2u64), 0)), ]; let c = [ MatrixElement::EOL, MatrixElement::Element((Fr::from(1u64), 1)), MatrixElement::EOL, MatrixElement::Element((Fr::from(2u64), 0)), ]; let a_stream = Mat(&a, 2); let b_stream = Mat(&b, 2); let c_stream = Mat(&c, 2); let joint_a = JointValStream::new(&a_stream, &b_stream, &c_stream, 2, 2); assert_eq!(joint_a.len(), joint_a.iter().count()); let mut joint_a_it = joint_a.iter(); assert_eq!(joint_a_it.next(), Some(Fr::from(1u64))); assert_eq!(joint_a_it.next(), Some(Fr::from(2u64))); assert_eq!(joint_a_it.next(), None); } #[test] fn test_matrix() { use ark_bls12_381::Fr; use ark_std::test_rng; use crate::circuit::{ generate_relation, matrix_into_colmaj, matrix_into_rowmaj, random_circuit, Circuit, }; use crate::iterable::dummy::Mat; let rng = &mut test_rng(); let num_constraints = 16; let num_variables = num_constraints; let rows = num_variables; let circuit: Circuit<Fr> = random_circuit(rng, num_constraints, num_variables); let r1cs = generate_relation(circuit); let acolm = matrix_into_rowmaj(&r1cs.a); let bcolm = matrix_into_rowmaj(&r1cs.b); let ccolm = matrix_into_rowmaj(&r1cs.c); let a_colm = Mat(acolm.as_slice(), rows); let b_colm = Mat(bcolm.as_slice(), rows); let c_colm = Mat(ccolm.as_slice(), rows); let arowm = matrix_into_colmaj(&r1cs.a, rows); let browm = matrix_into_colmaj(&r1cs.b, rows); let crowm = matrix_into_colmaj(&r1cs.c, rows); let a_rowm = Mat(arowm.as_slice(), rows); let b_rowm = Mat(browm.as_slice(), rows); let c_rowm = Mat(crowm.as_slice(), rows); let nonzero = num_constraints; let joint_len = num_constraints * 3; let row = JointRowStream::new(&a_colm, &b_colm, &c_colm, nonzero, joint_len); let col = JointColStream::new(&a_colm, &b_colm, &c_colm, nonzero, joint_len); // in row major, the rows should be plain decreasing let mut state = row.iter().next().unwrap(); for (x, _y) in row.iter().zip(col.iter()) { assert!(state >= x); state = x; } let row = JointColStream::new(&a_rowm, &b_rowm, &c_rowm, nonzero, joint_len); let col = JointRowStream::new(&a_rowm, &b_rowm, &c_rowm, nonzero, joint_len); // in row major, the rows should be plain decreasing let mut state = col.iter().next().unwrap(); for (_x, y) in row.iter().zip(col.iter()) { // println!("pos: ({}, {})", x, y); assert!(state >= y); state = y; } }
self.current_a = self.matrix_a.next(); Some(e) } // If only the rhs is available, pad it with zeros
test_models.py
from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='[email protected]', password='test1234'): return get_user_model().objects.create_user(email, password) class ModelTests(TestCase): def test_create_user_with_email_successful(self): email = '[email protected]' password = 'test1234' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): email = '[email protected]' user = get_user_model().objects.create_user(email, 'test1234') self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test1234') def test_create_new_superuser(self):
def test_tag_str(self): tag = models.Tag.objects.create( user=sample_user(), name='Vegan' ) self.assertEqual(str(tag), tag.name) def test_ingredient_str(self): ingredient = models.Ingredient.objects.create( user=sample_user(), name='Cucumber' ) self.assertEqual(str(ingredient), ingredient.name) def test_recipe_str(self): recipe = models.Recipe.objects.create( user=sample_user(), title='Staek and mushroom sauce', time_minutes=5, price=5.00 ) self.assertEqual(str(recipe), recipe.title)
user = get_user_model().objects.create_superuser( '[email protected]', 'test1234' ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)
list.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router' import { IRol } from './interface'; import { RolService } from './service'; import { IDatagridOptions } from '../../../shared/datagrid/interface' import { DataGridComponent } from '../../../shared/datagrid/component'; import { ModalDialogService } from '../../../shared/dialog/service' @Component({ template: ` <div> <datagrid [options]="options" [service]="service"></datagrid> </div> ` }) export class
{ options: IDatagridOptions; constructor( public service: RolService, protected router: Router, protected dialogService: ModalDialogService, ) { } ngOnInit() { this.options = { pageSize: 20, title: "Roles", baseUrl: "/admin/seguridad/roles", columns: [ { name: "nombre", caption: "Nombre", sortDirection: 0, width: "auto", sortable: false }, { name: "descripcion", caption: "Descripcion", sortDirection: 0, width: "auto", sortable: false } ], showHeader: true, editable: false } } }
ListRolesComponent
umount.go
package commands import ( "github.com/pkg/errors" "github.com/urfave/cli" "github.com/asmyasnikov/droot/mounter" ) var CommandArgUmount = "--root ROOT_DIR" var CommandUmount = cli.Command{ Name: "umount", Usage: "Umount directory mounted by 'run' command", Action: fatalOnError(doUmount), Flags: []cli.Flag{ cli.StringFlag{Name: "root, r", Usage: "Root directory path for chrooted"}, }, } func doUmount(c *cli.Context) error
{ optRootDir := c.String("root") if optRootDir == "" { cli.ShowCommandHelp(c, "umount") return errors.New("--root option required") } rootDir, err := mounter.ResolveRootDir(optRootDir) if err != nil { return err } mnt := mounter.NewMounter(rootDir) return mnt.UmountRoot() }
templates.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package templates import ( "bytes" "errors" "fmt" "net/http" "strconv" "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Templates{}) } // Templates is a middleware which executes response bodies as Go templates. // The syntax is documented in the Go standard library's // [text/template package](https://golang.org/pkg/text/template/). // // ⚠️ Template functions/actions are still experimental, so they are subject to change. // // [All Sprig functions](https://masterminds.github.io/sprig/) are supported. // // In addition to the standard functions and the Sprig library, Caddy adds // extra functions and data that are available to a template: // // ##### `.Args` // // Access arguments passed to this page/context, for example as the result of a `include`. // // ``` // {{.Args 0}} // first argument // ``` // // ##### `.Cookie` // // Gets the value of a cookie by name. // // ``` // {{.Cookie "cookiename"}} // ``` // // ##### `env` // // Gets an environment variable. // // ``` // {{env "VAR_NAME"}} // ``` // // ##### `placeholder` // // Gets an [placeholder variable](/docs/conventions#placeholders). // The braces (`{}`) have to be omitted. // // ``` // {{placeholder "http.request.uri.path"}} // {{placeholder "http.error.status_code"}} // ``` // // ##### `.Host` // // Returns the hostname portion (no port) of the Host header of the HTTP request. // // ``` // {{.Host}} // ``` // // ##### `httpInclude` // // Includes the contents of another file by making a virtual HTTP request (also known as a sub-request). The URI path must exist on the same virtual server because the request does not use sockets; instead, the request is crafted in memory and the handler is invoked directly for increased efficiency. // // ``` // {{httpInclude "/foo/bar?q=val"}} // ``` // // ##### `import` // // Imports the contents of another file and adds any template definitions to the template stack. If there are no defitions, the filepath will be the defition name. Any {{ define }} blocks will be accessible by {{ template }} or {{ block }}. Imports must happen before the template or block action is called // // **filename.html** // ``` // {{ define "main" }} // content // {{ end }} // // **index.html** // ``` // {{ import "/path/to/file.html" }} // {{ template "main" }} // ``` // // ##### `include` // // Includes the contents of another file and renders in-place. Optionally can pass key-value pairs as arguments to be accessed by the included file. // // ``` // {{include "path/to/file.html"}} // no arguments // {{include "path/to/file.html" "arg1" 2 "value 3"}} // with arguments // ``` // // ##### `listFiles` // // Returns a list of the files in the given directory, which is relative to the template context's file root. // // ``` // {{listFiles "/mydir"}} // ``` // // ##### `markdown` // // Renders the given Markdown text as HTML. // // ``` // {{markdown "My _markdown_ text"}} // ``` // // ##### `.RemoteIP` // // Returns the client's IP address. // // ``` // {{.RemoteIP}} // ``` // // ##### `.Req` // // Accesses the current HTTP request, which has various fields, including: // // - `.Method` - the method // - `.URL` - the URL, which in turn has component fields (Scheme, Host, Path, etc.) // - `.Header` - the header fields // - `.Host` - the Host or :authority header of the request // // ``` // {{.Req.Header.Get "User-Agent"}} // ``` // // ##### `.OriginalReq` // // Like .Req, except it accesses the original HTTP request before rewrites or other internal modifications. // // ##### `.RespHeader.Add` // // Adds a header field to the HTTP response. // // ``` // {{.RespHeader.Add "Field-Name" "val"}} // ``` // // ##### `.RespHeader.Del` // // Deletes a header field on the HTTP response. // // ``` // {{.RespHeader.Del "Field-Name"}} // ``` // // ##### `.RespHeader.Set` // // Sets a header field on the HTTP response, replacing any existing value. // // ``` // {{.RespHeader.Set "Field-Name" "val"}} // ``` // // ##### `splitFrontMatter` // // Splits front matter out from the body. Front matter is metadata that appears at the very beginning of a file or string. Front matter can be in YAML, TOML, or JSON formats: // // **TOML** front matter starts and ends with `+++`: // // ``` // +++ // template = "blog" // title = "Blog Homepage" // sitename = "A Caddy site" // +++ // ``` // // **YAML** is surrounded by `---`: // // ``` // --- // template: blog // title: Blog Homepage // sitename: A Caddy site // --- // ``` // // // **JSON** is simply `{` and `}`: // // ``` // { // "template": "blog", // "title": "Blog Homepage", // "sitename": "A Caddy site" // } // ``` // // The resulting front matter will be made available like so: // // - `.Meta` to access the metadata fields, for example: `{{$parsed.Meta.title}}` // - `.Body` to access the body after the front matter, for example: `{{markdown $parsed.Body}}` // // // ##### `stripHTML` // // Removes HTML from a string. // // ``` // {{stripHTML "Shows <b>only</b> text content"}} // ``` // type Templates struct { // The root path from which to load files. Required if template functions // accessing the file system are used (such as include). Default is // `{http.vars.root}` if set, or current working directory otherwise. FileRoot string `json:"file_root,omitempty"` // The MIME types for which to render templates. It is important to use // this if the route matchers do not exclude images or other binary files. // Default is text/plain, text/markdown, and text/html. MIMETypes []string `json:"mime_types,omitempty"` // The template action delimiters. If set, must be precisely two elements: // the opening and closing delimiters. Default: `["{{", "}}"]` Delimiters []string `json:"delimiters,omitempty"` } // CaddyModule returns the Caddy module information. func (Templates) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.templates", New: func() caddy.Module { return new(Templates) }, } } // Provision provisions t. func (t *Templates) Provision(ctx caddy.Context) error { if t.MIMETypes == nil { t.MIMETypes = defaultMIMETypes } if t.FileRoot == "" { t.FileRoot = "{http.vars.root}" } return nil } // Validate ensures t has a valid configuration. func (t *Templates) Validate() error { if len(t.Delimiters) != 0 && len(t.Delimiters) != 2 { return fmt.Errorf("delimiters must consist of exactly two elements: opening and closing") } return nil } func (t *Templates) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { buf := bufPool.Get().(*bytes.Buffer) buf.Reset() defer bufPool.Put(buf) // shouldBuf determines whether to execute templates on this response, // since generally we will not want to execute for images or CSS, etc. shouldBuf := func(status int, header http.Header) bool { ct := header.Get("Content-Type") for _, mt := range t.MIMETypes { if strings.Contains(ct, mt) { return true } } return false } rec := caddyhttp.NewResponseRecorder(w, buf, shouldBuf) err := next.ServeHTTP(rec, r) if err != nil { return err } if !rec.Buffered() { return nil } err = t.executeTemplate(rec, r) if err != nil { return err } rec.Header().Set("Content-Length", strconv.Itoa(buf.Len())) rec.Header().Del("Accept-Ranges") // we don't know ranges for dynamically-created content rec.Header().Del("Last-Modified") // useless for dynamic content since it's always changing // we don't know a way to quickly generate etag for dynamic content, // and weak etags still cause browsers to rely on it even after a // refresh, so disable them until we find a better way to do this rec.Header().Del("Etag") return rec.WriteResponse() } // executeTemplate executes the template contained in wb.buf and replaces it with the results. func (t *Templates) executeTemplate(rr caddyhttp.ResponseRecorder, r *http.Request) error { var fs http.FileSystem if t.FileRoot != "" { repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) fs = http.Dir(repl.ReplaceAll(t.FileRoot, ".")) } ctx := &TemplateContext{ Root: fs, Req: r, RespHeader: WrappedHeader{rr.Header()}, config: t, } err := ctx.executeTemplateInBuffer(r.URL.Path, rr.Buffer()) if err != nil { // templates may return a custom HTTP error to be propagated to the client,
} return caddyhttp.Error(http.StatusInternalServerError, err) } return nil } // virtualResponseWriter is used in virtualized HTTP requests // that templates may execute. type virtualResponseWriter struct { status int header http.Header body *bytes.Buffer } func (vrw *virtualResponseWriter) Header() http.Header { return vrw.header } func (vrw *virtualResponseWriter) WriteHeader(statusCode int) { vrw.status = statusCode } func (vrw *virtualResponseWriter) Write(data []byte) (int, error) { return vrw.body.Write(data) } var defaultMIMETypes = []string{ "text/html", "text/plain", "text/markdown", } // Interface guards var ( _ caddy.Provisioner = (*Templates)(nil) _ caddy.Validator = (*Templates)(nil) _ caddyhttp.MiddlewareHandler = (*Templates)(nil) )
// otherwise for any other error we assume the template is broken var handlerErr caddyhttp.HandlerError if errors.As(err, &handlerErr) { return handlerErr
reviews.page.ts
/* Authors : initappz (Rahul Jograna) Website : https://initappz.com/ App Name : ionic 5 foodies app Created : 28-Feb-2021 This App Template Source code is licensed as per the terms found in the Website https://initappz.com/license Copyright and Good Faith Purchasers © 2020-present initappz. */ import { Component, OnInit } from '@angular/core'; import { UtilService } from 'src/app/services/util.service'; import { NavController } from '@ionic/angular'; import * as moment from 'moment'; import { ApisService } from 'src/app/services/apis.service'; @Component({ selector: 'app-reviews', templateUrl: './reviews.page.html', styleUrls: ['./reviews.page.scss'], }) export class ReviewsPage implements OnInit { dummy: any[] = []; reviews: any[] = []; constructor( public api: ApisService, public util: UtilService, private navCtrl: NavController ) { this.getReviews(); } ngOnInit() { } getReviews() { const param = { id: localStorage.getItem('uid'), where: 'sid = ' + localStorage.getItem('uid') }; this.dummy = Array(10); this.api.post('rating/getFromIDs', param).then((data: any) => { this.dummy = []; console.log(data); if (data && data.status === 200) { this.reviews = data.data; } }, error => { console.log(error);
back() { this.navCtrl.back(); } getDate(date) { return moment(date).format('lll'); } }
this.dummy = []; this.util.errorToast(this.util.translate('Something went wrong')); }); }
article_slideshow_item.js
import React from "react" import { injectIntl, Link } from "gatsby-plugin-intl" import Img from "gatsby-image" import { Container, Row, Col } from "react-bootstrap" import TimeAndAuthor from "../shared/timeAndAuthor" import removeMd from "remove-markdown" class
extends React.Component { render() { return ( <Container fluid={true}> <Row> <Col xs={{ order: 12, span: 12 }} md={{ order: 1, span: 6 }} className="slide-content-container" > <p className={"slide-category"}> {this.props.intl.locale === "en" ? this.props.article.category.name_en : this.props.article.category.name} </p> <Link to={`/${this.props.article.fields.slug}`}> <h5 className={"link-title white-text"}> {this.props.intl.locale === "en" ? this.props.article.title_en : this.props.article.title} </h5> </Link> <p className={"description"}> {this.props.intl.locale === "en" ? removeMd( this.props.article.content_en .substring(0, 250) .concat("...") ) : removeMd( this.props.article.content.substring(0, 250).concat("...") )} </p> <TimeAndAuthor author={this.props.article.author} date={this.props.article.publishedAt} textClass={"time-and-author-link"} /> </Col> <Col xs={{ order: 1, span: 12 }} md={{ order: 12, span: 6 }} lg={{ span: 5, offset: 1 }} className="slide-image-container" > <Img fluid={this.props.article.image.childImageSharp.fluid} className="slide-image" alt="article image" /> </Col> </Row> </Container> ) } } export default injectIntl(ArticleSlideshowItem)
ArticleSlideshowItem
views.py
import datetime import json from flask import url_for from flask import redirect from flask import render_template from flask_login import login_user from flask_login import logout_user from . import blueprint_auth from .forms import RegisterForm from .forms import LoginForm from .utils_cms import generate_code from .utils_cms import send_sms_code from ..models import db from ..models import User @blueprint_auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(phone=form.phone.data).first() login_user(user) return redirect(url_for('blueprint_time.index')) return render_template('auth/login.html', form=form) @blueprint_auth.route('/logout', methods=['GET', 'POST']) def logout(): logout_user() return redirect(url_for('blueprint_auth.login')) @blueprint_auth.route('/register', methods=['GET', 'POST']) def register():
@blueprint_auth.route('/sms_code/<string:phone>', methods=['GET', 'POST']) def sms_code(phone): user = User.query.filter_by(phone=phone).first() if not user: ret = {'result': 'error'} return json.dumps(ret) code = generate_code() ret = send_sms_code(phone, code) if not ret: ret = {'result': 'error'} return json.dumps(ret) user.sms_code = code user.updated_at = datetime.datetime.now() db.session.commit() ret = {'result': 'success'} return json.dumps(ret)
form = RegisterForm() if form.validate_on_submit(): new_user = User.query.filter_by(phone=form.phone.data).first() new_user.set_password(form.password.data) db.session.commit() return redirect(url_for('blueprint_auth.login')) return render_template('auth/register.html', form=form)
lifetime.py
#contextos
## 1 Configuração ### Add configuração app.config["DEBUG"] = True app.config["SQLALCHEMY_DB_URI"] = "mysql://" ### Registrar Rotas @app.route("/path") def funcao(): pass # ou app.add_url_rule("/path", funcao) ### Inicializar extensões #from flask_admin import Admin #Admin.init_app(app) ### Registrar Blueprints app.register_blueprint(...) ### add hooks @app.before_request(...) @app.errorhandler(...) ### Chamar outras factories #views.init_app(app) ## 2 App Context ### App está pronto! 'app' ### Testar #app.test_client # debug # objetos globais do flask # (request, session, g) #- Hooks ## 3 Request Context ### usar globais do flask
from flask import Flask import flask app = Flask(__name__)
worker.go
/* Copyright 2017 The Nuclio Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package worker import ( "net/http" "sync/atomic" "time" "github.com/nuclio/nuclio/pkg/processor/cloudevent" "github.com/nuclio/nuclio/pkg/processor/runtime" "github.com/nuclio/nuclio/pkg/processor/status" "github.com/nuclio/nuclio/pkg/processor/util/clock" "github.com/nuclio/logger" "github.com/nuclio/nuclio-sdk-go" ) // Worker holds all the required state and context to handle a single request type Worker struct { logger logger.Logger context nuclio.Context index int runtime runtime.Runtime statistics Statistics structuredCloudEvent cloudevent.Structured binaryCloudEvent cloudevent.Binary eventTime *time.Time } // NewWorker creates a new worker func NewWorker(parentLogger logger.Logger, index int, runtime runtime.Runtime) (*Worker, error)
// ProcessEvent sends the event to the associated runtime func (w *Worker) ProcessEvent(event nuclio.Event, functionLogger logger.Logger) (interface{}, error) { w.eventTime = clock.Now() // process the event at the runtime response, err := w.runtime.ProcessEvent(event, functionLogger) w.eventTime = nil // check if there was a processing error. if so, log it if err != nil { atomic.AddUint64(&w.statistics.EventsHandledError, 1) } else { success := true switch typedResponse := response.(type) { case *nuclio.Response: success = typedResponse.StatusCode < http.StatusBadRequest case nuclio.Response: success = typedResponse.StatusCode < http.StatusBadRequest } if success { atomic.AddUint64(&w.statistics.EventsHandledSuccess, 1) } else { atomic.AddUint64(&w.statistics.EventsHandledError, 1) } } return response, err } // GetStatistics returns a pointer to the statistics object. This must not be modified by the reader func (w *Worker) GetStatistics() *Statistics { return &w.statistics } // GetIndex returns the index of the worker, as specified during creation func (w *Worker) GetIndex() int { return w.index } // GetRuntime returns the runtime of the worker, as specified during creation func (w *Worker) GetRuntime() runtime.Runtime { return w.runtime } // GetStatus returns the status of the worker, as updated by the runtime func (w *Worker) GetStatus() status.Status { return w.runtime.GetStatus() } // Stop stops the worker and associated runtime func (w *Worker) Stop() error { return w.runtime.Stop() } // GetStructuredCloudEvent return a structued clould event func (w *Worker) GetStructuredCloudEvent() *cloudevent.Structured { return &w.structuredCloudEvent } // GetBinaryCloudEvent return a binary cloud event func (w *Worker) GetBinaryCloudEvent() *cloudevent.Binary { return &w.binaryCloudEvent } // GetEventTime return current event time, nil if we're not handling event func (w *Worker) GetEventTime() *time.Time { return w.eventTime } // ResetEventTime resets the event time func (w *Worker) ResetEventTime() { w.eventTime = nil } // Restart restarts the worker func (w *Worker) Restart() error { w.eventTime = nil return w.runtime.Restart() } // SupportsRestart returns true if the underlying runtime supports restart func (w *Worker) SupportsRestart() bool { return w.runtime.SupportsRestart() }
{ newWorker := Worker{ logger: parentLogger, index: index, runtime: runtime, } // return an instance of the default worker return &newWorker, nil }
auth_controller.py
from sanic import Blueprint from sanic.response import json from sanic_openapi import doc from ..model.database import User from ..service.auth_helper import Auth from ..util.dto import AuthDto, json_response from ..util.response import response_message, USER_NOT_EXIST, SUCCESS user_auth = AuthDto.user_auth bp = Blueprint('auth', url_prefix='/auth') @bp.post('/login') @doc.summary('User login interface') @doc.consumes(user_auth, location='body') @doc.produces(json_response) async def
(request): ret = await Auth.login_user(data=request.json) return json(ret) @bp.post('/logout') @doc.summary('User logout interface') @doc.consumes(doc.String(name='X-Token'), location='header') @doc.produces(json_response) async def handler(request): auth_header = request.headers.get('X-Token') return json(await Auth.logout_user(data=auth_header))
handler
sports-templates.setup.ts
import { DiProcess, logTemplates, TemplateRegistry, templateService } from '@wikia/ad-engine'; import { Injectable } from '@wikia/dependency-injection'; import { merge } from 'rxjs'; import { registerBfaaTemplate } from './bfaa-template'; import { registerBfabTemplate } from './bfab-template'; import { registerLogoReplacementTemplate } from './logo-replacement-template'; @Injectable() export class SportsTemplatesSetup implements DiProcess { constructor(private registry: TemplateRegistry) { templateService.setInitializer(this.registry); } execute(): void {
const logoReplacement$ = registerLogoReplacementTemplate(this.registry); logTemplates(merge(bfaa$, bfab$, logoReplacement$)); } }
const bfaa$ = registerBfaaTemplate(this.registry); const bfab$ = registerBfabTemplate(this.registry);
exchange.go
package emmq import ( "context" "fmt" "log" "sync" "time" "github.com/dgraph-io/badger/v3" ) type ( // Exchange represents a message exchange Exchange struct { opts Options db *badger.DB queues map[string]chan Delivery topics map[string]map[string]struct{} quit chan struct{} wg *sync.WaitGroup mu *sync.RWMutex } // Options represents exchange options Options struct { PollInterval time.Duration PollBatchSize int VisibilityTimeout time.Duration BadgerOptions badger.Options OnError func(error) } // PublishOptions represents message publish options PublishOptions struct { Wait bool Delay time.Duration } ) // WithDelay delays message consumption until the first poll interval // after the specified duration func WithDelay(d time.Duration) func(*PublishOptions) { return func(o *PublishOptions) { o.Delay = d } } // WithPolling configures the exchange poll interval and batch size func WithPolling(interval time.Duration, batchSize int) func(*Options) { return func(o *Options) { o.PollInterval = interval o.PollBatchSize = batchSize } } // WithWait delays message consumption until the next poll interval func WithWait() func(*PublishOptions) { return func(o *PublishOptions) { o.Wait = true } } // Open opens a new exchange with the specified options func Open(path string, optFns ...func(*Options)) (*Exchange, error) { o := Options{ PollInterval: 100 * time.Millisecond, PollBatchSize: 10, VisibilityTimeout: 30 * time.Second, BadgerOptions: badger.DefaultOptions(path), OnError: func(err error) { log.Println(err) }, } for _, fn := range optFns { fn(&o) } db, err := badger.Open(o.BadgerOptions) if err != nil { return nil, err } return &Exchange{ opts: o, db: db, queues: map[string]chan Delivery{}, topics: map[string]map[string]struct{}{},
quit: make(chan struct{}), wg: new(sync.WaitGroup), mu: new(sync.RWMutex), }, nil } // Declare declares a new queue with the specified name func (e *Exchange) Declare(queue string) (Queue, error) { e.mu.Lock() defer e.mu.Unlock() if _, exists := e.queues[queue]; exists { return Queue{}, fmt.Errorf("queue already exists: %s", queue) } p, err := encodePrefix(queue) if err != nil { return Queue{}, err } e.queues[queue] = nil return Queue{ name: queue, prefix: p, exchange: e, }, nil } // Publish publishes the specified message // If no queues are bound to the topic then the message will be discarded func (e *Exchange) Publish(topic string, value []byte, optFns ...func(*PublishOptions)) error { var o PublishOptions for _, fn := range optFns { fn(&o) } e.mu.RLock() defer e.mu.RUnlock() wait := o.Wait || o.Delay > 0 now := time.Now().UTC() wb := e.db.NewWriteBatch() defer wb.Cancel() dm := map[chan Delivery]Delivery{} for q := range e.topics[topic] { var due time.Time ch := e.queues[q] if wait || ch == nil { due = now.Add(o.Delay) } else { due = now.Add(e.opts.VisibilityTimeout) } k, err := NewKey(q, due) if err != nil { return err } if err = wb.Set(k, value); err != nil { return err } if ch != nil { dm[ch] = Delivery{ Key: k, Value: value, exchange: e, } } } if err := wb.Flush(); err != nil { return err } if !wait { go func() { for ch, d := range dm { ch <- d } }() } return nil } // PurgeAll purges all messages in all queues func (e *Exchange) PurgeAll() error { return e.db.DropAll() } // Close closes the exchange and the underlying database func (e *Exchange) Close() error { e.mu.Lock() defer e.mu.Unlock() close(e.quit) e.wg.Wait() return e.db.Close() } func (e *Exchange) bind(topic string, q Queue) { e.mu.Lock() defer e.mu.Unlock() if t, ok := e.topics[topic]; ok { t[q.name] = struct{}{} } else { e.topics[topic] = map[string]struct{}{ q.name: {}, } } } func (e *Exchange) consume(ctx context.Context, q Queue) (<-chan Delivery, error) { e.mu.Lock() defer e.mu.Unlock() if ch, exists := e.queues[q.name]; exists && ch != nil { return nil, fmt.Errorf("queue already consumed: %s", q.name) } ch := make(chan Delivery) e.queues[q.name] = ch e.wg.Add(1) go func() { defer e.wg.Done() t := time.NewTicker(e.opts.PollInterval) for { select { case <-ctx.Done(): return case <-e.quit: return case <-t.C: ds, err := e.popBatch(q.prefix) if err != nil { e.opts.OnError(err) continue } for _, d := range ds { ch <- d } } } }() return ch, nil } func (e *Exchange) popBatch(prefix []byte) ([]Delivery, error) { var ds []Delivery err := e.db.Update(func(tx *badger.Txn) error { it := tx.NewIterator(badger.DefaultIteratorOptions) defer it.Close() var c int for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() { if !it.Valid() { break } i := it.Item() k := Key(i.KeyCopy(nil)) if k.DueAt().After(time.Now().UTC()) { break } v, err := i.ValueCopy(nil) if err != nil { return err } dk := k.Delay(e.opts.VisibilityTimeout) if err := tx.Set(dk, v); err != nil { return err } if err := tx.Delete(k); err != nil { return err } ds = append(ds, Delivery{Key: dk, Value: v, exchange: e}) c++ if c >= e.opts.PollBatchSize { break } } return nil }) if err != nil { return nil, err } return ds, nil } func (e *Exchange) delete(k Key) error { return e.db.Update(func(tx *badger.Txn) error { return tx.Delete(k) }) } func (e *Exchange) purge(prefix []byte) error { return e.db.DropPrefix(prefix) }
log.rs
use recap::Recap; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize, Recap)] #[recap(regex = r#"(?x) (?P<foo>\d+) \s+ (?P<bar>true|false) \s+ (?P<baz>\S+) "#)] struct LogEntry { foo: usize, bar: bool, baz: String, } fn main() -> Result<(), Box<dyn Error>> { let logs = r#"1 true hello 2 false world"#; for line in logs.lines() { if LogEntry::is_match(line) { let entry: LogEntry = line.parse()?; println!("{:#?}", entry); }
Ok(()) }
}
index.js
addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) const links = [ { 'name': 'My Professional Website', 'url': 'https://cthnn.github.io/' }, { 'name': 'My Favorite Project', 'url': 'https://github.com/Cthnn/VIP-Autonomous-Car' }, { 'name': 'A Link to my Favorite Song', 'url': 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' } ] const socials = [ {'name':'LinkedIn','svg':'https://simpleicons.org/icons/linkedin.svg','link':'https://www.linkedin.com/in/cthann/'}, {'name':'Instagram','svg':'https://simpleicons.org/icons/instagram.svg','link':'https://www.instagram.com/cth_n/'}, {'name':'Github','svg':'https://simpleicons.org/icons/github.svg','link':'https://github.com/Cthnn'} ] /** * Respond with hello worker text * @param {Request} request */ class LinksTransformer { constructor(links) { this.links = links } async element(element) { for (var link of this.links){ element.append(`<a href='${link.url}'>${link.name}</a>`, { html: true }); } } } class ProfileTransformer { async element(element) { element.removeAttribute('style') } } class AvatarTransformer { async element(element) { element.setAttribute('src', 'https://static-cdn.jtvnw.net/jtv_user_pictures/8fd15424-ab97-4249-ad18-4b0109befd16-profile_image-300x300.png'); } } class NameTransformer { async element(element) { element.setInnerContent('Cthan'); } } class SocialsTransformer{ constructor(socials) { this.socials = socials } async element(element) { for (var social of this.socials){ element.append(`<a href='${social.link}'><img src='${social.svg}'></img></a>`,{ html: true }) } } } class
{ async element(element) { element.setInnerContent('Ethan Cheung'); } } class BgTransformer{ async element(element) { element.setAttribute('style','background-color: #3760a7'); } } async function handleRequest(request) { if (request.url.split('/').pop() == 'links'){ const data = JSON.stringify(links) return new Response(data, { headers: { 'content-type': 'application/json;charset=UTF-8' }, }) } else{ const resp = await fetch('https://static-links-page.signalnerve.workers.dev',{ headers: { 'content-type': 'text/html' }, }) return new HTMLRewriter().on('div#links',new LinksTransformer(links)) .on('div#profile',new ProfileTransformer()) .on('img#avatar', new AvatarTransformer()) .on('h1#name',new NameTransformer()) .on('div#social',new ProfileTransformer()) .on('div#social', new SocialsTransformer(socials)) .on('title', new TitleTransformer()) .on('body', new BgTransformer()) .transform(resp); } }
TitleTransformer
write.rs
// This file is part of rss. // // Copyright © 2015-2017 The rust-syndication Developers // // This program is free software; you can redistribute it and/or modify // it under the terms of the MIT License and/or Apache 2.0 License. #![feature(test)] extern crate rss; extern crate test; use rss::Channel; use std::io::sink; use test::Bencher; #[bench] fn write_rss2sample(b: &mut Bencher) { let input: &[u8] = include_bytes!("../tests/data/rss2sample.xml"); let channel = Channel::read_from(input).expect("failed to parse feed"); b.iter(|| { let _ = channel.write_to(sink()).expect("failed to write"); }); } #[bench] fn w
b: &mut Bencher) { let input: &[u8] = include_bytes!("../tests/data/itunes.xml"); let channel = Channel::read_from(input).expect("failed to parse feed"); b.iter(|| { let _ = channel.write_to(sink()).expect("failed to write"); }); } #[bench] fn write_dublincore(b: &mut Bencher) { let input: &[u8] = include_bytes!("../tests/data/dublincore.xml"); let channel = Channel::read_from(input).expect("failed to parse feed"); b.iter(|| { let _ = channel.write_to(sink()).expect("failed to write"); }); } #[bench] fn write_syndication(b: &mut Bencher) { let input: &[u8] = include_bytes!("../tests/data/syndication.xml"); let channel = Channel::read_from(input).expect("failed to parse feed"); b.iter(|| { let _ = channel.write_to(sink()).expect("failed to write"); }); }
rite_itunes(
service_holder.rs
use std::{collections::HashMap, sync::Arc, path::{Path, PathBuf}}; use itertools::Itertools; use tokio::sync::Mutex; use crate::{error::{Error, Result}, model::Instance}; use super::{model::ServiceInfo, ServiceChangeListener}; /// 服务缓存 #[derive(Clone)] pub struct ServiceHolder { service_map: Arc<Mutex<HashMap<String, ServiceInfo>>>, callbacks: Arc<Mutex<HashMap<String, Vec<Box<dyn ServiceChangeListener>>>>>, cache_dir: PathBuf, update_when_empty: bool } impl ServiceHolder { pub async fn new(cache_dir: impl AsRef<Path>, update_when_empty: bool, load_at_start: bool) -> Result<Self> { let path = cache_dir.as_ref(); if !path.exists() { tokio::fs::create_dir_all(path).await .map_err(|err| Error::Fs("can not create cache dir".to_owned(), err))?; } let holder = ServiceHolder { service_map: Arc::new(Mutex::new(HashMap::new())), callbacks: Arc::new(Mutex::new(HashMap::new())), cache_dir: cache_dir.as_ref().to_path_buf(), update_when_empty }; if load_at_start { holder.load_from_disk().await?; } Ok(holder) } async fn load_from_disk(&self) -> Result<()> { let dir = self.cache_dir.as_path(); let map: HashMap<String, ServiceInfo> = nacos_sdk_core::cache::read_dir(dir).await?; let mut info_map = self.service_map.lock().await; info_map.extend(map.into_iter()); Ok(()) } pub async fn get_service_info( &self, service_name: &str, clusters: &[&str] ) -> Option<ServiceInfo> { let clusters = clusters.into_iter().join(","); let key = ServiceInfo::generate_key(service_name, clusters.as_str()); self.service_map.lock().await.get(key.as_str()).map(|data| data.clone()) } pub async fn update_service_info( &self, service_info: ServiceInfo ) { let key = service_info.get_key(); let old = self.service_map.lock().await.insert(key.clone(), service_info.clone()); let push_instance = Self::diff_instance(old.map(|x|x.hosts), service_info.hosts.clone()); let mut callbacks = self.callbacks.lock().await; let maybe_callbacks = callbacks.get_mut(key.as_str()); let mut default = vec![]; let vec = maybe_callbacks.unwrap_or(&mut default); for listener in vec { listener.changed(key.as_str(), push_instance.clone()).await; log::debug!("service change has been notified: {}", key.as_str()); } let result = nacos_sdk_core::cache::write_file( &service_info, self.cache_dir.clone(), key.as_str() ).await; if let Err(error) = result { log::warn!("can not write service_info cache to disk: {}", error); } log::debug!("service change has write to disk successed: {}", service_info.service_name); } fn diff_ins
tion<Vec<Instance>>, mut new: Vec<Instance>) -> Vec<Instance> { let old = match old { None => return new, Some(list) => list }; if old.is_empty() { return new; } for mut old_instance in old { match Self::get_same_instance(&new, &old_instance) { // 这里没有剔除已经在本地生效的instance // 调用者应该做去重处理来避免把该instance的权重错误加重 None => { // 如果new中没有该instance但是old中有,那么应该设置为剔除 old_instance.enabled = false; new.push(old_instance); }, // 其他情况不处理 _ => {} }; } new } fn get_same_instance<'a>(new: &'a Vec<Instance>, old: &'a Instance) -> Option<&'a Instance> { for item in new.iter() { if item.key() == old.key() { return Some(item) } } None } pub async fn register_subscribe( &self, service_name: String, clusters: String, listener: Box<dyn ServiceChangeListener> ) { let key = ServiceInfo::generate_key(service_name.as_str(), clusters.as_str()); let mut callback_map = self.callbacks.lock().await; if !callback_map.contains_key(key.as_str()) { callback_map.insert(key.clone(), vec![]); } let _ = callback_map.get_mut(key.as_str()).map(|v|v.push(listener)); } pub async fn get_service_info_map(&self) -> HashMap<String, ServiceInfo> { self.service_map.lock().await.clone() } }
tance(old: Op
dg_block.rs
use crate::utils; use super::{ cg_block::Cgblock, mdf3_block::{LinkedBlock, Mdf3Block}, }; #[derive(Debug, Clone, Copy)] pub struct Dgblock { #[allow(dead_code)] block_type: [u8; 2], #[allow(dead_code)] block_size: u16, #[allow(dead_code)] next: u32, #[allow(dead_code)] first: u32, #[allow(dead_code)] trigger_block: u32, #[allow(dead_code)] data_block: u32, #[allow(dead_code)] group_number: u16, #[allow(dead_code)] id_number: u16, #[allow(dead_code)] reserved: u32, } impl LinkedBlock for Dgblock { fn next(&self, stream: &[u8], little_endian: bool) -> Option<Self> where Self: std::marker::Sized, { if self.next == 0 { None } else { let (_pos, block) = Self::read(stream, self.next as usize, little_endian); Some(block) } } fn list(&self, stream: &[u8], little_endian: bool) -> Vec<Self> where Self: std::marker::Sized,
} impl Mdf3Block for Dgblock { fn read(stream: &[u8], position: usize, little_endian: bool) -> (usize, Self) { let mut pos = position; // Read block type to confirm let block_type: [u8; 2] = utils::read(stream, little_endian, &mut pos); if !utils::eq(&block_type, "DG".as_bytes()) { panic!( "DGBLOCK not found. Found: {}, {}", block_type[0], block_type[1] ); } let block_size = utils::read(stream, little_endian, &mut pos); let next = utils::read(stream, little_endian, &mut pos); let first = utils::read(stream, little_endian, &mut pos); let trigger_block = utils::read(stream, little_endian, &mut pos); let data_block = utils::read(stream, little_endian, &mut pos); let group_number = utils::read(stream, little_endian, &mut pos); let id_number = utils::read(stream, little_endian, &mut pos); let reserved = utils::read(stream, little_endian, &mut pos); ( pos, Dgblock { block_type, block_size, next, first, trigger_block, data_block, group_number, id_number, reserved, }, ) } } impl Dgblock { #[allow(dead_code)] pub fn data_location(&self) -> usize { self.data_block as usize } pub fn first_channel_group(&self, stream: &[u8], little_endian: bool) -> Cgblock { if self.first == 0 { panic!("Error"); } let (_pos, cg) = Cgblock::read(stream, self.first as usize, little_endian); cg } pub fn read_data(&self, _stream: &[u8], _little_endian: bool) -> Vec<u8> { todo!() } #[allow(dead_code)] pub fn write() { todo!() } pub fn read_all(stream: &[u8], little_endian: bool, position: usize) -> Vec<Self> { let mut all = Vec::new(); let mut next_dg = position; while next_dg != 0 { let (_pos, dg_block) = Dgblock::read(stream, next_dg, little_endian); next_dg = dg_block.next as usize; all.push(dg_block); } all } pub fn read_channel_groups(self, stream: &[u8], little_endian: bool) -> Vec<Cgblock> { let first_group = self.first_channel_group(stream, little_endian); first_group.list(stream, little_endian) } } #[cfg(test)] mod tests { use super::*; #[test] fn read() { let dg_data = [ 0x44, 0x47, 0x1C, 0x00, 0xF4, 0xDF, 0x10, 0x00, 0x99, 0xE4, 0x10, 0x00, 0x2B, 0xE5, 0x10, 0x00, 0xDC, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let position = 0; let (position, dg_block) = Dgblock::read(&dg_data, position, true); assert_eq!(position, 28); assert_eq!(dg_block.next, 1105908); assert_eq!(dg_block.first, 1107097); assert_eq!(dg_block.trigger_block, 1107243); assert_eq!(dg_block.data_block, 988); assert_eq!(dg_block.group_number, 1); assert_eq!(dg_block.id_number, 0); assert_eq!(dg_block.reserved, 0); } #[test] fn write() {} }
{ let mut all = Vec::new(); let next = self.next(stream, little_endian); all.push(*self); match next { None => {} Some(block) => all.append(&mut block.list(stream, little_endian)), } all }
setup.py
#! /usr/bin/env python from __future__ import print_function import sys import os import glob import platform # distutils is deprecated and vendored into setuptools now. from setuptools import setup from setuptools import Extension from setuptools import find_packages # Extra compiler arguments passed to *all* extensions. global_compile_args = [] # Extra compiler arguments passed to C++ extensions cpp_compile_args = [] # Extra linker arguments passed to C++ extensions cpp_link_args = [] # Extra compiler arguments passed to the main extension main_compile_args = [] # workaround segfaults on openbsd and RHEL 3 / CentOS 3 . see # https://bitbucket.org/ambroff/greenlet/issue/11/segfault-on-openbsd-i386 # https://github.com/python-greenlet/greenlet/issues/4 # https://github.com/python-greenlet/greenlet/issues/94 # pylint:disable=too-many-boolean-expressions is_linux = sys.platform.startswith('linux') # could be linux or linux2 if ((sys.platform == "openbsd4" and os.uname()[-1] == "i386") or ("-with-redhat-3." in platform.platform() and platform.machine() == 'i686') or (sys.platform == "sunos5" and os.uname()[-1] == "sun4v") or ("SunOS" in platform.platform() and platform.machine() == "sun4v") or (is_linux and platform.machine() == "ppc")): global_compile_args.append("-Os") if sys.platform == 'darwin': # The clang compiler doesn't use --std=c++11 by default cpp_compile_args.append("--std=gnu++11") elif sys.platform == 'win32' and "MSC" in platform.python_compiler(): # Older versions of MSVC (Python 2.7) don't handle C++ exceptions # correctly by default. While newer versions do handle exceptions by default, # they don't do it fully correctly. So we need an argument on all versions. #"/EH" == exception handling. # "s" == standard C++, # "c" == extern C functions don't throw # OR # "a" == standard C++, and Windows SEH; anything may throw, compiler optimizations # around try blocks are less aggressive. # /EHsc is suggested, as /EHa isn't supposed to be linked to other things not built # with it. # See https://docs.microsoft.com/en-us/cpp/build/reference/eh-exception-handling-model?view=msvc-160 handler = "/EHsc" cpp_compile_args.append(handler) # To disable most optimizations: #cpp_compile_args.append('/Od') # To enable assertions: #cpp_compile_args.append('/UNDEBUG') # To enable more compile-time warnings (/Wall produces a mountain of output). #cpp_compile_args.append('/W4') # To link with the debug C runtime...except we can't because we need # the Python debug lib too, and they're not around by default # cpp_compile_args.append('/MDd') # Support fiber-safe thread-local storage: "the compiler mustn't # cache the address of the TLS array, or optimize it as a common # subexpression across a function call." This would probably solve # some of the issues we had with MSVC caching the thread local # variables on the stack, leading to having to split some # functions up. Revisit those. cpp_compile_args.append("/GT") def readfile(filename): with open(filename, 'r') as f: # pylint:disable=unspecified-encoding return f.read() GREENLET_SRC_DIR = 'src/greenlet/' GREENLET_HEADER_DIR = GREENLET_SRC_DIR GREENLET_HEADER = GREENLET_HEADER_DIR + 'greenlet.h' GREENLET_TEST_DIR = 'src/greenlet/tests/' # The location of the platform specific assembly files # for switching. GREENLET_PLATFORM_DIR = GREENLET_SRC_DIR + 'platform/' def _find_platform_headers(): return glob.glob(GREENLET_PLATFORM_DIR + "switch_*.h") def
(): return glob.glob(GREENLET_SRC_DIR + "*.hpp") if hasattr(sys, "pypy_version_info"): ext_modules = [] headers = [] else: headers = [GREENLET_HEADER] if sys.platform == 'win32' and '64 bit' in sys.version: # this works when building with msvc, not with 64 bit gcc # switch_<platform>_masm.obj can be created with setup_switch_<platform>_masm.cmd obj_fn = 'switch_arm64_masm.obj' if platform.machine() == 'ARM64' else 'switch_x64_masm.obj' extra_objects = [os.path.join(GREENLET_PLATFORM_DIR, obj_fn)] else: extra_objects = [] if sys.platform == 'win32' and os.environ.get('GREENLET_STATIC_RUNTIME') in ('1', 'yes'): main_compile_args.append('/MT') elif hasattr(os, 'uname') and os.uname()[4] in ['ppc64el', 'ppc64le']: main_compile_args.append('-fno-tree-dominator-opts') ext_modules = [ Extension( name='greenlet._greenlet', sources=[ GREENLET_SRC_DIR + 'greenlet.cpp', ], language='c++', extra_objects=extra_objects, extra_compile_args=global_compile_args + main_compile_args + cpp_compile_args, extra_link_args=cpp_link_args, depends=[ GREENLET_HEADER, GREENLET_SRC_DIR + 'slp_platformselect.h', ] + _find_platform_headers() + _find_impl_headers() ), # Test extensions. # # We used to try hard to not include these in built # distributions, because we only distributed ``greenlet.so``. # That's really not important, now we have a clean layout with # the test directory nested inside a greenlet directory. See # https://github.com/python-greenlet/greenlet/issues/184 and # 189 Extension( name='greenlet.tests._test_extension', sources=[GREENLET_TEST_DIR + '_test_extension.c'], include_dirs=[GREENLET_HEADER_DIR], extra_compile_args=global_compile_args, ), Extension( name='greenlet.tests._test_extension_cpp', sources=[GREENLET_TEST_DIR + '_test_extension_cpp.cpp'], language="c++", include_dirs=[GREENLET_HEADER_DIR], extra_compile_args=global_compile_args + cpp_compile_args, extra_link_args=cpp_link_args, ), ] def get_greenlet_version(): with open('src/greenlet/__init__.py') as f: # pylint:disable=unspecified-encoding looking_for = '__version__ = \'' for line in f: if line.startswith(looking_for): version = line[len(looking_for):-2] return version raise ValueError("Unable to find version") setup( name="greenlet", version=get_greenlet_version(), description='Lightweight in-process concurrent programming', long_description=readfile("README.rst"), long_description_content_type="text/x-rst", url="https://greenlet.readthedocs.io/", keywords="greenlet coroutine concurrency threads cooperative", author="Alexey Borzenkov", author_email="[email protected]", maintainer='Jason Madden', maintainer_email='[email protected]', project_urls={ 'Bug Tracker': 'https://github.com/python-greenlet/greenlet/issues', 'Source Code': 'https://github.com/python-greenlet/greenlet/', 'Documentation': 'https://greenlet.readthedocs.io/', }, license="MIT License", platforms=['any'], package_dir={'': 'src'}, packages=find_packages('src'), include_package_data=True, headers=headers, ext_modules=ext_modules, classifiers=[ "Development Status :: 5 - Production/Stable", 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: C', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules' ], extras_require={ 'docs': [ 'Sphinx', # 0.18b1 breaks sphinx 1.8.5 which is the latest version that runs # on Python 2. The version pin sphinx itself contains isn't specific enough. 'docutils < 0.18; python_version < "3"', ], 'test': [ 'objgraph', 'faulthandler; python_version == "2.7" and platform_python_implementation == "CPython"', ], }, python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*", zip_safe=False, )
_find_impl_headers
visitor.rs
use std::borrow::Cow; use ast::{ Arguments, Definition, Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, InputValue, Operation, OperationType, Selection, Type, VariableDefinitions, }; use parser::Spanning; use schema::meta::Argument; use validation::{ValidatorContext, Visitor}; #[doc(hidden)] pub fn visit<'a, V: Visitor<'a>>(v: &mut V, ctx: &mut ValidatorContext<'a>, d: &'a Document) { v.enter_document(ctx, d); visit_definitions(v, ctx, d); v.exit_document(ctx, d); } fn visit_definitions<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, d: &'a Vec<Definition>, ) { for def in d { let def_type = match *def { Definition::Fragment(Spanning { item: Fragment { type_condition: Spanning { item: name, .. }, .. }, .. }) => Some(Type::NonNullNamed(Cow::Borrowed(name))), Definition::Operation(Spanning { item: Operation { operation_type: OperationType::Query, .. }, .. }) => Some(Type::NonNullNamed(Cow::Borrowed( ctx.schema.concrete_query_type().name().unwrap(), ))), Definition::Operation(Spanning { item: Operation { operation_type: OperationType::Mutation, .. }, .. }) => ctx.schema .concrete_mutation_type() .map(|t| Type::NonNullNamed(Cow::Borrowed(t.name().unwrap()))), }; ctx.with_pushed_type(def_type.as_ref(), |ctx| { enter_definition(v, ctx, def); visit_definition(v, ctx, def); exit_definition(v, ctx, def); }); } } fn enter_definition<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, def: &'a Definition, ) { match *def { Definition::Operation(ref op) => v.enter_operation_definition(ctx, op), Definition::Fragment(ref f) => v.enter_fragment_definition(ctx, f), } } fn exit_definition<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, def: &'a Definition, ) { match *def { Definition::Operation(ref op) => v.exit_operation_definition(ctx, op), Definition::Fragment(ref f) => v.exit_fragment_definition(ctx, f), } } fn visit_definition<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, def: &'a Definition, ) { match *def { Definition::Operation(ref op) => { visit_variable_definitions(v, ctx, &op.item.variable_definitions); visit_directives(v, ctx, &op.item.directives); visit_selection_set(v, ctx, &op.item.selection_set); } Definition::Fragment(ref f) => { visit_directives(v, ctx, &f.item.directives); visit_selection_set(v, ctx, &f.item.selection_set); } } } fn visit_variable_definitions<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, defs: &'a Option<Spanning<VariableDefinitions>>, ) { if let Some(ref defs) = *defs { for def in defs.item.iter() { let var_type = def.1.var_type.item.clone(); ctx.with_pushed_input_type(Some(&var_type), |ctx| { v.enter_variable_definition(ctx, def); if let Some(ref default_value) = def.1.default_value { visit_input_value(v, ctx, default_value); } v.exit_variable_definition(ctx, def); }) } } } fn visit_directives<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, directives: &'a Option<Vec<Spanning<Directive>>>, ) { if let Some(ref directives) = *directives { for directive in directives { let directive_arguments = ctx.schema .directive_by_name(directive.item.name.item) .map(|d| &d.arguments); v.enter_directive(ctx, directive); visit_arguments(v, ctx, &directive_arguments, &directive.item.arguments); v.exit_directive(ctx, directive); } } } fn visit_arguments<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, meta_args: &Option<&Vec<Argument<'a>>>, arguments: &'a Option<Spanning<Arguments>>, ) { if let Some(ref arguments) = *arguments { for argument in arguments.item.iter() { let arg_type = meta_args .and_then(|args| args.iter().find(|a| a.name == argument.0.item)) .map(|a| &a.arg_type); ctx.with_pushed_input_type(arg_type, |ctx| { v.enter_argument(ctx, argument); visit_input_value(v, ctx, &argument.1); v.exit_argument(ctx, argument); }) } } } fn visit_selection_set<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, selection_set: &'a Vec<Selection>, ) { ctx.with_pushed_parent_type(|ctx| { v.enter_selection_set(ctx, selection_set); for selection in selection_set.iter() { visit_selection(v, ctx, selection); } v.exit_selection_set(ctx, selection_set); }); } fn visit_selection<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, selection: &'a Selection, ) { match *selection { Selection::Field(ref field) => visit_field(v, ctx, field), Selection::FragmentSpread(ref spread) => visit_fragment_spread(v, ctx, spread), Selection::InlineFragment(ref fragment) => visit_inline_fragment(v, ctx, fragment), } } fn visit_field<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, field: &'a Spanning<Field>, ) { let meta_field = ctx.parent_type() .and_then(|t| t.field_by_name(field.item.name.item)); let field_type = meta_field.map(|f| &f.field_type); let field_args = meta_field.and_then(|f| f.arguments.as_ref()); ctx.with_pushed_type(field_type, |ctx| { v.enter_field(ctx, field); visit_arguments(v, ctx, &field_args, &field.item.arguments); visit_directives(v, ctx, &field.item.directives); if let Some(ref selection_set) = field.item.selection_set { visit_selection_set(v, ctx, selection_set); } v.exit_field(ctx, field); }); } fn visit_fragment_spread<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, spread: &'a Spanning<FragmentSpread>, ) { v.enter_fragment_spread(ctx, spread); visit_directives(v, ctx, &spread.item.directives); v.exit_fragment_spread(ctx, spread); } fn visit_inline_fragment<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, fragment: &'a Spanning<InlineFragment>, ) { let mut visit_fn = move |ctx: &mut ValidatorContext<'a>| { v.enter_inline_fragment(ctx, fragment); visit_directives(v, ctx, &fragment.item.directives); visit_selection_set(v, ctx, &fragment.item.selection_set); v.exit_inline_fragment(ctx, fragment); }; if let Some(Spanning { item: type_name, .. }) = fragment.item.type_condition { ctx.with_pushed_type( Some(&Type::NonNullNamed(Cow::Borrowed(type_name))), visit_fn, ); } else { visit_fn(ctx); } } fn visit_input_value<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, input_value: &'a Spanning<InputValue>, ) { enter_input_value(v, ctx, input_value); match input_value.item { InputValue::Object(ref fields) => for field in fields { let inner_type = ctx.current_input_type_literal() .and_then(|t| match *t { Type::NonNullNamed(ref name) | Type::Named(ref name) => { ctx.schema.concrete_type_by_name(name) } _ => None, }) .and_then(|ct| ct.input_field_by_name(&field.0.item)) .map(|f| &f.arg_type); ctx.with_pushed_input_type(inner_type, |ctx| { v.enter_object_field(ctx, field); visit_input_value(v, ctx, &field.1); v.exit_object_field(ctx, field); }) }, InputValue::List(ref ls) => { let inner_type = ctx.current_input_type_literal().and_then(|t| match *t { Type::List(ref inner) | Type::NonNullList(ref inner) => { Some(inner.as_ref().clone()) } _ => None, });
}) } _ => (), } exit_input_value(v, ctx, input_value); } fn enter_input_value<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, input_value: &'a Spanning<InputValue>, ) { use InputValue::*; let start = &input_value.start; let end = &input_value.end; match input_value.item { Null => v.enter_null_value(ctx, Spanning::start_end(start, end, ())), Int(ref i) => v.enter_int_value(ctx, Spanning::start_end(start, end, *i)), Float(ref f) => v.enter_float_value(ctx, Spanning::start_end(start, end, *f)), String(ref s) => v.enter_string_value(ctx, Spanning::start_end(start, end, s)), Boolean(ref b) => v.enter_boolean_value(ctx, Spanning::start_end(start, end, *b)), Enum(ref s) => v.enter_enum_value(ctx, Spanning::start_end(start, end, s)), Variable(ref s) => v.enter_variable_value(ctx, Spanning::start_end(start, end, s)), List(ref l) => v.enter_list_value(ctx, Spanning::start_end(start, end, l)), Object(ref o) => v.enter_object_value(ctx, Spanning::start_end(start, end, o)), } } fn exit_input_value<'a, V: Visitor<'a>>( v: &mut V, ctx: &mut ValidatorContext<'a>, input_value: &'a Spanning<InputValue>, ) { use InputValue::*; let start = &input_value.start; let end = &input_value.end; match input_value.item { Null => v.exit_null_value(ctx, Spanning::start_end(start, end, ())), Int(ref i) => v.exit_int_value(ctx, Spanning::start_end(start, end, *i)), Float(ref f) => v.exit_float_value(ctx, Spanning::start_end(start, end, *f)), String(ref s) => v.exit_string_value(ctx, Spanning::start_end(start, end, s)), Boolean(ref b) => v.exit_boolean_value(ctx, Spanning::start_end(start, end, *b)), Enum(ref s) => v.exit_enum_value(ctx, Spanning::start_end(start, end, s)), Variable(ref s) => v.exit_variable_value(ctx, Spanning::start_end(start, end, s)), List(ref l) => v.exit_list_value(ctx, Spanning::start_end(start, end, l)), Object(ref o) => v.exit_object_value(ctx, Spanning::start_end(start, end, o)), } }
ctx.with_pushed_input_type(inner_type.as_ref(), |ctx| { for value in ls { visit_input_value(v, ctx, value); }
ga_ie.go
package ga_ie import "github.com/wildptr/go-mc/chat" func
() { chat.SetLanguage(Map) } var Map = map[string]string{"addServer.add": "Déanta", "addServer.enterIp": "Seoladh an Fhreastalaí", "addServer.enterName": "Ainm an Fhreastalaí", "addServer.hideAddress": "Ceil Seoladh", "addServer.resourcePack": "Pacáistí Acmhainní an Fhreastalaí", "addServer.resourcePack.disabled": "Díchumasaithe", "addServer.resourcePack.enabled": "Cumasaithe", "addServer.resourcePack.prompt": "Fiafraigh", "addServer.title": "Athraigh Airíonna an Fhreastalaí", "advMode.allEntities": "Úsáid \"@e\" chun díriú ar gach aonán", "advMode.allPlayers": "Úsáid \"@a\" chun díriú ar gach imreoir", "advMode.command": "Ordú Consóil", "advMode.mode.auto": "Athfhillteach", "advMode.mode.autoexec.bat": "I bhfeidhm i gcónaí", "advMode.mode.conditional": "Coinníollach", "advMode.mode.redstone": "Truiceartha", "advMode.mode.redstoneTriggered": "Deargchloch Riachtanach", "advMode.mode.sequence": "Slabhrach", "advMode.mode.unconditional": "Gan choinníoll", "advMode.nearestPlayer": "Úsáid \"@p\" chun díriú ar imreoir is gaire", "advMode.notAllowed": "Is riachtanach bheith i d'oibreoir (op) i mód cruthaitheach", "advMode.notEnabled": "Níl bloic ordaithe i bhfeidhm ar an bhfreastalaí seo", "advMode.previousOutput": "Aschur Roimhe", "advMode.randomPlayer": "Úsáid \"@r\" chun díriú ar imreoir randamach", "advMode.self": "Úsáid \"@s\" don aonán forghniomhaithe a aimsiú", "advMode.setCommand": "Socraigh Ordú Consóil don Bhloc", "advMode.setCommand.success": "Ordú socraithe: %s", "advancement.advancementNotFound": "Forbairt anaithnid: %s", "advancements.adventure.adventuring_time.description": "Fionn gach bithóm", "advancements.adventure.adventuring_time.title": "Aimsir na nEachtraí", "advancements.adventure.arbalistic.description": "Maraigh cúig chréatúir ar leith le hurchar amháin ón gcrosbhogha", "advancements.adventure.arbalistic.title": "Nach bhfuil urchar den chéad scoth agat?", "advancements.adventure.hero_of_the_village.description": "Déan sráidbhaile a chosaint ó ruaig", "advancements.adventure.hero_of_the_village.title": "Laoch an tSráidbhaile", "advancements.adventure.kill_a_mob.description": "Maraigh arracht naimhdeach ar bith", "advancements.adventure.kill_a_mob.title": "Fiagaí Arrachtaí", "advancements.adventure.kill_all_mobs.description": "Maraigh ceann amháin de gach cineál arrachta naimhdigh", "advancements.adventure.kill_all_mobs.title": "Gan Trua", "advancements.adventure.ol_betsy.description": "Crosbhogha a scaoileadh", "advancements.adventure.ol_betsy.title": "A Shean-Bhetsy, is tú pór na gcrosbhoghannaí...", "advancements.adventure.root.description": "Eachtra, taiscéaladh agus troid", "advancements.adventure.root.title": "Eachtra", "advancements.adventure.shoot_arrow.description": "Scaoil rud éigin le bogha is saighead", "advancements.adventure.shoot_arrow.title": "Tóg d’Amas", "advancements.adventure.sleep_in_bed.description": "Athraigh d'áit athionchollaithe", "advancements.adventure.sleep_in_bed.title": "Codladh Sámh", "advancements.adventure.sniper_duel.description": "Maraigh Cnámharlach ó 50 méadar ar a laghad", "advancements.adventure.sniper_duel.title": "Coimhlint na Naoscairí", "advancements.adventure.summon_iron_golem.description": "Gair chugat Gólam Iarainn chun sráidbhaile a chosaint", "advancements.adventure.summon_iron_golem.title": "Giolla Beag", "advancements.adventure.throw_trident.description": "Caith trírinn chuig rud éigin.\nNóta: Ní dea-smaoineamh é an t-aon arm atá agat a ligean le sruth.", "advancements.adventure.throw_trident.title": "Greann le Sruth", "advancements.adventure.totem_of_undying.description": "Bain úsáid as Tótam na Síoraíochta chun cluain a chur ar an mbás", "advancements.adventure.totem_of_undying.title": "Iardhaonna", "advancements.adventure.trade.description": "Déan trádáil le Sráideánach", "advancements.adventure.trade.title": "Bíodh ina Mhargadh!", "advancements.adventure.two_birds_one_arrow.description": "Maraigh dhá Phúca le saighead polltach", "advancements.adventure.two_birds_one_arrow.title": "An Dá Churam a Dhéanamh in Éineacht", "advancements.adventure.very_very_frightening.description": "Buail Sráideánach le tintreach", "advancements.adventure.very_very_frightening.title": "Seoltóir Tintrí", "advancements.adventure.voluntary_exile.description": "Maraigh captaen ruaige. \nSeans gur fiú fanacht amach ó na sráidbhailte ar feadh tamaill...", "advancements.adventure.voluntary_exile.title": "Deoraí Deonach", "advancements.adventure.whos_the_pillager_now.description": "Tabhair tomhais a láimhe féin do Shreachadóir", "advancements.adventure.whos_the_pillager_now.title": "Nach tusa an Creachadóir anois?", "advancements.empty": "Tá cuma ar an scéal nach bhfuil rud ar bith anseo...", "advancements.end.dragon_breath.description": "Bailigh anáil an dragain i mbuidéal gloine", "advancements.end.dragon_breath.title": "Teastaíonn Mionta Uait", "advancements.end.dragon_egg.description": "Bíodh Ubh an Dragain i do lámh agat", "advancements.end.dragon_egg.title": "An Chéad Ghlúin Eile", "advancements.end.elytra.description": "Faigh na hEilitreaim", "advancements.end.elytra.title": "Go hArd na Spéire", "advancements.end.enter_end_gateway.description": "Éalaigh an t-oileán", "advancements.end.enter_end_gateway.title": "Saoire Iargúlta", "advancements.end.find_end_city.description": "Ar aghaidh leat isteach, céard a d’fhéadfadh tarlú?", "advancements.end.find_end_city.title": "An Chathair ag Críoch an Chluiche", "advancements.end.kill_dragon.description": "Go n-éirí an bóthar leat", "advancements.end.kill_dragon.title": "Fuascail an Chríoch", "advancements.end.levitate.description": "Eadarbhuasaigh suas 50 bloic ó ionsaithe Slíogadóra", "advancements.end.levitate.title": "Radharc Thar Barr", "advancements.end.respawn_dragon.description": "Athghin Dragan na Críche", "advancements.end.respawn_dragon.title": "An Chríoch... Arís...", "advancements.end.root.description": "Nó an tús?", "advancements.end.root.title": "An Chríoch", "advancements.husbandry.balanced_diet.description": "Ith gach rud inite, fiú na rudaí nach ndéanann aon mhaith duit", "advancements.husbandry.balanced_diet.title": "Réim Chothrom Bia", "advancements.husbandry.break_diamond_hoe.description": "Ídigh grafóg dhiamaint ina iomlán, agus ansin déan athbhreithniú ar do roghanna saoil", "advancements.husbandry.break_diamond_hoe.title": "Dúthracht Dhíograiseach", "advancements.husbandry.breed_all_animals.description": "Póraigh gach ainmhí!", "advancements.husbandry.breed_all_animals.title": "Ina gCúpla", "advancements.husbandry.breed_an_animal.description": "Póraigh dhá ainmhí le chéile", "advancements.husbandry.breed_an_animal.title": "Na Pearóidí agus na hIaltóga", "advancements.husbandry.complete_catalogue.description": "Déan peata de gach cineál cait!", "advancements.husbandry.complete_catalogue.title": "Catalóg Críochnaithe", "advancements.husbandry.fishy_business.description": "Beir ar iasc", "advancements.husbandry.fishy_business.title": "Úscra Iascra", "advancements.husbandry.plant_seed.description": "Cuir síol agus féach air ag fás", "advancements.husbandry.plant_seed.title": "Téigh Chun Síl", "advancements.husbandry.root.description": "Tá an domhan lán de chairde agus bia", "advancements.husbandry.root.title": "Fearachas", "advancements.husbandry.tactical_fishing.description": "Beir ar iasc... gan slat iascaigh!", "advancements.husbandry.tactical_fishing.title": "Iascaireacht Bheartach", "advancements.husbandry.tame_an_animal.description": "Ceansaigh ainmhí", "advancements.husbandry.tame_an_animal.title": "Dlúthchairde go deo", "advancements.nether.all_effects.description": "Gach éifeacht i bhfeidhm ort ag an am céanna", "advancements.nether.all_effects.title": "Conas a bhaineamar an áit seo amach?", "advancements.nether.all_potions.description": "Gach éifeacht posóide i bhfeidhm ort ag an am céanna", "advancements.nether.all_potions.title": "Manglam Marfach", "advancements.nether.brew_potion.description": "Grúdaigh posóid", "advancements.nether.brew_potion.title": "Grúdlann Áitiúil", "advancements.nether.create_beacon.description": "Tóg agus cuir síos Rabhcán", "advancements.nether.create_beacon.title": "Bíodh Sólás Ann", "advancements.nether.create_full_beacon.description": "Tabhair rabhcán chun a lánchumhacht", "advancements.nether.create_full_beacon.title": "Rabhcánóir", "advancements.nether.fast_travel.description": "Bain úsáid as an Íochtar chur turas 7 km a dhéanamh sa Bharrdhomhan", "advancements.nether.fast_travel.title": "Bolgán Fo-spáis", "advancements.nether.find_fortress.description": "Bris isteach i nDaingean san Íochtar", "advancements.nether.find_fortress.title": "Daingean an Uafáis", "advancements.nether.get_wither_skull.description": "Faigh cloigeann Chnámharlach Seargthóra", "advancements.nether.get_wither_skull.title": "Cnámharlach Cnagach Cradhscalach", "advancements.nether.obtain_blaze_rod.description": "Bain den Lasaire a slat", "advancements.nether.obtain_blaze_rod.title": "Isteach sa Tine", "advancements.nether.return_to_sender.description": "Scrios Uafaireach le caor thine", "advancements.nether.return_to_sender.title": "Cuir as ais don Seoltóir", "advancements.nether.root.description": "Bíodh éadaí samhraidh leat", "advancements.nether.root.title": "An tÍochtar", "advancements.nether.summon_wither.description": "Gair chugat an Seargthóir", "advancements.nether.summon_wither.title": "Is searg an fhírinne", "advancements.nether.uneasy_alliance.description": "Tarrtháil Uafaireach ón Íochtar, tabhair abhaile don Bharrdhomhan slán sábháilte é... agus ansin maraigh é", "advancements.nether.uneasy_alliance.title": "Comhaontas Míchompordach", "advancements.story.cure_zombie_villager.description": "Lagaigh agus leigheas Sráideánach Zombaí", "advancements.story.cure_zombie_villager.title": "Lia Zombaí", "advancements.story.deflect_arrow.description": "Sraon saighead le sciath", "advancements.story.deflect_arrow.title": "Maith thú, ach níl sé uaim", "advancements.story.enchant_item.description": "Cuir earra faoi dhraíocht ag Bord Asarlaíochta", "advancements.story.enchant_item.title": "Asarlaí", "advancements.story.enter_the_end.description": "Téigh isteach i dTairseach na Críche", "advancements.story.enter_the_end.title": "An Chríoch?", "advancements.story.enter_the_nether.description": "Tóg, las agus téigh isteach i dTairseach an Íochtair", "advancements.story.enter_the_nether.title": "Caithfimid Dul Níos Doimhne", "advancements.story.follow_ender_eye.description": "Lean Súil na Críche", "advancements.story.follow_ender_eye.title": "Caith do shúil thairis", "advancements.story.form_obsidian.description": "Cruthaigh agus tochail bloc Obsaidiain", "advancements.story.form_obsidian.title": "Dúshlán an Bhuicéid Oighir", "advancements.story.iron_tools.description": "Uasghradaigh do phiocóid", "advancements.story.iron_tools.title": "Nach bhfuil sé iarann-ta", "advancements.story.lava_bucket.description": "Líon buicéad lán le laibhe", "advancements.story.lava_bucket.title": "Stuifeanna Teo", "advancements.story.mine_diamond.description": "Faigh seilbh ar dhiamaint", "advancements.story.mine_diamond.title": "Diamaint!", "advancements.story.mine_stone.description": "Tochail cloch le do phiocóid nua", "advancements.story.mine_stone.title": "An Chlochaois", "advancements.story.obtain_armor.description": "Cosain túsa féin trí phíosa armúir iarainn", "advancements.story.obtain_armor.title": "Feistigh túsa féin", "advancements.story.root.description": "Croí agus scéal an chluiche", "advancements.story.root.title": "Minecraft", "advancements.story.shiny_gear.description": "Slánatheoir ollmhór é, armúr diamaint", "advancements.story.shiny_gear.title": "Clúdaigh mé le diamaint", "advancements.story.smelt_iron.description": "Bruithnigh uigne iarainn", "advancements.story.smelt_iron.title": "Faigh earraí", "advancements.story.upgrade_tools.description": "Cruthaigh piocóid níos fearr", "advancements.story.upgrade_tools.title": "Uasghradú a fháil", "advancements.toast.challenge": "Dúshlán Críochnaithe!", "advancements.toast.goal": "Sprioc Bainte Amach!", "advancements.toast.task": "Forbairt Bainte!", "argument.anchor.invalid": "Áit ancaire an aonáin neamhbhailí '%s'", "argument.block.id.invalid": "Cineál bloic anaithnid '%s'", "argument.block.property.duplicate": "Is féidir le hairí '%s' a chur ach uair amháin le haghaidh bloic %s", "argument.block.property.invalid": "Ní ghlacann bloc %s '%s' le haghaidh airí %s", "argument.block.property.novalue": "Coinne le luach la haghaidh airí '%s' ar an bloc '%s'", "argument.block.property.unclosed": "Ag súil le ] deireanach d‘airíonna stádas bloic", "argument.block.property.unknown": "Níl airí '%2s' ag an mbloc '%1s'", "argument.block.tag.disallowed": "Níl clibeanna ceadaithe anseo, fíorbhloic amháin", "argument.color.invalid": "Dath anaithnid '%s'", "argument.component.invalid": "Páirt comhrá neamhbhailí: %s", "argument.criteria.invalid": "Critéar anaithnid '%s'", "argument.dimension.invalid": "Toise anaithnid '%s'", "argument.double.big": "Ní mór le dúbailt a bheith níos mó ná %s, %s aimsithe", "argument.double.low": "Ní mór le dúbailt a bheith níos lú ná %s, %s aimsithe", "argument.entity.invalid": "Ainm neamhbhailí nó UUID", "argument.entity.notfound.entity": "Aonán ar bith aimsithe", "argument.entity.notfound.player": "Imreoir ar bith aimsithe", "argument.entity.options.advancements.description": "Imreoirí forbartha", "argument.entity.options.distance.description": "Fad go haonán", "argument.entity.options.distance.negative": "Ní féidir le faid a bheith diúltacha", "argument.entity.options.dx.description": "Aonáin idir x agus x + dx", "argument.entity.options.dy.description": "Aonáin idir y agus y + dy", "argument.entity.options.dz.description": "Aonáin idir z agus z + dz", "argument.entity.options.gamemode.description": "Imreoirí leis an mód cluiche", "argument.entity.options.inapplicable": "Níl rogha '%s' infheidhme anseo", "argument.entity.options.level.description": "Leibhéal taithí", "argument.entity.options.level.negative": "Ní cheart le leibhéil a bheith diúltacha", "argument.entity.options.limit.description": "Uasuimhir na n-aonán atá ag filleadh", "argument.entity.options.limit.toosmall": "Ní mór leis an dteorainn a bheith 1 ar a laghad", "argument.entity.options.mode.invalid": "Mód cluiche neamhbhailí nó anaithnid '%s'", "argument.entity.options.name.description": "Ainm aonáin", "argument.entity.options.nbt.description": "Aonáin le NBT", "argument.entity.options.scores.description": "Aonáin le scóir", "argument.entity.options.sort.description": "Sórtáil na haonáin", "argument.entity.options.sort.irreversible": "Cineál sórtála neamhbhailí nó anaithnid '%s'", "argument.entity.options.tag.description": "Aonáin le clib", "argument.entity.options.team.description": "Aonáin ar fhoireann", "argument.entity.options.type.description": "Aonáin de chineál", "argument.entity.options.type.invalid": "Cineál aonáin neamhbhailí nó anaithnid '%s'", "argument.entity.options.unknown": "Rogha anaithnid '%s'", "argument.entity.options.unterminated": "Deireadh roghanna le coinne", "argument.entity.options.valueless": "Coinne le luach le haghaidh rogha '%s'", "argument.entity.options.x.description": "ionad x", "argument.entity.options.x_rotation.description": "Rothlúchán x an aonáin", "argument.entity.options.y.description": "ionad y", "argument.entity.options.y_rotation.description": "Rothlúchán y an aonáin", "argument.entity.options.z.description": "ionad z", "argument.entity.selector.allEntities": "Aonáin uile", "argument.entity.selector.allPlayers": "Imreoirí uile", "argument.entity.selector.missing": "Sórt roghnóra in easnamh", "argument.entity.selector.nearestPlayer": "An t-imreoir is gaire", "argument.entity.selector.not_allowed": "Roghnóir neamhcheadaithe", "argument.entity.selector.randomPlayer": "Imreoir gan choinne", "argument.entity.selector.self": "Aonán reatha", "argument.entity.selector.unknown": "Cineál roghnóra anaithnid '%s'", "argument.entity.toomany": "Ach aonán amháin ceadaithe, ach ceadaíonn an roghnóir soláthraithe níos mó ná haon amháin", "argument.float.big": "Ní mór le teagmhas a bheith níos mó ná %s, %s aimsithe", "argument.float.low": "Ní mór le teagmhas a bheith níos lú ná %s, %s aimsithe", "argument.id.invalid": "ID neamhbhailí", "argument.id.unknown": "ID anaithnid: %s", "argument.integer.big": "Ní mór le slánuimhir a bheith níos mó ná %s, %s aimsithe", "argument.integer.low": "Ní mór le slánuimhir a bheith níos lú ná %s, %s aimsithe", "argument.item.id.invalid": "Earraí anaithnid '%s'", "argument.item.tag.disallowed": "Níl clibeanna ceadaithe anseo, fíorearraithe amháin", "argument.literal.incorrect": "Coinne le hoibreann litriúil %s", "argument.long.big": "Ní mór le fad a bheith níos mó ná %s, %s aimsithe", "argument.long.low": "Ní mór le fad a bheith níos lú ná %s, %s aimsithe", "argument.nbt.array.invalid": "Cineál eagair neamhbhailí '%s'", "argument.nbt.array.mixed": "Ní féidir le %s a chur isteach i %s", "argument.nbt.expected.key": "Clé le coinne", "argument.nbt.expected.value": "Luach le coinne", "argument.nbt.list.mixed": "Ní féidir le %s a chur isteach i liosta %s", "argument.nbt.trailing": "Sonraí sraoilleach gan choinne", "argument.player.entities": "Féadfar le himreoirí amháin a bhaineann leis an t-ordú seo, ach cuimsíonn an roghnóir soláthraithe aonáin ina measc", "argument.player.toomany": "Ach imreoir amháin ceadaithe, ach ceadaíonn an roghnóir soláthraithe níos mó ná haon amháin", "argument.player.unknown": "Níl an t-imreoir sin ann", "argument.pos.missing.double": "Coinne le comhordanáid", "argument.pos.missing.int": "Coinne le hionad bloic", "argument.pos.mixed": "Ní féidir le comhordanáidí áitiúla & den domhan a mheascadh (ní mór ag gach rud ^ a úsáid nó ná húsáid é)", "argument.pos.outofworld": "Tá an t-ionad sin as an ndomhan seo!", "argument.pos.unloaded": "Níl an t-ionad sin lódáilte", "argument.pos2d.incomplete": "Easnamhach (coinne le dhá chomordanáid)", "argument.pos3d.incomplete": "Easnamhach (coinne le 3 chomhordanáid)", "argument.range.empty": "Bhí coinne le luach nó raon luachanna", "argument.range.ints": "Ach slánuimhir amháin ceadaithe, gan deachúil", "argument.range.swapped": "Ní féidir le íosmhéid níos mó ná an uasmhéid a fháil", "argument.rotation.incomplete": "Easnamhach (coinne le dhá chomhordanáid)", "argument.scoreHolder.empty": "Scóirshealbhóir ábhartha ar bith aimsithe", "argument.scoreboardDisplaySlot.invalid": "Sliotán taispeána anaithnid '%s'", "argument.time.invalid_tick_count": "Ná bíodh áireamh na dticeanna ina uimhir dhiúltach", "argument.time.invalid_unit": "Miosúr mícheart", "arguments.block.tag.unknown": "Clib bloic anaithnid '%s'", "arguments.function.tag.unknown": "Clib feidhme anaithnid '%s'", "arguments.function.unknown": "Feidhm anaithnid %s", "arguments.item.overstacked": "Is féidir le %s ach cruach a dhéanamh go dtí %s", "arguments.item.tag.unknown": "Clib earraí anaithnid '%s'", "arguments.nbtpath.node.invalid": "Gné bealaigh NBT neamhbhailí", "arguments.nbtpath.nothing_found": "Ní bhfuarthas éard is ionann le %s", "arguments.objective.notFound": "Aidhm scórchláir anaithnid '%s'", "arguments.objective.readonly": "Is léamh-amháin é an aidhm scórchláir '%s'", "arguments.operation.div0": "Ní féidir le roinnt a dhéanamh le náid", "arguments.operation.invalid": "Oibreoir neamhbhailí", "arguments.swizzle.invalid": "Meascán neamhbhailí, coinne le meascán 'x', 'y' agus 'z'", "attribute.modifier.equals.0": "%s %s", "attribute.modifier.equals.1": "%s%% %s", "attribute.modifier.equals.2": "%s%% %s", "attribute.modifier.plus.0": "+%s %s", "attribute.modifier.plus.1": "+%s%% %s", "attribute.modifier.plus.2": "+%s%% %s", "attribute.modifier.take.0": "-%s %s", "attribute.modifier.take.1": "-%s%% %s", "attribute.modifier.take.2": "-%s%% %s", "attribute.name.generic.armor": "Cathéide", "attribute.name.generic.armorToughness": "Righneas Cathéide", "attribute.name.generic.attackDamage": "Damáiste Ionsaithe", "attribute.name.generic.attackSpeed": "Luas Ionsaithe", "attribute.name.generic.followRange": "Raon Braite na gCréatúr", "attribute.name.generic.knockbackResistance": "Seasmhacht in aghaidh Cnag Siar", "attribute.name.generic.luck": "Ádh", "attribute.name.generic.maxHealth": "Uasmhéid Sláinte", "attribute.name.generic.movementSpeed": "Luas", "attribute.name.horse.jumpStrength": "Neart Léim an Chapaill", "attribute.name.zombie.spawnReinforcements": "Zombaithe Athneartacha", "biome.minecraft.badlands": "Drochailte", "biome.minecraft.badlands_plateau": "Ardchlár na nDrochailte", "biome.minecraft.bamboo_jungle": "Dufair Bhambú", "biome.minecraft.bamboo_jungle_hills": "Cnoic Dhufaire Bambú", "biome.minecraft.beach": "Trá", "biome.minecraft.birch_forest": "Forais Beithe", "biome.minecraft.birch_forest_hills": "Cnoic Foraoise Beithe", "biome.minecraft.cold_ocean": "Muir Fhuar", "biome.minecraft.dark_forest": "Dubhfhoraois", "biome.minecraft.dark_forest_hills": "Cnoic Dubhfhoraoise", "biome.minecraft.deep_cold_ocean": "Muir Fhuar Domhain", "biome.minecraft.deep_frozen_ocean": "Muir Reoite Domhain", "biome.minecraft.deep_lukewarm_ocean": "Muir Bhogthe Domhain", "biome.minecraft.deep_ocean": "Muir Domhain", "biome.minecraft.deep_warm_ocean": "Muir The Domhain", "biome.minecraft.desert": "Fásach", "biome.minecraft.desert_hills": "Cnoic Fásacha", "biome.minecraft.desert_lakes": "Lochanna Fásacha", "biome.minecraft.end_barrens": "Deireadh Talún Sheasc", "biome.minecraft.end_highlands": "Deireadh na nArdchríocha", "biome.minecraft.end_midlands": "Deireadh na Láirtíortha", "biome.minecraft.eroded_badlands": "Drochailte Creimthe", "biome.minecraft.flower_forest": "Foraois na mBláthanna", "biome.minecraft.forest": "Foraois", "biome.minecraft.frozen_ocean": "Muir Reoite", "biome.minecraft.frozen_river": "Abhainn Reoite", "biome.minecraft.giant_spruce_taiga": "Táigeá Sprúis Ollmhóir", "biome.minecraft.giant_spruce_taiga_hills": "Cnoic Táigeá Sprúis Ollmhóir", "biome.minecraft.giant_tree_taiga": "Táigeá Crainn Ollmhóir", "biome.minecraft.giant_tree_taiga_hills": "Cnoic Táigeá Crainn Ollmhóir", "biome.minecraft.gravelly_mountains": "Sléibhte Gairbhéil", "biome.minecraft.ice_spikes": "Spící Oighir", "biome.minecraft.jungle": "Dufair", "biome.minecraft.jungle_edge": "Teorainn na Dufaire", "biome.minecraft.jungle_hills": "Cnoic Dufaire", "biome.minecraft.lukewarm_ocean": "Muir Bhogthe", "biome.minecraft.modified_badlands_plateau": "Ardchlár na nDrochailte Mhionathraithe", "biome.minecraft.modified_gravelly_mountains": "Sléibhte Gairbhéil+", "biome.minecraft.modified_jungle": "Dufair Mhionathraithe", "biome.minecraft.modified_jungle_edge": "Teorainn na Dufaire Mionathraithe", "biome.minecraft.modified_wooded_badlands_plateau": "Ardchlár Mionathraithe na Drochailte Choillteacha", "biome.minecraft.mountain_edge": "Teorainn na Sléibhte", "biome.minecraft.mountains": "Sléibhte", "biome.minecraft.mushroom_field_shore": "Cladach an Ghoirt Muisiriún", "biome.minecraft.mushroom_fields": "Goirt Muisiriún", "biome.minecraft.nether": "An tÍochtar", "biome.minecraft.ocean": "Muir", "biome.minecraft.plains": "Mánna", "biome.minecraft.river": "Abhainn", "biome.minecraft.savanna": "Sabhána", "biome.minecraft.savanna_plateau": "Ardchlár an tSabhána", "biome.minecraft.shattered_savanna": "Sabhána Réabtha", "biome.minecraft.shattered_savanna_plateau": "Ardchlár an tSabhána Réabtha", "biome.minecraft.small_end_islands": "Deireadh na nOileán Beaga", "biome.minecraft.snowy_beach": "Trá Sneachtúil", "biome.minecraft.snowy_mountains": "Sléibhte Sneachtúla", "biome.minecraft.snowy_taiga": "Táigeá Sneachtúil", "biome.minecraft.snowy_taiga_hills": "Cnoic Táigeá Sneachtúla", "biome.minecraft.snowy_taiga_mountains": "Sléibhte Táigeá Sneachtúil", "biome.minecraft.snowy_tundra": "Tundra Sneachtúil", "biome.minecraft.stone_shore": "Cladach Cloiche", "biome.minecraft.sunflower_plains": "Mánna Lusanna na Gréine", "biome.minecraft.swamp": "Corcach", "biome.minecraft.swamp_hills": "Cnoic Corcaí", "biome.minecraft.taiga": "Táigeá", "biome.minecraft.taiga_hills": "Cnoic Táigeá", "biome.minecraft.taiga_mountains": "Sléibhte Táigeá", "biome.minecraft.tall_birch_forest": "Foraois Ardbheithe", "biome.minecraft.tall_birch_hills": "Cnoic Ardbheithe", "biome.minecraft.the_end": "An Chríoch", "biome.minecraft.the_void": "An Folús", "biome.minecraft.warm_ocean": "Muir The", "biome.minecraft.wooded_badlands_plateau": "Ardchlár Coillteach na nDrochailte", "biome.minecraft.wooded_hills": "Cnoic Coillteacha", "biome.minecraft.wooded_mountains": "Sléibhte Coillteacha", "block.minecraft.acacia_button": "Cnaipe Acaicia", "block.minecraft.acacia_door": "Doras Acaicia", "block.minecraft.acacia_fence": "Claí Acaicia", "block.minecraft.acacia_fence_gate": "Géata Acaicia", "block.minecraft.acacia_leaves": "Duilleoga Acaicia", "block.minecraft.acacia_log": "Lomán Acaicia", "block.minecraft.acacia_planks": "Clár Acaicia", "block.minecraft.acacia_pressure_plate": "Brúphláta Acaicia", "block.minecraft.acacia_sapling": "Acaicia Óg", "block.minecraft.acacia_sign": "Comhartha Acáise", "block.minecraft.acacia_slab": "Leac Acaicia", "block.minecraft.acacia_stairs": "Staighre Acaicia", "block.minecraft.acacia_trapdoor": "Comhla Thógála Acaicia", "block.minecraft.acacia_wall_sign": "Comhartha Balla Acacia", "block.minecraft.acacia_wood": "Adhmad Acaicia", "block.minecraft.activator_rail": "Ráillí Gníomhachtóra", "block.minecraft.air": "Aer", "block.minecraft.allium": "Allium", "block.minecraft.andesite": "Aindéisít", "block.minecraft.andesite_slab": "Leac Aindéisíte", "block.minecraft.andesite_stairs": "Staighre Aindéisíte", "block.minecraft.andesite_wall": "Balla Aindéisíte", "block.minecraft.anvil": "Inneoin", "block.minecraft.attached_melon_stem": "Gas Mealbhacán Ceangailte", "block.minecraft.attached_pumpkin_stem": "Gas Puimcín Ceangailte", "block.minecraft.azure_bluet": "Goirmín Spéiriúil", "block.minecraft.bamboo": "Bambú", "block.minecraft.bamboo_sapling": "Buinneán Bambú", "block.minecraft.banner": "Bratach", "block.minecraft.banner.border.black": "Imeallbhord Dubh", "block.minecraft.banner.border.blue": "Imeallbhord Gorm", "block.minecraft.banner.border.brown": "Imeallbhord Donn", "block.minecraft.banner.border.cyan": "Imeallbhord Cian", "block.minecraft.banner.border.gray": "Imeallbhord Liath", "block.minecraft.banner.border.green": "Imeallbhord Uaine", "block.minecraft.banner.border.light_blue": "Imeallbhord Bánghorm", "block.minecraft.banner.border.light_gray": "Imeallbhord Fionnliath", "block.minecraft.banner.border.lime": "Imeallbhord Líomach", "block.minecraft.banner.border.magenta": "Imeallbhord Maigeanta", "block.minecraft.banner.border.orange": "Imeallbhord Oráisteach", "block.minecraft.banner.border.pink": "Imeallbhord Bándearg", "block.minecraft.banner.border.purple": "Imeallbhord Corcra", "block.minecraft.banner.border.red": "Imeallbhord Dearg", "block.minecraft.banner.border.white": "Imeallbhord Bán", "block.minecraft.banner.border.yellow": "Imeallbhord Buí", "block.minecraft.banner.bricks.black": "Machaire Saoirsithe Dubh", "block.minecraft.banner.bricks.blue": "Machaire Saoirsithe Gorm", "block.minecraft.banner.bricks.brown": "Machaire Saoirsithe Donn", "block.minecraft.banner.bricks.cyan": "Machaire Saoirsithe Cian", "block.minecraft.banner.bricks.gray": "Machaire Saoirsithe Liath", "block.minecraft.banner.bricks.green": "Machaire Saoirsithe Uaine", "block.minecraft.banner.bricks.light_blue": "Machaire Saoirsithe Bánghorm", "block.minecraft.banner.bricks.light_gray": "Machaire Saoirsithe Fionnliath", "block.minecraft.banner.bricks.lime": "Machaire Saoirsithe Líomach", "block.minecraft.banner.bricks.magenta": "Machaire Saoirsithe Maigeanta", "block.minecraft.banner.bricks.orange": "Machaire Saoirsithe Oráisteach", "block.minecraft.banner.bricks.pink": "Machaire Saoirsithe Bándearg", "block.minecraft.banner.bricks.purple": "Machaire Saoirsithe Corcra", "block.minecraft.banner.bricks.red": "Machaire Saoirsithe Dearg", "block.minecraft.banner.bricks.white": "Machaire Saoirsithe Bán", "block.minecraft.banner.bricks.yellow": "Machaire Saoirsithe Buí", "block.minecraft.banner.circle.black": "Cruinneán Dubh", "block.minecraft.banner.circle.blue": "Cruinneán Gorm", "block.minecraft.banner.circle.brown": "Cruinneán Donn", "block.minecraft.banner.circle.cyan": "Cruinneán Cian", "block.minecraft.banner.circle.gray": "Cruinneán Liath", "block.minecraft.banner.circle.green": "Cruinneán Uaine", "block.minecraft.banner.circle.light_blue": "Cruinneán Bánghorm", "block.minecraft.banner.circle.light_gray": "Cruinneán Fionnliath", "block.minecraft.banner.circle.lime": "Cruinneán Líomach", "block.minecraft.banner.circle.magenta": "Cruinneán Maigeanta", "block.minecraft.banner.circle.orange": "Cruinneán Oráisteach", "block.minecraft.banner.circle.pink": "Cruinneán Bándearg", "block.minecraft.banner.circle.purple": "Cruinneán Corcra", "block.minecraft.banner.circle.red": "Cruinneán Dearg", "block.minecraft.banner.circle.white": "Cruinneán Bán", "block.minecraft.banner.circle.yellow": "Cruinneán Buí", "block.minecraft.banner.creeper.black": "Fíor Creeper Dhuibh", "block.minecraft.banner.creeper.blue": "Fíor Creeper Ghoirm", "block.minecraft.banner.creeper.brown": "Fíor Creeper Dhoinn", "block.minecraft.banner.creeper.cyan": "Fíor Creeper Chian", "block.minecraft.banner.creeper.gray": "Fíor Creeper Léith", "block.minecraft.banner.creeper.green": "Fíor Creeper Ghlais", "block.minecraft.banner.creeper.light_blue": "Fíor Creeper Bhánghoirm", "block.minecraft.banner.creeper.light_gray": "Fíor Creeper Bhánléith", "block.minecraft.banner.creeper.lime": "Fíor Creeper Fionnghlais", "block.minecraft.banner.creeper.magenta": "Fíor Creeper Mhaigeanta", "block.minecraft.banner.creeper.orange": "Fíor Creeper Oráistigh", "block.minecraft.banner.creeper.pink": "Fíor Creeper Bhándeirg", "block.minecraft.banner.creeper.purple": "Fíor Creeper Chorcra", "block.minecraft.banner.creeper.red": "Fíor Creeper Dheirg", "block.minecraft.banner.creeper.white": "Fíor Creeper Bháin", "block.minecraft.banner.creeper.yellow": "Fíor Creeper Bhuí", "block.minecraft.banner.cross.black": "Sailtír Dhubh", "block.minecraft.banner.cross.blue": "Sailtír Ghorm", "block.minecraft.banner.cross.brown": "Sailtír Dhonn", "block.minecraft.banner.cross.cyan": "Sailtír Chian", "block.minecraft.banner.cross.gray": "Sailtír Liath", "block.minecraft.banner.cross.green": "Sailtír Uaine", "block.minecraft.banner.cross.light_blue": "Sailtír Bhánghorm", "block.minecraft.banner.cross.light_gray": "Sailtír Fhionnliath", "block.minecraft.banner.cross.lime": "Sailtír Líomach", "block.minecraft.banner.cross.magenta": "Sailtír Mhaigeanta", "block.minecraft.banner.cross.orange": "Sailtír Oráisteach", "block.minecraft.banner.cross.pink": "Sailtír Bhándearg", "block.minecraft.banner.cross.purple": "Sailtír Chorcra", "block.minecraft.banner.cross.red": "Sailtír Dhearg", "block.minecraft.banner.cross.white": "Sailtír Bhán", "block.minecraft.banner.cross.yellow": "Sailtír Bhuí", "block.minecraft.banner.curly_border.black": "Imeallbhord Eangach Dubh", "block.minecraft.banner.curly_border.blue": "Imeallbhord Eangach Gorm", "block.minecraft.banner.curly_border.brown": "Imeallbhord Eangach Donn", "block.minecraft.banner.curly_border.cyan": "Imeallbhord Eangach Cian", "block.minecraft.banner.curly_border.gray": "Imeallbhord Eangach Liath", "block.minecraft.banner.curly_border.green": "Imeallbhord Eangach Uaine", "block.minecraft.banner.curly_border.light_blue": "Imeallbhord Eangach Bánghorm", "block.minecraft.banner.curly_border.light_gray": "Imeallbhord Eangach Fionnliath", "block.minecraft.banner.curly_border.lime": "Imeallbhord Eangach Líomach", "block.minecraft.banner.curly_border.magenta": "Imeallbhord Eangach Maigeanta", "block.minecraft.banner.curly_border.orange": "Imeallbhord Eangach Oráisteach", "block.minecraft.banner.curly_border.pink": "Imeallbhord Eangach Bándearg", "block.minecraft.banner.curly_border.purple": "Imeallbhord Eangach Corcra", "block.minecraft.banner.curly_border.red": "Imeallbhord Eangach Dearg", "block.minecraft.banner.curly_border.white": "Imeallbhord Eangach Bán", "block.minecraft.banner.curly_border.yellow": "Imeallbhord Eangach Buí", "block.minecraft.banner.diagonal_left.black": "Cléroinnte Dubh", "block.minecraft.banner.diagonal_left.blue": "Cléroinnte Gorm", "block.minecraft.banner.diagonal_left.brown": "Cléroinnte Donn", "block.minecraft.banner.diagonal_left.cyan": "Cléroinnte Cian", "block.minecraft.banner.diagonal_left.gray": "Cléroinnte Liath", "block.minecraft.banner.diagonal_left.green": "Cléroinnte Uaine", "block.minecraft.banner.diagonal_left.light_blue": "Cléroinnte Bánghorm", "block.minecraft.banner.diagonal_left.light_gray": "Cléroinnte Fionnliath", "block.minecraft.banner.diagonal_left.lime": "Cléroinnte Líomach", "block.minecraft.banner.diagonal_left.magenta": "Cléroinnte Maigeanta", "block.minecraft.banner.diagonal_left.orange": "Cléroinnte Oráisteach", "block.minecraft.banner.diagonal_left.pink": "Cléroinnte Bándearg", "block.minecraft.banner.diagonal_left.purple": "Cléroinnte Corcra", "block.minecraft.banner.diagonal_left.red": "Cléroinnte Dearg", "block.minecraft.banner.diagonal_left.white": "Cléroinnte Bán", "block.minecraft.banner.diagonal_left.yellow": "Cléroinnte Buí", "block.minecraft.banner.diagonal_right.black": "Criosroinnte Dubh", "block.minecraft.banner.diagonal_right.blue": "Criosroinnte Gorm", "block.minecraft.banner.diagonal_right.brown": "Criosroinnte Donn", "block.minecraft.banner.diagonal_right.cyan": "Criosroinnte Cian", "block.minecraft.banner.diagonal_right.gray": "Criosroinnte Liath", "block.minecraft.banner.diagonal_right.green": "Criosroinnte Uaine", "block.minecraft.banner.diagonal_right.light_blue": "Criosroinnte Bánghorm", "block.minecraft.banner.diagonal_right.light_gray": "Criosroinnte Fionnliath", "block.minecraft.banner.diagonal_right.lime": "Criosroinnte Líomach", "block.minecraft.banner.diagonal_right.magenta": "Criosroinnte Maigeanta", "block.minecraft.banner.diagonal_right.orange": "Criosroinnte Oráisteach", "block.minecraft.banner.diagonal_right.pink": "Criosroinnte Bándearg", "block.minecraft.banner.diagonal_right.purple": "Criosroinnte Corcra", "block.minecraft.banner.diagonal_right.red": "Criosroinnte Dearg", "block.minecraft.banner.diagonal_right.white": "Criosroinnte Bán", "block.minecraft.banner.diagonal_right.yellow": "Criosroinnte Buí", "block.minecraft.banner.diagonal_up_left.black": "Criosroinnte Bunoscionn Dubh", "block.minecraft.banner.diagonal_up_left.blue": "Criosroinnte Bunoscionn Gorm", "block.minecraft.banner.diagonal_up_left.brown": "Criosroinnte Bunoscionn Donn", "block.minecraft.banner.diagonal_up_left.cyan": "Criosroinnte Bunoscionn Cian", "block.minecraft.banner.diagonal_up_left.gray": "Criosroinnte Bunoscionn Liath", "block.minecraft.banner.diagonal_up_left.green": "Criosroinnte Bunoscionn Uaine", "block.minecraft.banner.diagonal_up_left.light_blue": "Criosroinnte Bunoscionn Bánghorm", "block.minecraft.banner.diagonal_up_left.light_gray": "Criosroinnte Bunoscionn Fionnliath", "block.minecraft.banner.diagonal_up_left.lime": "Criosroinnte Bunoscionn Líomach", "block.minecraft.banner.diagonal_up_left.magenta": "Criosroinnte Bunoscionn Maigeanta", "block.minecraft.banner.diagonal_up_left.orange": "Criosroinnte Bunoscionn Oráisteach", "block.minecraft.banner.diagonal_up_left.pink": "Criosroinnte Bunoscionn Bándearg", "block.minecraft.banner.diagonal_up_left.purple": "Criosroinnte Bunoscionn Corcra", "block.minecraft.banner.diagonal_up_left.red": "Criosroinnte Bunoscionn Dearg", "block.minecraft.banner.diagonal_up_left.white": "Criosroinnte Bunoscionn Bán", "block.minecraft.banner.diagonal_up_left.yellow": "Criosroinnte Bunoscionn Buí", "block.minecraft.banner.diagonal_up_right.black": "Cléroinnte Bunoscionn Dubh", "block.minecraft.banner.diagonal_up_right.blue": "Cléroinnte Bunoscionn Gorm", "block.minecraft.banner.diagonal_up_right.brown": "Cléroinnte Bunoscionn Donn", "block.minecraft.banner.diagonal_up_right.cyan": "Cléroinnte Bunoscionn Cian", "block.minecraft.banner.diagonal_up_right.gray": "Cléroinnte Bunoscionn Liath", "block.minecraft.banner.diagonal_up_right.green": "Cléroinnte Bunoscionn Uaine", "block.minecraft.banner.diagonal_up_right.light_blue": "Cléroinnte Bunoscionn Bánghorm", "block.minecraft.banner.diagonal_up_right.light_gray": "Cléroinnte Bunoscionn Fionnliath", "block.minecraft.banner.diagonal_up_right.lime": "Cléroinnte Bunoscionn Líomach", "block.minecraft.banner.diagonal_up_right.magenta": "Cléroinnte Bunoscionn Maigeanta", "block.minecraft.banner.diagonal_up_right.orange": "Cléroinnte Bunoscionn Oráisteach", "block.minecraft.banner.diagonal_up_right.pink": "Cléroinnte Bunoscionn Bándearg", "block.minecraft.banner.diagonal_up_right.purple": "Cléroinnte Bunoscionn Corcra", "block.minecraft.banner.diagonal_up_right.red": "Cléroinnte Bunoscionn Dearg", "block.minecraft.banner.diagonal_up_right.white": "Cléroinnte Bunoscionn Bán", "block.minecraft.banner.diagonal_up_right.yellow": "Cléroinnte Bunoscionn Buí", "block.minecraft.banner.flower.black": "Fíor Blátha Dubh", "block.minecraft.banner.flower.blue": "Fíor Blátha Gorm", "block.minecraft.banner.flower.brown": "Fíor Blátha Donn", "block.minecraft.banner.flower.cyan": "Fíor Blátha Cian", "block.minecraft.banner.flower.gray": "Fíor Blátha Liath", "block.minecraft.banner.flower.green": "Fíor Blátha Uaine", "block.minecraft.banner.flower.light_blue": "Fíor Blátha Bánghorm", "block.minecraft.banner.flower.light_gray": "Fíor Blátha Fionnliath", "block.minecraft.banner.flower.lime": "Fíor Blátha Líomach", "block.minecraft.banner.flower.magenta": "Fíor Blátha Maigeanta", "block.minecraft.banner.flower.orange": "Fíor Blátha Oráisteach", "block.minecraft.banner.flower.pink": "Fíor Blátha Bándearg", "block.minecraft.banner.flower.purple": "Fíor Blátha Corcra", "block.minecraft.banner.flower.red": "Fíor Blátha Dearg", "block.minecraft.banner.flower.white": "Fíor Blátha Bán", "block.minecraft.banner.flower.yellow": "Fíor Blátha Buí", "block.minecraft.banner.globe.black": "Dubh Globe", "block.minecraft.banner.globe.blue": "Gorm Globe", "block.minecraft.banner.globe.brown": "Brown Globe", "block.minecraft.banner.globe.cyan": "Ciain Globe", "block.minecraft.banner.globe.gray": "Grey Globe", "block.minecraft.banner.globe.green": "Glas Globe", "block.minecraft.banner.globe.light_blue": "Gorm Gorm Globe", "block.minecraft.banner.globe.light_gray": "Solas Liath Globe", "block.minecraft.banner.globe.lime": "Aol Globe", "block.minecraft.banner.globe.magenta": "Magenta Globe", "block.minecraft.banner.globe.orange": "Oráiste Globe", "block.minecraft.banner.globe.pink": "Bándearg Globe", "block.minecraft.banner.globe.purple": "Corcra Globe", "block.minecraft.banner.globe.red": "Dearg Globe", "block.minecraft.banner.globe.white": "Bán Globe", "block.minecraft.banner.globe.yellow": "Buí Globe", "block.minecraft.banner.gradient.black": "Grádán Dubh", "block.minecraft.banner.gradient.blue": "Grádán Gorm", "block.minecraft.banner.gradient.brown": "Grádán Donn", "block.minecraft.banner.gradient.cyan": "Grádán Cian", "block.minecraft.banner.gradient.gray": "Grádán Liath", "block.minecraft.banner.gradient.green": "Grádán Uaine", "block.minecraft.banner.gradient.light_blue": "Grádán Bánghorm", "block.minecraft.banner.gradient.light_gray": "Grádán Fionnliath", "block.minecraft.banner.gradient.lime": "Grádán Líomach", "block.minecraft.banner.gradient.magenta": "Grádán Maigeanta", "block.minecraft.banner.gradient.orange": "Grádán Oráisteach", "block.minecraft.banner.gradient.pink": "Grádán Bándearg", "block.minecraft.banner.gradient.purple": "Grádán Corcra", "block.minecraft.banner.gradient.red": "Grádán Dearg", "block.minecraft.banner.gradient.white": "Grádán Bán", "block.minecraft.banner.gradient.yellow": "Grádán Buí", "block.minecraft.banner.gradient_up.black": "Grádán Dubh ó Bhun", "block.minecraft.banner.gradient_up.blue": "Grádán Gorm ó Bhun", "block.minecraft.banner.gradient_up.brown": "Grádán Donn ó Bhun", "block.minecraft.banner.gradient_up.cyan": "Grádán Cian ó Bhun", "block.minecraft.banner.gradient_up.gray": "Grádán Liath ó Bhun", "block.minecraft.banner.gradient_up.green": "Grádán Uaine ó Bhun", "block.minecraft.banner.gradient_up.light_blue": "Grádán Bánghorm ó Bhun", "block.minecraft.banner.gradient_up.light_gray": "Grádán Fionnliath ó Bhun", "block.minecraft.banner.gradient_up.lime": "Grádán Líomach ó Bhun", "block.minecraft.banner.gradient_up.magenta": "Grádán Maigeanta ó Bhun", "block.minecraft.banner.gradient_up.orange": "Grádán Oráisteach ó Bhun", "block.minecraft.banner.gradient_up.pink": "Grádán Bándearg ó Bhun", "block.minecraft.banner.gradient_up.purple": "Grádán Corcra ó Bhun", "block.minecraft.banner.gradient_up.red": "Grádán Dearg ó Bhun", "block.minecraft.banner.gradient_up.white": "Grádán Bán ó Bhun", "block.minecraft.banner.gradient_up.yellow": "Grádán Buí ó Bhun", "block.minecraft.banner.half_horizontal.black": "Gearrtha, Dubh Thuas", "block.minecraft.banner.half_horizontal.blue": "Gearrtha, Gorm Thuas", "block.minecraft.banner.half_horizontal.brown": "Gearrtha, Donn Thuas", "block.minecraft.banner.half_horizontal.cyan": "Gearrtha, Cian Thuas", "block.minecraft.banner.half_horizontal.gray": "Gearrtha, Liath Thuas", "block.minecraft.banner.half_horizontal.green": "Gearrtha, Uaine Thuas", "block.minecraft.banner.half_horizontal.light_blue": "Gearrtha, Bánghorm Thuas", "block.minecraft.banner.half_horizontal.light_gray": "Gearrtha, Fionnliath Thuas", "block.minecraft.banner.half_horizontal.lime": "Gearrtha, Líomach Thuas", "block.minecraft.banner.half_horizontal.magenta": "Gearrtha, Maigeanta Thuas", "block.minecraft.banner.half_horizontal.orange": "Gearrtha, Oráisteach Thuas", "block.minecraft.banner.half_horizontal.pink": "Gearrtha, Bándearg Thuas", "block.minecraft.banner.half_horizontal.purple": "Gearrtha, Corcra Thuas", "block.minecraft.banner.half_horizontal.red": "Gearrtha, Dearg Thuas", "block.minecraft.banner.half_horizontal.white": "Gearrtha, Ban Thuas", "block.minecraft.banner.half_horizontal.yellow": "Gearrtha, Buí Thuas", "block.minecraft.banner.half_horizontal_bottom.black": "Gearrtha, Dubh Thíos", "block.minecraft.banner.half_horizontal_bottom.blue": "Gearrtha, Gorm Thíos", "block.minecraft.banner.half_horizontal_bottom.brown": "Gearrtha, Donn Thíos", "block.minecraft.banner.half_horizontal_bottom.cyan": "Gearrtha, Cian Thíos", "block.minecraft.banner.half_horizontal_bottom.gray": "Gearrtha, Liath Thíos", "block.minecraft.banner.half_horizontal_bottom.green": "Gearrtha, Uaine Thíos", "block.minecraft.banner.half_horizontal_bottom.light_blue": "Gearrtha, Bánghorm Thíos", "block.minecraft.banner.half_horizontal_bottom.light_gray": "Gearrtha, Fionnliath Thíos", "block.minecraft.banner.half_horizontal_bottom.lime": "Gearrtha, Líomach Thíos", "block.minecraft.banner.half_horizontal_bottom.magenta": "Gearrtha, Maigeanta Thíos", "block.minecraft.banner.half_horizontal_bottom.orange": "Gearrtha, Oráisteach Thíos", "block.minecraft.banner.half_horizontal_bottom.pink": "Gearrtha, Bándearg Thíos", "block.minecraft.banner.half_horizontal_bottom.purple": "Gearrtha, Corcra Thíos", "block.minecraft.banner.half_horizontal_bottom.red": "Gearrtha, Dearg Thíos", "block.minecraft.banner.half_horizontal_bottom.white": "Gearrtha, Bán Thíos", "block.minecraft.banner.half_horizontal_bottom.yellow": "Gearrtha, Buí Thíos", "block.minecraft.banner.half_vertical.black": "Deighilte, Dubh ar Dheis", "block.minecraft.banner.half_vertical.blue": "Deighilte, Gorm ar Dheis", "block.minecraft.banner.half_vertical.brown": "Deighilte, Donn ar Dheis", "block.minecraft.banner.half_vertical.cyan": "Deighilte, Cian ar Dheis", "block.minecraft.banner.half_vertical.gray": "Deighilte, Liath ar Dheis", "block.minecraft.banner.half_vertical.green": "Deighilte, Uaine ar Dheis", "block.minecraft.banner.half_vertical.light_blue": "Deighilte, Bánghorm ar Dheis", "block.minecraft.banner.half_vertical.light_gray": "Deighilte, Fionnliath ar Dheis", "block.minecraft.banner.half_vertical.lime": "Deighilte, Líomach ar Dheis", "block.minecraft.banner.half_vertical.magenta": "Deighilte, Maigeanta ar Dheis", "block.minecraft.banner.half_vertical.orange": "Deighilte, Oráisteach ar Dheis", "block.minecraft.banner.half_vertical.pink": "Deighilte, Bándearg ar Dheis", "block.minecraft.banner.half_vertical.purple": "Deighilte, Corcra ar Dheis", "block.minecraft.banner.half_vertical.red": "Deighilte, Dearg ar Dheis", "block.minecraft.banner.half_vertical.white": "Deighilte, Bán ar Dheis", "block.minecraft.banner.half_vertical.yellow": "Deighilte, Buí ar Dheis", "block.minecraft.banner.half_vertical_right.black": "Deighilte, Dubh ar Clé", "block.minecraft.banner.half_vertical_right.blue": "Deighilte, Gorm ar Clé", "block.minecraft.banner.half_vertical_right.brown": "Deighilte, Donn ar Clé", "block.minecraft.banner.half_vertical_right.cyan": "Deighilte, Cian ar Clé", "block.minecraft.banner.half_vertical_right.gray": "Deighilte, Liath ar Clé", "block.minecraft.banner.half_vertical_right.green": "Deighilte, Uaine ar Clé", "block.minecraft.banner.half_vertical_right.light_blue": "Deighilte, Bánghorm ar Clé", "block.minecraft.banner.half_vertical_right.light_gray": "Deighilte, Fionnliath ar Clé", "block.minecraft.banner.half_vertical_right.lime": "Deighilte, Líomach ar Clé", "block.minecraft.banner.half_vertical_right.magenta": "Deighilte, Maigeanta ar Clé", "block.minecraft.banner.half_vertical_right.orange": "Deighilte, Oráisteach ar Clé", "block.minecraft.banner.half_vertical_right.pink": "Deighilte, Bándearg ar Clé", "block.minecraft.banner.half_vertical_right.purple": "Deighilte, Corcra ar Clé", "block.minecraft.banner.half_vertical_right.red": "Deighilte, Dearg ar Clé", "block.minecraft.banner.half_vertical_right.white": "Deighilte, Bán ar Clé", "block.minecraft.banner.half_vertical_right.yellow": "Deighilte, Buí ar Clé", "block.minecraft.banner.mojang.black": "Rud Dubh", "block.minecraft.banner.mojang.blue": "Rud Gorm", "block.minecraft.banner.mojang.brown": "Rud Donn", "block.minecraft.banner.mojang.cyan": "Rud Cian", "block.minecraft.banner.mojang.gray": "Rud Liath", "block.minecraft.banner.mojang.green": "Rud Uaine", "block.minecraft.banner.mojang.light_blue": "Rud Bánghorm", "block.minecraft.banner.mojang.light_gray": "Rud Fionnliath", "block.minecraft.banner.mojang.lime": "Rud Líomach", "block.minecraft.banner.mojang.magenta": "Rud Maigeanta", "block.minecraft.banner.mojang.orange": "Rud Oráisteach", "block.minecraft.banner.mojang.pink": "Rud Bándearg", "block.minecraft.banner.mojang.purple": "Rud Corcra", "block.minecraft.banner.mojang.red": "Rud Dearg", "block.minecraft.banner.mojang.white": "Rud Bán", "block.minecraft.banner.mojang.yellow": "Rud Buí", "block.minecraft.banner.rhombus.black": "Muileata Dubh", "block.minecraft.banner.rhombus.blue": "Muileata Gorm", "block.minecraft.banner.rhombus.brown": "Muileata Donn", "block.minecraft.banner.rhombus.cyan": "Muileata Cian", "block.minecraft.banner.rhombus.gray": "Muileata Liath", "block.minecraft.banner.rhombus.green": "Muileata Uaine", "block.minecraft.banner.rhombus.light_blue": "Muileata Bánghorm", "block.minecraft.banner.rhombus.light_gray": "Muileata Fionnliath", "block.minecraft.banner.rhombus.lime": "Muileata Líomach", "block.minecraft.banner.rhombus.magenta": "Muileata Maigeanta", "block.minecraft.banner.rhombus.orange": "Muileata Oráisteach", "block.minecraft.banner.rhombus.pink": "Muileata Bándearg", "block.minecraft.banner.rhombus.purple": "Muileata Corcra", "block.minecraft.banner.rhombus.red": "Muileata Dearg", "block.minecraft.banner.rhombus.white": "Muileata Bán", "block.minecraft.banner.rhombus.yellow": "Muileata Buí", "block.minecraft.banner.skull.black": "Fíor Cloiginn Dubh", "block.minecraft.banner.skull.blue": "Fíor Cloiginn Gorm", "block.minecraft.banner.skull.brown": "Fíor Cloiginn Donn", "block.minecraft.banner.skull.cyan": "Fíor Cloiginn Cian", "block.minecraft.banner.skull.gray": "Fíor Cloiginn Liath", "block.minecraft.banner.skull.green": "Fíor Cloiginn Uaine", "block.minecraft.banner.skull.light_blue": "Fíor Cloiginn Bánghorm", "block.minecraft.banner.skull.light_gray": "Fíor Cloiginn Fionnliath", "block.minecraft.banner.skull.lime": "Fíor Cloiginn Líomach", "block.minecraft.banner.skull.magenta": "Fíor Cloiginn Maigeanta", "block.minecraft.banner.skull.orange": "Fíor Cloiginn Oráisteach", "block.minecraft.banner.skull.pink": "Fíor Cloiginn Bándearg", "block.minecraft.banner.skull.purple": "Fíor Cloiginn Corcra", "block.minecraft.banner.skull.red": "Fíor Cloiginn Dearg", "block.minecraft.banner.skull.white": "Fíor Cloiginn Bán", "block.minecraft.banner.skull.yellow": "Fíor Cloiginn Buí", "block.minecraft.banner.small_stripes.black": "Cuailleach Dubh", "block.minecraft.banner.small_stripes.blue": "Cuailleach Gorm", "block.minecraft.banner.small_stripes.brown": "Cuailleach Donn", "block.minecraft.banner.small_stripes.cyan": "Cuailleach Cian", "block.minecraft.banner.small_stripes.gray": "Cuailleach Liath", "block.minecraft.banner.small_stripes.green": "Cuailleach Uaine", "block.minecraft.banner.small_stripes.light_blue": "Cuailleach Bánghorm", "block.minecraft.banner.small_stripes.light_gray": "Cuailleach Fionnliath", "block.minecraft.banner.small_stripes.lime": "Cuailleach Líomach", "block.minecraft.banner.small_stripes.magenta": "Cuailleach Maigeanta", "block.minecraft.banner.small_stripes.orange": "Cuailleach Oráisteach", "block.minecraft.banner.small_stripes.pink": "Cuailleach Bándearg", "block.minecraft.banner.small_stripes.purple": "Cuailleach Corcra", "block.minecraft.banner.small_stripes.red": "Cuailleach Dearg", "block.minecraft.banner.small_stripes.white": "Cuailleach Bán", "block.minecraft.banner.small_stripes.yellow": "Cuailleach Buí", "block.minecraft.banner.square_bottom_left.black": "Cúinneán Dubh sa Bhun Deas", "block.minecraft.banner.square_bottom_left.blue": "Cúinneán Gorm sa Bhun Deas", "block.minecraft.banner.square_bottom_left.brown": "Cúinneán Donn sa Bhun Deas", "block.minecraft.banner.square_bottom_left.cyan": "Cúinneán Cian sa Bhun Deas", "block.minecraft.banner.square_bottom_left.gray": "Cúinneán Liath sa Bhun Deas", "block.minecraft.banner.square_bottom_left.green": "Cúinneán Uaine sa Bhun Deas", "block.minecraft.banner.square_bottom_left.light_blue": "Cúinneán Bánghorm sa Bhun Deas", "block.minecraft.banner.square_bottom_left.light_gray": "Cúinneán Fionnliath sa Bhun Deas", "block.minecraft.banner.square_bottom_left.lime": "Cúinneán Líomach sa Bhun Deas", "block.minecraft.banner.square_bottom_left.magenta": "Cúinneán Maigeanta sa Bhun Deas", "block.minecraft.banner.square_bottom_left.orange": "Cúinneán Oráisteach sa Bhun Deas", "block.minecraft.banner.square_bottom_left.pink": "Cúinneán Bándearg sa Bhun Deas", "block.minecraft.banner.square_bottom_left.purple": "Cúinneán Corcra sa Bhun Deas", "block.minecraft.banner.square_bottom_left.red": "Cúinneán Dearg sa Bhun Deas", "block.minecraft.banner.square_bottom_left.white": "Cúinneán Bán sa Bhun Deas", "block.minecraft.banner.square_bottom_left.yellow": "Cúinneán Buí sa Bhun Deas", "block.minecraft.banner.square_bottom_right.black": "Cúinneán Dubh sa Bhun Clé", "block.minecraft.banner.square_bottom_right.blue": "Cúinneán Gorm sa Bhun Clé", "block.minecraft.banner.square_bottom_right.brown": "Cúinneán Donn sa Bhun Clé", "block.minecraft.banner.square_bottom_right.cyan": "Cúinneán Cian sa Bhun Clé", "block.minecraft.banner.square_bottom_right.gray": "Cúinneán Liath sa Bhun Clé", "block.minecraft.banner.square_bottom_right.green": "Cúinneán Uaine sa Bhun Clé", "block.minecraft.banner.square_bottom_right.light_blue": "Cúinneán Bánghorm sa Bhun Clé", "block.minecraft.banner.square_bottom_right.light_gray": "Cúinneán Fionnliath sa Bhun Clé", "block.minecraft.banner.square_bottom_right.lime": "Cúinneán Líomach sa Bhun Clé", "block.minecraft.banner.square_bottom_right.magenta": "Cúinneán Maigeanta sa Bhun Clé", "block.minecraft.banner.square_bottom_right.orange": "Cúinneán Oráisteach sa Bhun Clé", "block.minecraft.banner.square_bottom_right.pink": "Cúinneán Bándearg sa Bhun Clé", "block.minecraft.banner.square_bottom_right.purple": "Cúinneán Corcra sa Bhun Clé", "block.minecraft.banner.square_bottom_right.red": "Cúinneán Dearg sa Bhun Clé", "block.minecraft.banner.square_bottom_right.white": "Cúinneán Ban sa Bhun Clé", "block.minecraft.banner.square_bottom_right.yellow": "Cúinneán Buí sa Bhun Clé", "block.minecraft.banner.square_top_left.black": "Cúinneán Dubh Thuas ar Dheis", "block.minecraft.banner.square_top_left.blue": "Cúinneán Gorm Thuas ar Dheis", "block.minecraft.banner.square_top_left.brown": "Cúinneán Donn Thuas ar Dheis", "block.minecraft.banner.square_top_left.cyan": "Cúinneán Cian Thuas ar Dheis", "block.minecraft.banner.square_top_left.gray": "Cúinneán Liath Thuas ar Dheis", "block.minecraft.banner.square_top_left.green": "Cúinneán Uaine Thuas ar Dheis", "block.minecraft.banner.square_top_left.light_blue": "Cúinneán Bánghorm Thuas ar Dheis", "block.minecraft.banner.square_top_left.light_gray": "Cúinneán Fionnliath Thuas ar Dheis", "block.minecraft.banner.square_top_left.lime": "Cúinneán Líomach Thuas ar Dheis", "block.minecraft.banner.square_top_left.magenta": "Cúinneán Maigeanta Thuas ar Dheis", "block.minecraft.banner.square_top_left.orange": "Cúinneán Oráisteach Thuas ar Dheis", "block.minecraft.banner.square_top_left.pink": "Cúinneán Bándearg Thuas ar Dheis", "block.minecraft.banner.square_top_left.purple": "Cúinneán Corcra Thuas ar Dheis", "block.minecraft.banner.square_top_left.red": "Cúinneán Dearg Thuas ar Dheis", "block.minecraft.banner.square_top_left.white": "Cúinneán Bán Thuas ar Dheis", "block.minecraft.banner.square_top_left.yellow": "Cúinneán Buí Thuas ar Dheis", "block.minecraft.banner.square_top_right.black": "Cúinneán Dubh Thuas ar Clé", "block.minecraft.banner.square_top_right.blue": "Cúinneán Gorm Thuas ar Clé", "block.minecraft.banner.square_top_right.brown": "Cúinneán Donn Thuas ar Clé", "block.minecraft.banner.square_top_right.cyan": "Cúinneán Cian Thuas ar Clé", "block.minecraft.banner.square_top_right.gray": "Cúinneán Liath Thuas ar Clé", "block.minecraft.banner.square_top_right.green": "Cúinneán Uaine Thuas ar Clé", "block.minecraft.banner.square_top_right.light_blue": "Cúinneán Bánghorm Thuas ar Clé", "block.minecraft.banner.square_top_right.light_gray": "Cúinneán Fionnliath Thuas ar Clé", "block.minecraft.banner.square_top_right.lime": "Cúinneán Líomach Thuas ar Clé", "block.minecraft.banner.square_top_right.magenta": "Cúinneán Maigeanta Thuas ar Clé", "block.minecraft.banner.square_top_right.orange": "Cúinneán Oráisteach Thuas ar Clé", "block.minecraft.banner.square_top_right.pink": "Cúinneán Bándearg Thuas ar Clé", "block.minecraft.banner.square_top_right.purple": "Cúinneán Corcra Thuas ar Clé", "block.minecraft.banner.square_top_right.red": "Cúinneán Dearg Thuas ar Clé", "block.minecraft.banner.square_top_right.white": "Cúinneán Bán Thuas ar Clé", "block.minecraft.banner.square_top_right.yellow": "Cúinneán Buí Thuas ar Clé", "block.minecraft.banner.straight_cross.black": "Cros Dubh", "block.minecraft.banner.straight_cross.blue": "Cros Gorm", "block.minecraft.banner.straight_cross.brown": "Cros Donn", "block.minecraft.banner.straight_cross.cyan": "Cros Cian", "block.minecraft.banner.straight_cross.gray": "Cros Liath", "block.minecraft.banner.straight_cross.green": "Cros Uaine", "block.minecraft.banner.straight_cross.light_blue": "Cros Bánghorm", "block.minecraft.banner.straight_cross.light_gray": "Cros Fionnliath", "block.minecraft.banner.straight_cross.lime": "Cros Líomach", "block.minecraft.banner.straight_cross.magenta": "Cros Maigeanta", "block.minecraft.banner.straight_cross.orange": "Cros Oráisteach", "block.minecraft.banner.straight_cross.pink": "Cros Bándearg", "block.minecraft.banner.straight_cross.purple": "Cros Corcra", "block.minecraft.banner.straight_cross.red": "Cros Dearg", "block.minecraft.banner.straight_cross.white": "Cros Bán", "block.minecraft.banner.straight_cross.yellow": "Cros Buí", "block.minecraft.banner.stripe_bottom.black": "Ionad Dubh", "block.minecraft.banner.stripe_bottom.blue": "Bun Gorm", "block.minecraft.banner.stripe_bottom.brown": "Bun Donn", "block.minecraft.banner.stripe_bottom.cyan": "Bun Cian", "block.minecraft.banner.stripe_bottom.gray": "Bun Liath", "block.minecraft.banner.stripe_bottom.green": "Bun Uaine", "block.minecraft.banner.stripe_bottom.light_blue": "Bun Fionnghorm", "block.minecraft.banner.stripe_bottom.light_gray": "Bun Fionnliath", "block.minecraft.banner.stripe_bottom.lime": "Bun Líomach", "block.minecraft.banner.stripe_bottom.magenta": "Bun Maigeanta", "block.minecraft.banner.stripe_bottom.orange": "Bun Oráisteach", "block.minecraft.banner.stripe_bottom.pink": "Bun Bándearg", "block.minecraft.banner.stripe_bottom.purple": "Bun Corcra", "block.minecraft.banner.stripe_bottom.red": "Ionad Dearg", "block.minecraft.banner.stripe_bottom.white": "Bun Bán", "block.minecraft.banner.stripe_bottom.yellow": "Bun Buí", "block.minecraft.banner.stripe_center.black": "Cuaille Dubh", "block.minecraft.banner.stripe_center.blue": "Cuaille Gorm", "block.minecraft.banner.stripe_center.brown": "Cuaille Donn", "block.minecraft.banner.stripe_center.cyan": "Cuaille Cian", "block.minecraft.banner.stripe_center.gray": "Cuaille Liath", "block.minecraft.banner.stripe_center.green": "Cuaille Uaine", "block.minecraft.banner.stripe_center.light_blue": "Cuaille Bánghorm", "block.minecraft.banner.stripe_center.light_gray": "Cuaille Fionnliath", "block.minecraft.banner.stripe_center.lime": "Cuaille Líomach", "block.minecraft.banner.stripe_center.magenta": "Cuaille Maigeanta", "block.minecraft.banner.stripe_center.orange": "Cuaille Oráisteach", "block.minecraft.banner.stripe_center.pink": "Cuaille Bándearg", "block.minecraft.banner.stripe_center.purple": "Cuaille Corcra", "block.minecraft.banner.stripe_center.red": "Cuaille Dearg", "block.minecraft.banner.stripe_center.white": "Cuaille Bán", "block.minecraft.banner.stripe_center.yellow": "Cuaille Buí", "block.minecraft.banner.stripe_downleft.black": "Clébhandán Dubh", "block.minecraft.banner.stripe_downleft.blue": "Clébhandán Gorm", "block.minecraft.banner.stripe_downleft.brown": "Clébhandán Donn", "block.minecraft.banner.stripe_downleft.cyan": "Clébhandán Cian", "block.minecraft.banner.stripe_downleft.gray": "Clébhandán Liath", "block.minecraft.banner.stripe_downleft.green": "Clébhandán Uaine", "block.minecraft.banner.stripe_downleft.light_blue": "Clébhandán Bánghorm", "block.minecraft.banner.stripe_downleft.light_gray": "Clébhandán Fionnliath", "block.minecraft.banner.stripe_downleft.lime": "Clébhandán Líomach", "block.minecraft.banner.stripe_downleft.magenta": "Clébhandán Maigeanta", "block.minecraft.banner.stripe_downleft.orange": "Clébhandán Oráisteach", "block.minecraft.banner.stripe_downleft.pink": "Clébhandán Bándearg", "block.minecraft.banner.stripe_downleft.purple": "Clébhandán Corcra", "block.minecraft.banner.stripe_downleft.red": "Clébhandán Dearg", "block.minecraft.banner.stripe_downleft.white": "Clébhandán Bán", "block.minecraft.banner.stripe_downleft.yellow": "Clébhandán Buí", "block.minecraft.banner.stripe_downright.black": "Bandán Dubh", "block.minecraft.banner.stripe_downright.blue": "Bandán Gorm", "block.minecraft.banner.stripe_downright.brown": "Bandán Donn", "block.minecraft.banner.stripe_downright.cyan": "Bandán Cian", "block.minecraft.banner.stripe_downright.gray": "Bandán Liath", "block.minecraft.banner.stripe_downright.green": "Bandán Uaine", "block.minecraft.banner.stripe_downright.light_blue": "Bandán Bánghorm", "block.minecraft.banner.stripe_downright.light_gray": "Bandán Fionnliath", "block.minecraft.banner.stripe_downright.lime": "Bandán Líomach", "block.minecraft.banner.stripe_downright.magenta": "Bandán Maigeanta", "block.minecraft.banner.stripe_downright.orange": "Bandán Oráisteach", "block.minecraft.banner.stripe_downright.pink": "Bandán Bándearg", "block.minecraft.banner.stripe_downright.purple": "Bandán Corcra", "block.minecraft.banner.stripe_downright.red": "Bandán Dearg", "block.minecraft.banner.stripe_downright.white": "Bandán Bán", "block.minecraft.banner.stripe_downright.yellow": "Bandán Buí", "block.minecraft.banner.stripe_left.black": "Cuaille Dubh ar Dheis", "block.minecraft.banner.stripe_left.blue": "Cuaille Gorm ar Dheis", "block.minecraft.banner.stripe_left.brown": "Cuaille Donn ar Dheis", "block.minecraft.banner.stripe_left.cyan": "Cuaille Cian ar Dheis", "block.minecraft.banner.stripe_left.gray": "Cuaille Liath ar Dheis", "block.minecraft.banner.stripe_left.green": "Cuaille Uaine ar Dheis", "block.minecraft.banner.stripe_left.light_blue": "Cuaille Bánghorm ar Dheis", "block.minecraft.banner.stripe_left.light_gray": "Cuaille Fionnliath ar Dheis", "block.minecraft.banner.stripe_left.lime": "Cuaille Líomach ar Dheis", "block.minecraft.banner.stripe_left.magenta": "Cuaille Maigeanta ar Dheis", "block.minecraft.banner.stripe_left.orange": "Cuaille Oráisteach ar Dheis", "block.minecraft.banner.stripe_left.pink": "Cuaille Bándearg ar Dheis", "block.minecraft.banner.stripe_left.purple": "Cuaille Corcra ar Dheis", "block.minecraft.banner.stripe_left.red": "Cuaille Dearg ar Dheis", "block.minecraft.banner.stripe_left.white": "Cuaille Bán ar Dheis", "block.minecraft.banner.stripe_left.yellow": "Cuaille Buí ar Dheis", "block.minecraft.banner.stripe_middle.black": "Balc Dubh", "block.minecraft.banner.stripe_middle.blue": "Balc Gorm", "block.minecraft.banner.stripe_middle.brown": "Balc Donn", "block.minecraft.banner.stripe_middle.cyan": "Balc Cian", "block.minecraft.banner.stripe_middle.gray": "Balc Liath", "block.minecraft.banner.stripe_middle.green": "Balc Uaine", "block.minecraft.banner.stripe_middle.light_blue": "Balc Bánghorm", "block.minecraft.banner.stripe_middle.light_gray": "Balc Fionnliath", "block.minecraft.banner.stripe_middle.lime": "Balc Líomach", "block.minecraft.banner.stripe_middle.magenta": "Balc Maigeanta", "block.minecraft.banner.stripe_middle.orange": "Balc Oráisteach", "block.minecraft.banner.stripe_middle.pink": "Balc Bándearg", "block.minecraft.banner.stripe_middle.purple": "Balc Corcra", "block.minecraft.banner.stripe_middle.red": "Balc Dearg", "block.minecraft.banner.stripe_middle.white": "Balc Bán", "block.minecraft.banner.stripe_middle.yellow": "Balc Buí", "block.minecraft.banner.stripe_right.black": "Cuaille Dubh ar Clé", "block.minecraft.banner.stripe_right.blue": "Cuaille Gorm ar Clé", "block.minecraft.banner.stripe_right.brown": "Cuaille Donn ar Clé", "block.minecraft.banner.stripe_right.cyan": "Cuaille Cian ar Clé", "block.minecraft.banner.stripe_right.gray": "Cuaille Liath ar Clé", "block.minecraft.banner.stripe_right.green": "Cuaille Uaine ar Clé", "block.minecraft.banner.stripe_right.light_blue": "Cuaille Bánghorm ar Clé", "block.minecraft.banner.stripe_right.light_gray": "Cuaille Fionnliath ar Clé", "block.minecraft.banner.stripe_right.lime": "Cuaille Líomach ar Clé", "block.minecraft.banner.stripe_right.magenta": "Cuaille Maigeanta ar Clé", "block.minecraft.banner.stripe_right.orange": "Cuaille Oráisteach ar Clé", "block.minecraft.banner.stripe_right.pink": "Cuaille Bándearg ar Clé", "block.minecraft.banner.stripe_right.purple": "Cuaille Corcra ar Clé", "block.minecraft.banner.stripe_right.red": "Cuaille Dearg ar Clé", "block.minecraft.banner.stripe_right.white": "Cuaille Bán ar Clé", "block.minecraft.banner.stripe_right.yellow": "Cuaille Buí ar Clé", "block.minecraft.banner.stripe_top.black": "Barr Dubh", "block.minecraft.banner.stripe_top.blue": "Barr Gorm", "block.minecraft.banner.stripe_top.brown": "Barr Donn", "block.minecraft.banner.stripe_top.cyan": "Barr Cian", "block.minecraft.banner.stripe_top.gray": "Barr Liath", "block.minecraft.banner.stripe_top.green": "Barr Uaine", "block.minecraft.banner.stripe_top.light_blue": "Barr Bánghorm", "block.minecraft.banner.stripe_top.light_gray": "Barr Fionnliath", "block.minecraft.banner.stripe_top.lime": "Barr Líomach", "block.minecraft.banner.stripe_top.magenta": "Barr Maigeanta", "block.minecraft.banner.stripe_top.orange": "Barr Oráisteach", "block.minecraft.banner.stripe_top.pink": "Barr Bándearg", "block.minecraft.banner.stripe_top.purple": "Barr Corcra", "block.minecraft.banner.stripe_top.red": "Barr Dearg", "block.minecraft.banner.stripe_top.white": "Barr Bán", "block.minecraft.banner.stripe_top.yellow": "Barr Buí", "block.minecraft.banner.triangle_bottom.black": "Binnroinnte Dubh", "block.minecraft.banner.triangle_bottom.blue": "Binnroinnte Gorm", "block.minecraft.banner.triangle_bottom.brown": "Binnroinnte Donn", "block.minecraft.banner.triangle_bottom.cyan": "Binnroinnte Cian", "block.minecraft.banner.triangle_bottom.gray": "Binnroinnte Liath", "block.minecraft.banner.triangle_bottom.green": "Binnroinnte Uaine", "block.minecraft.banner.triangle_bottom.light_blue": "Binnroinnte Bánghorm", "block.minecraft.banner.triangle_bottom.light_gray": "Binnroinnte Fionnliath", "block.minecraft.banner.triangle_bottom.lime": "Binnroinnte Líomach", "block.minecraft.banner.triangle_bottom.magenta": "Binnroinnte Maigeanta", "block.minecraft.banner.triangle_bottom.orange": "Binnroinnte Oráisteach", "block.minecraft.banner.triangle_bottom.pink": "Binnroinnte Bándearg", "block.minecraft.banner.triangle_bottom.purple": "Binnroinnte Corcra", "block.minecraft.banner.triangle_bottom.red": "Binnroinnte Dearg", "block.minecraft.banner.triangle_bottom.white": "Binnroinnte Bán", "block.minecraft.banner.triangle_bottom.yellow": "Binnroinnte Buí", "block.minecraft.banner.triangle_top.black": "Binnroinnte Bunoscionn Dubh", "block.minecraft.banner.triangle_top.blue": "Binnroinnte Bunoscionn Gorm", "block.minecraft.banner.triangle_top.brown": "Binnroinnte Bunoscionn Donn", "block.minecraft.banner.triangle_top.cyan": "Binnroinnte Bunoscionn Cian", "block.minecraft.banner.triangle_top.gray": "Binnroinnte Bunoscionn Liath", "block.minecraft.banner.triangle_top.green": "Binnroinnte Bunoscionn Uaine", "block.minecraft.banner.triangle_top.light_blue": "Binnroinnte Bunoscionn Bánghorm", "block.minecraft.banner.triangle_top.light_gray": "Binnroinnte Bunoscionn Fionnliath", "block.minecraft.banner.triangle_top.lime": "Binnroinnte Bunoscionn Líomach", "block.minecraft.banner.triangle_top.magenta": "Binnroinnte Bunoscionn Maigeanta", "block.minecraft.banner.triangle_top.orange": "Binnroinnte Bunoscionn Oráisteach", "block.minecraft.banner.triangle_top.pink": "Binnroinnte Bunoscionn Bándearg", "block.minecraft.banner.triangle_top.purple": "Binnroinnte Bunoscionn Corcra", "block.minecraft.banner.triangle_top.red": "Binnroinnte Bunoscionn Dearg", "block.minecraft.banner.triangle_top.white": "Binnroinnte Bunoscionn Bán", "block.minecraft.banner.triangle_top.yellow": "Binnroinnte Bunoscionn Buí", "block.minecraft.banner.triangles_bottom.black": "Bun Dubh Eangach", "block.minecraft.banner.triangles_bottom.blue": "Bun Gorm Eangach", "block.minecraft.banner.triangles_bottom.brown": "Bun Donn Eangach", "block.minecraft.banner.triangles_bottom.cyan": "Bun Cian Eangach", "block.minecraft.banner.triangles_bottom.gray": "Bun Liath Eangach", "block.minecraft.banner.triangles_bottom.green": "Bun Uaine Eangach", "block.minecraft.banner.triangles_bottom.light_blue": "Bun Bánghorm Eangach", "block.minecraft.banner.triangles_bottom.light_gray": "Bun Fionnliath Eangach", "block.minecraft.banner.triangles_bottom.lime": "Bun Liomach Eangach", "block.minecraft.banner.triangles_bottom.magenta": "Bun Maigeanta Eangach", "block.minecraft.banner.triangles_bottom.orange": "Bun Oráisteach Eangach", "block.minecraft.banner.triangles_bottom.pink": "Bun Bándearg Eangach", "block.minecraft.banner.triangles_bottom.purple": "Bun Corcra Eangach", "block.minecraft.banner.triangles_bottom.red": "Bun Dearg Eangach", "block.minecraft.banner.triangles_bottom.white": "Bun Bán Eangach", "block.minecraft.banner.triangles_bottom.yellow": "Bun Buí Eangach", "block.minecraft.banner.triangles_top.black": "Barr Dubh Eangach", "block.minecraft.banner.triangles_top.blue": "Barr Gorm Eangach", "block.minecraft.banner.triangles_top.brown": "Barr Donn Eangach", "block.minecraft.banner.triangles_top.cyan": "Barr Cian Eangach", "block.minecraft.banner.triangles_top.gray": "Barr Liath Eangach", "block.minecraft.banner.triangles_top.green": "Barr Uaine Eangach", "block.minecraft.banner.triangles_top.light_blue": "Barr Bánghorm Eangach", "block.minecraft.banner.triangles_top.light_gray": "Barr Fionnliath Eangach", "block.minecraft.banner.triangles_top.lime": "Barr Líomach Eangach", "block.minecraft.banner.triangles_top.magenta": "Barr Maigeanta Eangach", "block.minecraft.banner.triangles_top.orange": "Barr Oráisteach Eangach", "block.minecraft.banner.triangles_top.pink": "Barr Bándearg Eangach", "block.minecraft.banner.triangles_top.purple": "Barr Corcra Eangach", "block.minecraft.banner.triangles_top.red": "Barr Dearg Eangach", "block.minecraft.banner.triangles_top.white": "Barr Bán Eangach", "block.minecraft.banner.triangles_top.yellow": "Barr Buí Eangach", "block.minecraft.barrel": "Bairille", "block.minecraft.barrier": "Bacainn", "block.minecraft.beacon": "Rabhcán", "block.minecraft.beacon.primary": "Príomh-chumhacht", "block.minecraft.beacon.secondary": "Fo-chumhacht", "block.minecraft.bed": "Leaba", "block.minecraft.bed.no_sleep": "Ní féidir codladh ach san oíche agus le linn stoirmeacha toirní", "block.minecraft.bed.not_safe": "Ní féidir leat do scíth a ligean anois, tá arrachtaí in aice leat", "block.minecraft.bed.not_valid": "Bhí do leaba bhaile ar iarraidh nó bhí bac uirthi", "block.minecraft.bed.obstructed": "Tá bac ar an leaba seo", "block.minecraft.bed.occupied": "Tá an leaba seo gafa", "block.minecraft.bed.too_far_away": "Ní féidir scíth a ligean anois, tá an leaba rófhada uait", "block.minecraft.bedrock": "Buncharraig", "block.minecraft.beetroots": "Biatais", "block.minecraft.bell": "Clog", "block.minecraft.birch_button": "Cnaipe Beithe", "block.minecraft.birch_door": "Doras Beithe", "block.minecraft.birch_fence": "Claí Beithe", "block.minecraft.birch_fence_gate": "Geata Beithe", "block.minecraft.birch_leaves": "Duilleoga Beithe", "block.minecraft.birch_log": "Lomán Beithe", "block.minecraft.birch_planks": "Clár Beithe", "block.minecraft.birch_pressure_plate": "Brúphláta Beithe", "block.minecraft.birch_sapling": "Beith Óg", "block.minecraft.birch_sign": "Comhartha Beithe", "block.minecraft.birch_slab": "Leac Beithe", "block.minecraft.birch_stairs": "Staighre Beithe", "block.minecraft.birch_trapdoor": "Comhla Thógála Beithe", "block.minecraft.birch_wall_sign": "Comhartha Balla Beithe", "block.minecraft.birch_wood": "Adhmad Beithe", "block.minecraft.black_banner": "Meirge Dubh", "block.minecraft.black_bed": "Leaba Dhubh", "block.minecraft.black_carpet": "Cairpéad Dubh", "block.minecraft.black_concrete": "Stroighin Dhubh", "block.minecraft.black_concrete_powder": "Púdar Stroighne Dubh", "block.minecraft.black_glazed_terracotta": "Cré Ghlónraithe Dhubh", "block.minecraft.black_shulker_box": "Bosca Slíogadóra Dhuibh", "block.minecraft.black_stained_glass": "Gloine Dhaite Dhubh", "block.minecraft.black_stained_glass_pane": "Pána Gloine Daite Duibhe", "block.minecraft.black_terracotta": "Cré Bhruite Dhubh", "block.minecraft.black_wool": "Olann Dhubh", "block.minecraft.blast_furnace": "Foirnéis Soinneáin", "block.minecraft.blue_banner": "Meirge Gorm", "block.minecraft.blue_bed": "Leaba Ghorm", "block.minecraft.blue_carpet": "Cairpéad Gorm", "block.minecraft.blue_concrete": "Stroighin Ghorm", "block.minecraft.blue_concrete_powder": "Púdar Stroighne Gorm", "block.minecraft.blue_glazed_terracotta": "Cré Ghlónraithe Ghorm", "block.minecraft.blue_ice": "Oighear Gorm", "block.minecraft.blue_orchid": "Magairlín Gorm", "block.minecraft.blue_shulker_box": "Bosca Slíogadóra Ghoirm", "block.minecraft.blue_stained_glass": "Gloine Dhaite Ghorm", "block.minecraft.blue_stained_glass_pane": "Pána Gloine Daite Goirme", "block.minecraft.blue_terracotta": "Cré Bhruite Liath", "block.minecraft.blue_wool": "Olann Ghorm", "block.minecraft.bone_block": "Bloc Cnáimhe", "block.minecraft.bookshelf": "Seilf Leabhar", "block.minecraft.brain_coral": "Inchinnchoiréal", "block.minecraft.brain_coral_block": "Bloc Inchinnchoiréil", "block.minecraft.brain_coral_fan": "Fean Inchinnchoiréil", "block.minecraft.brain_coral_wall_fan": "Ballafhean Inchinnchoiréil", "block.minecraft.brewing_stand": "Seastán Grúdaireachta", "block.minecraft.brick_slab": "Leac Bríce", "block.minecraft.brick_stairs": "Staighre Bríce", "block.minecraft.brick_wall": "Balla Brící", "block.minecraft.bricks": "Brící", "block.minecraft.brown_banner": "Meirge Donn", "block.minecraft.brown_bed": "Leaba Dhonn", "block.minecraft.brown_carpet": "Cairpéad Donn", "block.minecraft.brown_concrete": "Stroighin Dhonn", "block.minecraft.brown_concrete_powder": "Púdar Stroighne Donn", "block.minecraft.brown_glazed_terracotta": "Cré Ghlónraithe Dhonn", "block.minecraft.brown_mushroom": "Muisiriún Donn", "block.minecraft.brown_mushroom_block": "Bloic Muisiriún Donn", "block.minecraft.brown_shulker_box": "Bosca Slíogadóra Dhoinn", "block.minecraft.brown_stained_glass": "Gloine Dhaite Dhonn", "block.minecraft.brown_stained_glass_pane": "Pána Gloine Daite Doinne", "block.minecraft.brown_terracotta": "Cré Bhruite Dhonn", "block.minecraft.brown_wool": "Olann Dhonn", "block.minecraft.bubble_column": "Colún Bolgán", "block.minecraft.bubble_coral": "Bolgánchoiréal", "block.minecraft.bubble_coral_block": "Bloc Bolgánchoiréil", "block.minecraft.bubble_coral_fan": "Fean Bolgánchoiréil", "block.minecraft.bubble_coral_wall_fan": "Ballafhean Bolgánchoiréil", "block.minecraft.cactus": "Cachtas", "block.minecraft.cake": "Cáca", "block.minecraft.campfire": "Tine Champa", "block.minecraft.carrots": "Meacain Dhearga", "block.minecraft.cartography_table": "Bord Cartagrafaíochta", "block.minecraft.carved_pumpkin": "Puimcín Snoite", "block.minecraft.cauldron": "Coire", "block.minecraft.cave_air": "Aer Uaimhe", "block.minecraft.chain_command_block": "Bloc Ordaithe Slabhrach", "block.minecraft.chest": "Cófra", "block.minecraft.chipped_anvil": "Inneoin Scealptha", "block.minecraft.chiseled_quartz_block": "Bloc Grianchloiche Siséalta", "block.minecraft.chiseled_red_sandstone": "Gaineamhchloch Dhearg Shiséalta", "block.minecraft.chiseled_sandstone": "Gaineamhchloch Shiséalta", "block.minecraft.chiseled_stone_bricks": "Brící Cloiche Siséalta", "block.minecraft.chorus_flower": "Bláth Curfá", "block.minecraft.chorus_plant": "Planda Curfá", "block.minecraft.clay": "Cré", "block.minecraft.coal_block": "Bloc Guail", "block.minecraft.coal_ore": "Mian Guail", "block.minecraft.coarse_dirt": "Garbhithir", "block.minecraft.cobblestone": "Duirleog", "block.minecraft.cobblestone_slab": "Leac Duirleoga", "block.minecraft.cobblestone_stairs": "Staighre Cloiche", "block.minecraft.cobblestone_wall": "Balla Duirleoga", "block.minecraft.cobweb": "Gréasán an Damháin Alla", "block.minecraft.cocoa": "Cócó", "block.minecraft.command_block": "Bloc Ordaithe", "block.minecraft.comparator": "Comparadóir Deargchloiche", "block.minecraft.composter": "Bosca Múirín", "block.minecraft.conduit": "Seolphíopa", "block.minecraft.cornflower": "Gormán", "block.minecraft.cracked_stone_bricks": "Brící Cloiche Gágacha", "block.minecraft.crafting_table": "Bord Ceardaíochta", "block.minecraft.creeper_head": "Ceann Téaltóra", "block.minecraft.creeper_wall_head": "Ceann Balla Creeper", "block.minecraft.cut_red_sandstone": "Gaineamhchloch Dhearg Gearrtha", "block.minecraft.cut_red_sandstone_slab": "Gearr Leac Gaineamhchloiche Deirge", "block.minecraft.cut_sandstone": "Gaineamhchloch Gearrtha", "block.minecraft.cut_sandstone_slab": "Gearr Leac Gaineamhchloiche", "block.minecraft.cyan_banner": "Meirge Cian", "block.minecraft.cyan_bed": "Leaba Chian", "block.minecraft.cyan_carpet": "Cairpéad Cian", "block.minecraft.cyan_concrete": "Stroighin Chian", "block.minecraft.cyan_concrete_powder": "Púdar Stroighne Cian", "block.minecraft.cyan_glazed_terracotta": "Cré Ghlónraithe Chian", "block.minecraft.cyan_shulker_box": "Bosca Slíogadóra Chiain", "block.minecraft.cyan_stained_glass": "Gloine Dhaite Chian", "block.minecraft.cyan_stained_glass_pane": "Pána Gloine Daite Cian", "block.minecraft.cyan_terracotta": "Cré Bhruite Ghorm", "block.minecraft.cyan_wool": "Olann Chian", "block.minecraft.damaged_anvil": "Inneoin Damáiste", "block.minecraft.dandelion": "Caisearbhán", "block.minecraft.dark_oak_button": "Cnaipe Darach Duibhe", "block.minecraft.dark_oak_door": "Doras Darach Duibhe", "block.minecraft.dark_oak_fence": "Claí Darach Duibhe", "block.minecraft.dark_oak_fence_gate": "Geata Darach Duibhe", "block.minecraft.dark_oak_leaves": "Duilleoga Darach Duibhe", "block.minecraft.dark_oak_log": "Lomán Darach Duibhe", "block.minecraft.dark_oak_planks": "Clár Darach Duibhe", "block.minecraft.dark_oak_pressure_plate": "Brúphláta Darach Duibhe", "block.minecraft.dark_oak_sapling": "Dair Dhubh Óg", "block.minecraft.dark_oak_sign": "Comhartha Darach Duibhe", "block.minecraft.dark_oak_slab": "Leac Darach Duibhe", "block.minecraft.dark_oak_stairs": "Staighre Darach Duibhe", "block.minecraft.dark_oak_trapdoor": "Comhla Thógála Darach Duibhe", "block.minecraft.dark_oak_wall_sign": "Comhartha Balla Darach Duibhe", "block.minecraft.dark_oak_wood": "Adhmad Darach Duibhe", "block.minecraft.dark_prismarine": "Priosmuiríneach Dubh", "block.minecraft.dark_prismarine_slab": "Leac Priosmuirínigh Dhuibh", "block.minecraft.dark_prismarine_stairs": "Staighre Priosmuirínigh Dhuibh", "block.minecraft.daylight_detector": "Brathadóir Sholas an Lae", "block.minecraft.dead_brain_coral": "Inchinnchoiréal Marbh", "block.minecraft.dead_brain_coral_block": "Bloc Inchinnchoiréil Mhairbh", "block.minecraft.dead_brain_coral_fan": "Fean Inchinnchoiréil Mhairbh", "block.minecraft.dead_brain_coral_wall_fan": "Ballafhean Inchinnchoiréil Mhairbh", "block.minecraft.dead_bubble_coral": "Bolgánchoiréal Marbh", "block.minecraft.dead_bubble_coral_block": "Bloc Bolgánchoiréil Mhairbh", "block.minecraft.dead_bubble_coral_fan": "Fean Bolgánchoiréil Mhairbh", "block.minecraft.dead_bubble_coral_wall_fan": "Ballafhean Bolgánchoiréil Mhairbh", "block.minecraft.dead_bush": "Tor Marbh", "block.minecraft.dead_fire_coral": "Tinechoiréal Marbh", "block.minecraft.dead_fire_coral_block": "Bloc Tinechoiréil Mhairbh", "block.minecraft.dead_fire_coral_fan": "Fean Tinechoiréil Mhairbh", "block.minecraft.dead_fire_coral_wall_fan": "Ballafhean Tinechoiréil Mhairbh", "block.minecraft.dead_horn_coral": "Adharc-Choiréal Marbh", "block.minecraft.dead_horn_coral_block": "Bloc Adharc-Choiréil Mhairbh", "block.minecraft.dead_horn_coral_fan": "Fean Adharc-Choiréil Mhairbh", "block.minecraft.dead_horn_coral_wall_fan": "Ballafhean Adharc-Choiréil Mhairbh", "block.minecraft.dead_tube_coral": "Tiúbchoiréil Marbh", "block.minecraft.dead_tube_coral_block": "Bloc Tiúbchoiréil Mhairbh", "block.minecraft.dead_tube_coral_fan": "Fean Tiúbhchoiréil Mhairbh", "block.minecraft.dead_tube_coral_wall_fan": "Ballafhean Tiúbchoiréil Mhairbh", "block.minecraft.detector_rail": "Ráillí Brathadóireachta", "block.minecraft.diamond_block": "Bloc Diamaint", "block.minecraft.diamond_ore": "Mian Diamaint", "block.minecraft.diorite": "Dióirít", "block.minecraft.diorite_slab": "Leac Dhióiríte", "block.minecraft.diorite_stairs": "Staighre Dióiríte", "block.minecraft.diorite_wall": "Balla Dióiríte", "block.minecraft.dirt": "Ithir", "block.minecraft.dispenser": "Teilgeoir", "block.minecraft.dragon_egg": "Ubh Dhragain", "block.minecraft.dragon_head": "Ceann Dragain", "block.minecraft.dragon_wall_head": "Ceann Balla Dragain", "block.minecraft.dried_kelp_block": "Bloic Ceilp Triomaithe", "block.minecraft.dropper": "Dáileoir", "block.minecraft.emerald_block": "Bloc Smaragaide", "block.minecraft.emerald_ore": "Mian Smaragaide", "block.minecraft.enchanting_table": "Bord Asarlaíochta", "block.minecraft.end_gateway": "Geata na Críche", "block.minecraft.end_portal": "Tairseach don Chríoch", "block.minecraft.end_portal_frame": "Fráma do Thairseach na Críche", "block.minecraft.end_rod": "Slat na Críche", "block.minecraft.end_stone": "Cloch na Críche", "block.minecraft.end_stone_brick_slab": "Leac Bhrící Cloiche an Deiridh", "block.minecraft.end_stone_brick_stairs": "Staighre Brící Cloiche an Deiridh", "block.minecraft.end_stone_brick_wall": "Balla Brící Cloiche an Deireadh", "block.minecraft.end_stone_bricks": "Brící Chloch na Críche", "block.minecraft.ender_chest": "Cófra na Críche", "block.minecraft.farmland": "Talamh Feirme", "block.minecraft.fern": "Raithneach", "block.minecraft.fire": "Tine", "block.minecraft.fire_coral": "Tinechoiréal", "block.minecraft.fire_coral_block": "Bloc Tinechoiréil", "block.minecraft.fire_coral_fan": "Fean Tinechoiréil", "block.minecraft.fire_coral_wall_fan": "Ballafhean Tinechoiréil", "block.minecraft.fletching_table": "Bord Saighead", "block.minecraft.flower_pot": "Pota Bláthanna", "block.minecraft.flowing_lava": "Laibhe ag Sileadh", "block.minecraft.flowing_water": "Uisce ag Sileadh", "block.minecraft.four_turtle_eggs": "Ceithre Ubh Thurtair", "block.minecraft.frosted_ice": "Sioc Oighear", "block.minecraft.furnace": "Foirnéis", "block.minecraft.glass": "Gloine", "block.minecraft.glass_pane": "Pána Gloine", "block.minecraft.glowstone": "Lonnraít", "block.minecraft.gold_block": "Bloc Óir", "block.minecraft.gold_ore": "Mian Óir", "block.minecraft.granite": "Eibhear", "block.minecraft.granite_slab": "Leac Eibhir", "block.minecraft.granite_stairs": "Staighre Eibhir", "block.minecraft.granite_wall": "Balla Eibhir", "block.minecraft.grass": "Féar", "block.minecraft.grass_block": "Bloc Féir", "block.minecraft.grass_path": "Cosán Féir", "block.minecraft.gravel": "Gairbhéal", "block.minecraft.gray_banner": "Meirge Liath", "block.minecraft.gray_bed": "Leaba Liath", "block.minecraft.gray_carpet": "Cairpéad Liath", "block.minecraft.gray_concrete": "Stroighin Liath", "block.minecraft.gray_concrete_powder": "Púdar Stroighne Liath", "block.minecraft.gray_glazed_terracotta": "Cré Ghlónraithe Liath", "block.minecraft.gray_shulker_box": "Bosca Slíogadóra Léith", "block.minecraft.gray_stained_glass": "Gloine Dhaite Liath", "block.minecraft.gray_stained_glass_pane": "Pána Gloine Daite Léithe", "block.minecraft.gray_terracotta": "Cré Bhruite Liath", "block.minecraft.gray_wool": "Olann Liath", "block.minecraft.green_banner": "Meirge Uaine", "block.minecraft.green_bed": "Leaba Uaine", "block.minecraft.green_carpet": "Cairpéad Uaine", "block.minecraft.green_concrete": "Stroighin Uaine", "block.minecraft.green_concrete_powder": "Púdar Stroighne Uaine", "block.minecraft.green_glazed_terracotta": "Cré Ghlónraithe Uaine", "block.minecraft.green_shulker_box": "Bosca Slíogadóra Uaine", "block.minecraft.green_stained_glass": "Gloine Dhaite Uaine", "block.minecraft.green_stained_glass_pane": "Pána Gloine Daite Uaine", "block.minecraft.green_terracotta": "Cré Bhruite Uaine", "block.minecraft.green_wool": "Olann Uaine", "block.minecraft.grindstone": "Cloch Fhaobhair", "block.minecraft.hay_block": "Burla Féir Thirim", "block.minecraft.heavy_weighted_pressure_plate": "Brúphláta Trom", "block.minecraft.hopper": "Crannóg", "block.minecraft.horn_coral": "Adharc-Choiréal", "block.minecraft.horn_coral_block": "Bloc Adharc-Choiréil", "block.minecraft.horn_coral_fan": "Fean Adharc-Choiréil", "block.minecraft.horn_coral_wall_fan": "Ballafhean Adharc-Choiréil", "block.minecraft.ice": "Oighear", "block.minecraft.infested_chiseled_stone_bricks": "Brící Cloiche Siséalta Salacha", "block.minecraft.infested_cobblestone": "Duirleog Shalach", "block.minecraft.infested_cracked_stone_bricks": "Brící Cloiche Scoilte Salacha", "block.minecraft.infested_mossy_stone_bricks": "Brící Cloiche Caonacha Salacha", "block.minecraft.infested_stone": "Cloch Salach", "block.minecraft.infested_stone_bricks": "Brící Cloiche Salacha", "block.minecraft.iron_bars": "Barraí Iarainn", "block.minecraft.iron_block": "Bloc Iarainn", "block.minecraft.iron_door": "Doras Iarainn", "block.minecraft.iron_ore": "Amhiarann", "block.minecraft.iron_trapdoor": "Comhla Thógála Iarainn", "block.minecraft.jack_o_lantern": "Seán na Gealaí", "block.minecraft.jigsaw": "Bloc mireanna mearaí", "block.minecraft.jukebox": "Júcbhosca", "block.minecraft.jungle_button": "Cnaipe Dufaire", "block.minecraft.jungle_door": "Doras Adhmad Dufaire", "block.minecraft.jungle_fence": "Claí Adhmad Dufaire", "block.minecraft.jungle_fence_gate": "Geata Adhmad Dufaire", "block.minecraft.jungle_leaves": "Duilleoga Dufaire", "block.minecraft.jungle_log": "Lomán Dufaire", "block.minecraft.jungle_planks": "Clár Adhmad Dufaire", "block.minecraft.jungle_pressure_plate": "Brúphláta Dufaire", "block.minecraft.jungle_sapling": "Crann Dufaire Óg", "block.minecraft.jungle_sign": "Comhartha Ahmaid Dufaire", "block.minecraft.jungle_slab": "Leac Dufaire", "block.minecraft.jungle_stairs": "Staighre Dugaire", "block.minecraft.jungle_trapdoor": "Comhla Thógála Dufaire", "block.minecraft.jungle_wall_sign": "Comhartha Balla Adhmaid Dufaire", "block.minecraft.jungle_wood": "Adhmad Dufaire", "block.minecraft.kelp": "Ceilp", "block.minecraft.kelp_plant": "Planda Ceilp", "block.minecraft.ladder": "Dréimire", "block.minecraft.lantern": "Laindéar", "block.minecraft.lapis_block": "Bloc Lapis Lazuli", "block.minecraft.lapis_ore": "Mian Lapis Lazuli", "block.minecraft.large_fern": "Raithneach Mhór", "block.minecraft.lava": "Laibhe", "block.minecraft.lectern": "Léachtán", "block.minecraft.lever": "Luamhán", "block.minecraft.light_blue_banner": "Meirge Bánghorm", "block.minecraft.light_blue_bed": "Leaba Bhánghorm", "block.minecraft.light_blue_carpet": "Cairpéad Bánghorm", "block.minecraft.light_blue_concrete": "Stroighin Bhánghorm", "block.minecraft.light_blue_concrete_powder": "Púdar Stroighne Bánghorm", "block.minecraft.light_blue_glazed_terracotta": "Cré Ghlónraithe Bhánghorm", "block.minecraft.light_blue_shulker_box": "Bosca Slíogadóra Bhánghoirm", "block.minecraft.light_blue_stained_glass": "Gloine Dhaite Bhánghorm", "block.minecraft.light_blue_stained_glass_pane": "Pána Gloine Daite Bánghoirme", "block.minecraft.light_blue_terracotta": "Cré Bhruite Bhánghorm", "block.minecraft.light_blue_wool": "Olann Bhánghorm", "block.minecraft.light_gray_banner": "Meirge Fionnliath", "block.minecraft.light_gray_bed": "Leaba Fhionnliath", "block.minecraft.light_gray_carpet": "Cairpéad Fionnliath", "block.minecraft.light_gray_concrete": "Stroighin Fhionnliath", "block.minecraft.light_gray_concrete_powder": "Púdar Stroighne Fionnliath", "block.minecraft.light_gray_glazed_terracotta": "Cré Ghlónraithe Fhionnliath", "block.minecraft.light_gray_shulker_box": "Bosca Slíogadóra Fhionnléith", "block.minecraft.light_gray_stained_glass": "Gloine Dhaite Fhionnliath", "block.minecraft.light_gray_stained_glass_pane": "Pána Gloine Daite Fionnléithe", "block.minecraft.light_gray_terracotta": "Cré Bhruite Fhionnliath", "block.minecraft.light_gray_wool": "Olann Fhionnliath", "block.minecraft.light_weighted_pressure_plate": "Brúphláta Éadrom", "block.minecraft.lilac": "Líológ", "block.minecraft.lily_of_the_valley": "Lile na nGleanntán", "block.minecraft.lily_pad": "Duilleog Bháite", "block.minecraft.lime_banner": "Meirge Líomach", "block.minecraft.lime_bed": "Leaba Líomach", "block.minecraft.lime_carpet": "Cairpéad Líomach", "block.minecraft.lime_concrete": "Stroighin Líomach", "block.minecraft.lime_concrete_powder": "Púdar Stroighne Líomach", "block.minecraft.lime_glazed_terracotta": "Cré Ghlónraithe Líomach", "block.minecraft.lime_shulker_box": "Bosca Slíogadóra Líomach", "block.minecraft.lime_stained_glass": "Gloine Dhaite Líomach", "block.minecraft.lime_stained_glass_pane": "Pána Gloine Daite Líomaí", "block.minecraft.lime_terracotta": "Cré Bhruite Líomach", "block.minecraft.lime_wool": "Olann Líomach", "block.minecraft.loom": "Seol", "block.minecraft.magenta_banner": "Meirge Maigeanta", "block.minecraft.magenta_bed": "Leaba Mhaigeanta", "block.minecraft.magenta_carpet": "Cairpéad Maigeanta", "block.minecraft.magenta_concrete": "Stroighin Mhaigeanta", "block.minecraft.magenta_concrete_powder": "Púdar Stroighne Maigeanta", "block.minecraft.magenta_glazed_terracotta": "Cré Ghlónraithe Mhaigeanta", "block.minecraft.magenta_shulker_box": "Bosca Slíogadóra Mhaigeanta", "block.minecraft.magenta_stained_glass": "Gloine Dhaite Mhaigeanta", "block.minecraft.magenta_stained_glass_pane": "Pána Gloine Daite Maigeanta", "block.minecraft.magenta_terracotta": "Cré Bhruite Mhaigeanta", "block.minecraft.magenta_wool": "Olann Mhaigeanta", "block.minecraft.magma_block": "Bloc Magma", "block.minecraft.melon": "Mealbhacán", "block.minecraft.melon_stem": "Gas Mealbhacán", "block.minecraft.mossy_cobblestone": "Duirleog Caonach", "block.minecraft.mossy_cobblestone_slab": "Leac Dhuirleoga Caonaigh", "block.minecraft.mossy_cobblestone_stairs": "Staighre Duirleoga Caonaigh", "block.minecraft.mossy_cobblestone_wall": "Balla Duirleoga Caonaí", "block.minecraft.mossy_stone_brick_slab": "Leac Bhrící Cloiche Caonaigh", "block.minecraft.mossy_stone_brick_stairs": "Staighre Brící Cloiche Caonaigh", "block.minecraft.mossy_stone_brick_wall": "Balla Brící Cloiche Caonaigh", "block.minecraft.mossy_stone_bricks": "Brící Cloiche Caonaigh", "block.minecraft.moving_piston": "Loine Gluaiste", "block.minecraft.mushroom_stem": "Gas Muisiriún", "block.minecraft.mycelium": "Mícéiliam", "block.minecraft.nether_brick_fence": "Claí Íochtarbhríce", "block.minecraft.nether_brick_slab": "Leac Íochtarbhríce", "block.minecraft.nether_brick_stairs": "Staighre Íochtarbhríce", "block.minecraft.nether_brick_wall": "Balla Brící Ifrinn", "block.minecraft.nether_bricks": "Íochtarbhrící", "block.minecraft.nether_portal": "Tairseach don Íochtar", "block.minecraft.nether_quartz_ore": "Mian Ghrianchloch an Íochtair", "block.minecraft.nether_wart": "Mus an Íochtair", "block.minecraft.nether_wart_block": "Bloc Mhus an Íochtair", "block.minecraft.netherrack": "Íochtarchloch", "block.minecraft.note_block": "Bloc Nóta", "block.minecraft.oak_button": "Cnaipe Darach", "block.minecraft.oak_door": "Doras Darach", "block.minecraft.oak_fence": "Claí Darach", "block.minecraft.oak_fence_gate": "Geata Darach", "block.minecraft.oak_leaves": "Duilleoga Darach", "block.minecraft.oak_log": "Darach", "block.minecraft.oak_planks": "Clár Darach", "block.minecraft.oak_pressure_plate": "Brúphláta Darach", "block.minecraft.oak_sapling": "Dair Óg", "block.minecraft.oak_sign": "Comhartha Darach", "block.minecraft.oak_slab": "Leac Darach", "block.minecraft.oak_stairs": "Staighre Darach", "block.minecraft.oak_trapdoor": "Comhla Thógála Darach", "block.minecraft.oak_wall_sign": "Comhartha Balla Darach", "block.minecraft.oak_wood": "Adhmad Darach", "block.minecraft.observer": "Breathnóir", "block.minecraft.obsidian": "Obsaidian", "block.minecraft.ominous_banner": "Bratach tuarúil", "block.minecraft.orange_banner": "Meirge Oráisteach", "block.minecraft.orange_bed": "Leaba Oráisteach", "block.minecraft.orange_carpet": "Cairpéad Oráisteach", "block.minecraft.orange_concrete": "Stroighin Oráisteach", "block.minecraft.orange_concrete_powder": "Púdar Stroighne Oráisteach", "block.minecraft.orange_glazed_terracotta": "Cré Ghlónraithe Oráisteach", "block.minecraft.orange_shulker_box": "Bosca Slíogadóra Oráisteach", "block.minecraft.orange_stained_glass": "Gloine Dhaite Oráisteach", "block.minecraft.orange_stained_glass_pane": "Pána Gloine Daite Oráisteach", "block.minecraft.orange_terracotta": "Cré Bhruite Oráisteach", "block.minecraft.orange_tulip": "Tiúilip Oráisteach", "block.minecraft.orange_wool": "Olann Oráisteach", "block.minecraft.oxeye_daisy": "Nóinín Mór", "block.minecraft.packed_ice": "Oighear Cruaite", "block.minecraft.peony": "Piaine", "block.minecraft.petrified_oak_slab": "Leac Darach Clochraithe", "block.minecraft.pink_banner": "Meirge Bándearg", "block.minecraft.pink_bed": "Leaba Bhándearg", "block.minecraft.pink_carpet": "Cairpéad Bándearg", "block.minecraft.pink_concrete": "Stroighin Bhándearg", "block.minecraft.pink_concrete_powder": "Púdar Stroighne Bándearg", "block.minecraft.pink_glazed_terracotta": "Cré Ghlónraithe Bhándearg", "block.minecraft.pink_shulker_box": "Bosca Slíogadóra Bhándeirg", "block.minecraft.pink_stained_glass": "Gloine Dhaite Bhándearg", "block.minecraft.pink_stained_glass_pane": "Pána Gloine Daite Bándeirge", "block.minecraft.pink_terracotta": "Cré Bhruite Bhándearg", "block.minecraft.pink_tulip": "Tiúilip Bhándearg", "block.minecraft.pink_wool": "Olann Bhándearg", "block.minecraft.piston": "Loine", "block.minecraft.piston_head": "Ceann Loine", "block.minecraft.player_head": "Ceann Imreora", "block.minecraft.player_head.named": "Ceann %s", "block.minecraft.player_wall_head": "Ceann Balla Imreora", "block.minecraft.podzol": "Podsol", "block.minecraft.polished_andesite": "Aindéisít Shnasta", "block.minecraft.polished_andesite_slab": "Leac Aindéisíte Snasta", "block.minecraft.polished_andesite_stairs": "Staighre Andéisíte Snasta", "block.minecraft.polished_diorite": "Dióirít Shnasta", "block.minecraft.polished_diorite_slab": "Leac Dióiríte Snasta", "block.minecraft.polished_diorite_stairs": "Staighre Dióiríte Snasta", "block.minecraft.polished_granite": "Eibhear Snasta", "block.minecraft.polished_granite_slab": "Leac Eibhir Shnasta", "block.minecraft.polished_granite_stairs": "Staighre Eibhir Shnasta", "block.minecraft.poppy": "Poipín", "block.minecraft.potatoes": "Prátaí", "block.minecraft.potted_acacia_sapling": "Buinneán Acaicia i bPota", "block.minecraft.potted_allium": "Allium i bPota", "block.minecraft.potted_azure_bluet": "Goirmín Spéiriúil i bPota", "block.minecraft.potted_bamboo": "Bambú i gCroca", "block.minecraft.potted_birch_sapling": "Buinneán Beithe i bPota", "block.minecraft.potted_blue_orchid": "Magairlín Gorm i bPota", "block.minecraft.potted_brown_mushroom": "Muisirúin Donn i bPota", "block.minecraft.potted_cactus": "Cachtas i bPota", "block.minecraft.potted_cornflower": "Gormán i gCroca", "block.minecraft.potted_dandelion": "Caisearbhán i bPota", "block.minecraft.potted_dark_oak_sapling": "Buinneán Darach Duibhe i bPota", "block.minecraft.potted_dead_bush": "Tom Marbh i bPota", "block.minecraft.potted_fern": "Raithneach i bPota", "block.minecraft.potted_jungle_sapling": "Buinneán Dufaire i bPota", "block.minecraft.potted_lily_of_the_valley": "Lile na nGleanntán i bPota", "block.minecraft.potted_oak_sapling": "Buinneán Darach i bPota", "block.minecraft.potted_orange_tulip": "Tiúilip Orásite i bPota", "block.minecraft.potted_oxeye_daisy": "Nóinín Mór i bPota", "block.minecraft.potted_pink_tulip": "Tiúilip Bhándhearg i bPota", "block.minecraft.potted_poppy": "Poipín i bPota", "block.minecraft.potted_red_mushroom": "Muisiriún Dearg i bPota", "block.minecraft.potted_red_tulip": "Tiúilip Dhearg i bPota", "block.minecraft.potted_spruce_sapling": "Buinneán Sprúis i bPota", "block.minecraft.potted_white_tulip": "Tiúilip Bhán i bPota", "block.minecraft.potted_wither_rose": "Rósa Seargthóra i gCroca", "block.minecraft.powered_rail": "Ráillí Cumhachtaithe", "block.minecraft.prismarine": "Priosmuiríneach", "block.minecraft.prismarine_brick_slab": "Leac Bríce Priosmuiríní", "block.minecraft.prismarine_brick_stairs": "Staighre Bríce Priosmuiríní", "block.minecraft.prismarine_bricks": "Brící Priosmuirínigh", "block.minecraft.prismarine_slab": "Leac Priosmuirínigh", "block.minecraft.prismarine_stairs": "Staighre Priosmuirínigh", "block.minecraft.prismarine_wall": "Balla Priosmuiríneach", "block.minecraft.pumpkin": "Puimcín", "block.minecraft.pumpkin_stem": "Gas Puimcín", "block.minecraft.purple_banner": "Meirge Corcra", "block.minecraft.purple_bed": "Leaba Chorcra", "block.minecraft.purple_carpet": "Cairpéad Corcra", "block.minecraft.purple_concrete": "Stroighin Chorcra", "block.minecraft.purple_concrete_powder": "Púdar Stroighne Corcra", "block.minecraft.purple_glazed_terracotta": "Cré Ghlónraithe Chorcra", "block.minecraft.purple_shulker_box": "Bosca Slíogadóra Corcra", "block.minecraft.purple_stained_glass": "Gloine Dhaite Chorcra", "block.minecraft.purple_stained_glass_pane": "Pána Gloine Daite Corcra", "block.minecraft.purple_terracotta": "Cré Bhruite Chorcra", "block.minecraft.purple_wool": "Olann Chorcra", "block.minecraft.purpur_block": "Bloc Purpaire", "block.minecraft.purpur_pillar": "Colún Purpaire", "block.minecraft.purpur_slab": "Leac Purpaire", "block.minecraft.purpur_stairs": "Staighre Purpaire", "block.minecraft.quartz_block": "Bloc Grianchloiche", "block.minecraft.quartz_pillar": "Colún Grianchloiche", "block.minecraft.quartz_slab": "Leac Ghrianchloiche", "block.minecraft.quartz_stairs": "Staighre Grianchloiche", "block.minecraft.rail": "Ráillí", "block.minecraft.red_banner": "Meirge Dearg", "block.minecraft.red_bed": "Leaba Dhearg", "block.minecraft.red_carpet": "Cairpéad Dearg", "block.minecraft.red_concrete": "Stroighin Dhearg", "block.minecraft.red_concrete_powder": "Púdar Stroighne Dearg", "block.minecraft.red_glazed_terracotta": "Cré Ghlónraithe Dhearg", "block.minecraft.red_mushroom": "Muisiriún Dearg", "block.minecraft.red_mushroom_block": "Bloic Muisiriún Dearg", "block.minecraft.red_nether_brick_slab": "Leac Brící Dearga Ifrinn", "block.minecraft.red_nether_brick_stairs": "Staighre Brící Dearga Ifrinn", "block.minecraft.red_nether_brick_wall": "Balla Brící Dearga Ifrinn", "block.minecraft.red_nether_bricks": "Íochtarbhrící Dearga", "block.minecraft.red_sand": "Gaineamh Dearg", "block.minecraft.red_sandstone": "Gaineamhchloch Dhearg", "block.minecraft.red_sandstone_slab": "Leac Gaineamhchloiche Deirge", "block.minecraft.red_sandstone_stairs": "Staighre Gaineamhchloiche Deirge", "block.minecraft.red_sandstone_wall": "Balla Gaineamhchloiche Deirge", "block.minecraft.red_shulker_box": "Bosca Slíogadóra Dheirg", "block.minecraft.red_stained_glass": "Gloine Dhaite Dhearg", "block.minecraft.red_stained_glass_pane": "Pána Gloine Daite Deirge", "block.minecraft.red_terracotta": "Cré Bhruite Dhearg", "block.minecraft.red_tulip": "Tiúilip Dhearg", "block.minecraft.red_wool": "Olann Dhearg", "block.minecraft.redstone_block": "Bloc Deargchloiche", "block.minecraft.redstone_lamp": "Lampa Deargchloiche", "block.minecraft.redstone_ore": "Mian Deargchloiche", "block.minecraft.redstone_torch": "Tóirse Deargchloiche", "block.minecraft.redstone_wall_torch": "Tóirse Deargchloiche Balla", "block.minecraft.redstone_wire": "Sreang Dheargchloiche", "block.minecraft.repeater": "Athsheoltóir Deargchloiche", "block.minecraft.repeating_command_block": "Bloc Ordaithe Athfhillteach", "block.minecraft.rose_bush": "Rós", "block.minecraft.sand": "Gaineamh", "block.minecraft.sandstone": "Gaineamhchloch", "block.minecraft.sandstone_slab": "Leac Ghaineamhchloiche", "block.minecraft.sandstone_stairs": "Staighre Gaineamhchloiche", "block.minecraft.sandstone_wall": "Balla Gaineamhchloiche", "block.minecraft.scaffolding": "Scafall", "block.minecraft.sea_lantern": "Laindéar Farraige", "block.minecraft.sea_pickle": "Picil Mara", "block.minecraft.seagrass": "Féar Mara", "block.minecraft.shulker_box": "Bosca Slíogadóra", "block.minecraft.skeleton_skull": "Cloigeann Cnámharlaigh", "block.minecraft.skeleton_wall_skull": "Cloigeann Balla Chnámharlaigh", "block.minecraft.slime_block": "Bloc Slaim", "block.minecraft.smithing_table": "Bord Gabha", "block.minecraft.smoker": "Deatóir", "block.minecraft.smooth_quartz": "Ghrianchloiche Mhín", "block.minecraft.smooth_quartz_slab": "Leac Ghrianchloiche Míne", "block.minecraft.smooth_quartz_stairs": "Staighre Grianchloiche Míne", "block.minecraft.smooth_red_sandstone": "Gaineamhchloch Dhearg Mhín", "block.minecraft.smooth_red_sandstone_slab": "Leac Ghaineamhchloiche Deirge Míne", "block.minecraft.smooth_red_sandstone_stairs": "Staighre Gaineamhchloiche Deirge Míne", "block.minecraft.smooth_sandstone": "Gaineamhchloch Mhín", "block.minecraft.smooth_sandstone_slab": "Leac Ghaineamhchloiche Míne", "block.minecraft.smooth_sandstone_stairs": "Staighre Gaineamhchloiche Míne", "block.minecraft.smooth_stone": "Cloch Mhín", "block.minecraft.smooth_stone_slab": "Leac Chloiche Míne", "block.minecraft.snow": "Sneachta", "block.minecraft.snow_block": "Bloic Sneachta", "block.minecraft.soul_sand": "Gaineamh Anama", "block.minecraft.spawner": "Gineadóir", "block.minecraft.sponge": "Spúinse", "block.minecraft.spruce_button": "Cnaipe Sprúis", "block.minecraft.spruce_door": "Doras Sprúis", "block.minecraft.spruce_fence": "Claí Sprúis", "block.minecraft.spruce_fence_gate": "Geata Sprúis", "block.minecraft.spruce_leaves": "Duilleoga Sprúis", "block.minecraft.spruce_log": "Lomán Sprúis", "block.minecraft.spruce_planks": "Clár Sprúis", "block.minecraft.spruce_pressure_plate": "Brúphláta Sprúis", "block.minecraft.spruce_sapling": "Sprús Óg", "block.minecraft.spruce_sign": "Comhartha Sprúis", "block.minecraft.spruce_slab": "Leac Sprúis", "block.minecraft.spruce_stairs": "Staighre Sprúis", "block.minecraft.spruce_trapdoor": "Comhla Thógála Sprúis", "block.minecraft.spruce_wall_sign": "Comhartha Balla Sprúis", "block.minecraft.spruce_wood": "Adhmad Sprúis", "block.minecraft.sticky_piston": "Loine Greamaitheach", "block.minecraft.stone": "Cloch", "block.minecraft.stone_brick_slab": "Leac Brící Cloiche", "block.minecraft.stone_brick_stairs": "Staighre Bhríce Cloiche", "block.minecraft.stone_brick_wall": "Balla Brící Cloiche", "block.minecraft.stone_bricks": "Brící Cloiche", "block.minecraft.stone_button": "Cnaipe Cloiche", "block.minecraft.stone_pressure_plate": "Brúphláta Cloiche", "block.minecraft.stone_slab": "Leac Chloiche", "block.minecraft.stone_stairs": "Staighre Cloiche", "block.minecraft.stonecutter": "Gearrthóir Cloiche", "block.minecraft.stripped_acacia_log": "Lomán Acaicia", "block.minecraft.stripped_acacia_wood": "Adhmad Scafa Acaicia", "block.minecraft.stripped_birch_log": "Lomán Beithe", "block.minecraft.stripped_birch_wood": "Adhmad Scafa Beithe", "block.minecraft.stripped_dark_oak_log": "Lomán Darach Dhubh", "block.minecraft.stripped_dark_oak_wood": "Adhmad Scafa Darach Dhuibhe", "block.minecraft.stripped_jungle_log": "Lomán Dufaire", "block.minecraft.stripped_jungle_wood": "Adhmad Scafa Dufaire", "block.minecraft.stripped_oak_log": "Lomán Darach", "block.minecraft.stripped_oak_wood": "Lomán Darach Scafa", "block.minecraft.stripped_spruce_log": "Lomán Sprúis", "block.minecraft.stripped_spruce_wood": "Lomán Sprúis Scafa", "block.minecraft.structure_block": "Bloc Struchtúir", "block.minecraft.structure_void": "Folús Struchtúrach", "block.minecraft.sugar_cane": "Cána Siúcra", "block.minecraft.sunflower": "Lus na Gréine", "block.minecraft.sweet_berry_bush": "Tom Caor Milis", "block.minecraft.tall_grass": "Féar Ard", "block.minecraft.tall_seagrass": "Féar Mara Ard", "block.minecraft.terracotta": "Cré Bhruite", "block.minecraft.three_turtle_eggs": "Trí Ubh Thurtair", "block.minecraft.tnt": "TNT", "block.minecraft.torch": "Tóirse", "block.minecraft.trapped_chest": "Cófra Gaiste", "block.minecraft.tripwire": "Sreang Thuisle", "block.minecraft.tripwire_hook": "Crúca Shreang Tuisle", "block.minecraft.tube_coral": "Tiúbchoiréal", "block.minecraft.tube_coral_block": "Bloc Tiúbchoiréil", "block.minecraft.tube_coral_fan": "Fean Tiúbchoiréil", "block.minecraft.tube_coral_wall_fan": "Ballafhean Tiúbhchoiréil", "block.minecraft.turtle_egg": "Ubh Thurtair", "block.minecraft.two_turtle_eggs": "Dhá Ubh Thurtair", "block.minecraft.vine": "Féithleog", "block.minecraft.void_air": "Aer Folúis", "block.minecraft.wall_banner": "Bratach Balla", "block.minecraft.wall_torch": "Tóirse Balla", "block.minecraft.water": "Uisce", "block.minecraft.wet_sponge": "Spúinse Fliuch", "block.minecraft.wheat": "Barra Cruithneachta", "block.minecraft.white_banner": "Meirge Bán", "block.minecraft.white_bed": "Leaba Bhán", "block.minecraft.white_carpet": "Cairpéad Bán", "block.minecraft.white_concrete": "Stroighin Bhán", "block.minecraft.white_concrete_powder": "Púdar Stroighne Bán", "block.minecraft.white_glazed_terracotta": "Cré Ghlónraithe Bhán", "block.minecraft.white_shulker_box": "Bosca Slíogadóra Bháin", "block.minecraft.white_stained_glass": "Gloine Dhaite Bhán", "block.minecraft.white_stained_glass_pane": "Pána Gloine Daite Báine", "block.minecraft.white_terracotta": "Cré Bhruite Bhán", "block.minecraft.white_tulip": "Tiúilip Bhán", "block.minecraft.white_wool": "Olann Bhán", "block.minecraft.wither_rose": "Rós Wither", "block.minecraft.wither_skeleton_skull": "Cloigeann Cnámharlaigh Wither", "block.minecraft.wither_skeleton_wall_skull": "Cloigeann Cnámharlaigh Wither ar an mBalla", "block.minecraft.yellow_banner": "Meirge Buí", "block.minecraft.yellow_bed": "Leaba Bhuí", "block.minecraft.yellow_carpet": "Cairpéad Buí", "block.minecraft.yellow_concrete": "Stroighin Bhuí", "block.minecraft.yellow_concrete_powder": "Púdar Stroighne Buí", "block.minecraft.yellow_glazed_terracotta": "Cré Ghlónraithe Bhuí", "block.minecraft.yellow_shulker_box": "Bosca Slíogadóra Bhuí", "block.minecraft.yellow_stained_glass": "Gloine Dhaite Bhuí", "block.minecraft.yellow_stained_glass_pane": "Pána Gloine Daite Buí", "block.minecraft.yellow_terracotta": "Cré Bhruite Bhuí", "block.minecraft.yellow_wool": "Olann Bhuí", "block.minecraft.zombie_head": "Ceann Zombaí", "block.minecraft.zombie_wall_head": "Ceann Balla Zombaí", "book.byAuthor": "le %1s", "book.editTitle": "Teideal an Leabhair:", "book.finalizeButton": "Sínigh agus Dún", "book.finalizeWarning": "Tabhair faoi deara! Nuair a shíneoidh tú an leabhar, ní bheidh tú in ann é a athrú.", "book.generation.0": "Bunleabhar", "book.generation.1": "Cóip den bhunleabhar", "book.generation.2": "Cóip de chóip", "book.generation.3": "Cifleogach", "book.invalid.tag": "* Clib leabhair neamhbhailí *", "book.pageIndicator": "Leathanach %1s de %2s", "book.signButton": "Sínigh", "build.tooHigh": "Teorainn airde don tógáil: %s bloic", "chat.cannotSend": "Ní féidir teachtaireacht comhráite a sheoladh", "chat.coordinates": "%s, %s, %s", "chat.coordinates.tooltip": "Cliceáil le teileapórtáil", "chat.copy": "Cóipeáil don Ghearrthaisce", "chat.editBox": "comhrá", "chat.link.confirm": "An bhfuil tú cinnte gur mian leat an suíomh gréasáin seo a oscailt?", "chat.link.confirmTrusted": "Ar mhaith leath an nasc seo a oscailt nó é a chóipeáil chuig an gearrthaisce?", "chat.link.open": "Oscail i mbrabhsálaí", "chat.link.warning": "Ná hoscail naisc ó dhaoine nach bhfuil muinín agat astu!", "chat.type.admin": "[%s: %s]", "chat.type.advancement.challenge": "Chríochnaigh %s an dúshlán %s", "chat.type.advancement.goal": "Shroich %s an sprioc %s", "chat.type.advancement.task": "Bhain %s an fhorbairt %s amach", "chat.type.announcement": "[%s] %s", "chat.type.emote": "* %s %s", "chat.type.team.hover": "Teachtaireacht don fhoireann", "chat.type.team.sent": "-> %s <%s> %s", "chat.type.team.text": "%s <%s> %s", "chat.type.text": "<%s> %s", "chat.type.text.narrate": "Dúirt %s %s", "clear.failed.multiple": "Aimsíodh earraí ar bith ar %s imreoir", "clear.failed.single": "Aimsíodh earraí ar bith ar imreoir %s", "color.minecraft.black": "Dubh", "color.minecraft.blue": "Gorm", "color.minecraft.brown": "Donn", "color.minecraft.cyan": "Cian", "color.minecraft.gray": "Liath", "color.minecraft.green": "Uaine", "color.minecraft.light_blue": "Bánghorm", "color.minecraft.light_gray": "Fionnliath", "color.minecraft.lime": "Líomach", "color.minecraft.magenta": "Maigeanta", "color.minecraft.orange": "Oráisteach", "color.minecraft.pink": "Bándearg", "color.minecraft.purple": "Corcra", "color.minecraft.red": "Dearg", "color.minecraft.white": "Bán", "color.minecraft.yellow": "Buí", "command.context.here": "<--[HERE]", "command.exception": "Ní féidir le hordú a pharsáil: %s", "command.expected.separator": "Coinne le bánspás ag deireadh na hargóint, ach sonraí sraoilleach aimsithe", "command.failed": "Tharla earráid gan choinne nuair a rinneadh iarracht an t-ordú sin a chur i gcrích", "command.unknown.argument": "Argóint mhícheart le haghaidh an orduithe", "command.unknown.command": "Ordú anaithnid", "commands.advancement.advancementNotFound": "Ní bhfuarthas forbairt ar bith darb ainm '%1s'", "commands.advancement.criterionNotFound": "Níl an critéar '%2s' le fáil san fhorbairt %1s", "commands.advancement.grant.criterion.to.many.failure": "Níorbh fhéidir critéar '%s' na forbartha %s a bhronnadh ar %s imreoirí mar tá sé acu cheana", "commands.advancement.grant.criterion.to.many.success": "Bronnadh critéar '%s' na forbartha %s ar %s imreoirí", "commands.advancement.grant.criterion.to.one.failure": "Níorbh fhéidir critéar '%s' na forbartha %s a bhronnadh ar %s mar tá sí acu cheana", "commands.advancement.grant.criterion.to.one.success": "Bronnadh critéar '%s' na forbartha %s ar %s", "commands.advancement.grant.many.to.many.failure": "Níorbh fhéidir %s forbairtí a bhronnadh ar %s imreoirí mar tá sí acu cheana", "commands.advancement.grant.many.to.many.success": "Bronnadh %s forbairtí ar %s imreoirí", "commands.advancement.grant.many.to.one.failure": "Níorbh fhéidir %s forbairt a bhronnadh ar %s mar tá sí acu cheana", "commands.advancement.grant.many.to.one.success": "Bronnadh %s forbairt ar %s", "commands.advancement.grant.one.to.many.failure": "Níorbh fhéidir an fhorbairt %s a bhronnadh ar %s imreoirí mar tá sí acu cheana", "commands.advancement.grant.one.to.many.success": "Bronnadh an fhorbairt %s ar %s imreoirí", "commands.advancement.grant.one.to.one.failure": "Níorbh fhéidir an fhorbairt %s a bhronnadh ar %s mar tá sí acu cheana", "commands.advancement.grant.one.to.one.success": "Bronnadh an fhorbairt %s ar %s", "commands.advancement.revoke.criterion.to.many.failure": "Níorbh fhéidir critéar '%s' na forbartha %s a bhaint de %s imreoirí mar níl sé acu", "commands.advancement.revoke.criterion.to.many.success": "Baineadh critéar '%s' na forbartha %s de %s imreoirí", "commands.advancement.revoke.criterion.to.one.failure": "Níorbh fhéidir critéar '%s' na forbartha %s a bhaint de %s mar níl sé acu", "commands.advancement.revoke.criterion.to.one.success": "Baineadh critéar '%s' na forbartha %s de %s", "commands.advancement.revoke.many.to.many.failure": "Níorbh fhéidir %s forbairtí a bhaint de %s imreoirí mar níl siad acu", "commands.advancement.revoke.many.to.many.success": "Baineadh %s forbairtí de %s imreoirí", "commands.advancement.revoke.many.to.one.failure": "Níorbh fhéidir %s forbairtí a bhaint de %s mar níl siad acu", "commands.advancement.revoke.many.to.one.success": "Baineadh %s forbairtí de %s", "commands.advancement.revoke.one.to.many.failure": "Níorbh fhéidir an fhorbairt %s a bhaint de %s imreoirí mar níl sí acu", "commands.advancement.revoke.one.to.many.success": "Baineadh an fhorbairt %s de %s imreoirí", "commands.advancement.revoke.one.to.one.failure": "Níorbh fhéidir an fhorbairt %s a bhaint de %s mar níl sí acu", "commands.advancement.revoke.one.to.one.success": "Baineadh an fhorbairt %s de %s", "commands.ban.failed": "Níor athraíodh dada. Bhí cosc ar an t-imreoir sin cheana", "commands.ban.success": "Coisceadh %s: %s", "commands.banip.failed": "Níor athraíodh dada. Bhí cosc ar an IP sin cheana", "commands.banip.info": "Bain an cosc le %s imreoirí: %s", "commands.banip.invalid": "Seoladh IP neamhbhailí nó imreoir anaithnid", "commands.banip.success": "Coisceadh IP %s: %s", "commands.banlist.entry": "Chuir %2s cosc ar %1s: %3s", "commands.banlist.list": "Tá %s cosc:", "commands.banlist.none": "Tá cosc ar bith", "commands.bossbar.create.failed": "Tá basbharra ann cheana féin le ID '%s'", "commands.bossbar.create.success": "Cruthaíodh basbharra saincheaptha %s", "commands.bossbar.get.max": "Tá uasmhéid %s ag an mbasbharra saincheaptha %s", "commands.bossbar.get.players.none": "Níl imreoir ar bith ar líne faoi láthair ag an mbasbharra saincheaptha %s", "commands.bossbar.get.players.some": "Tá %2s imreoir ar líne faoi láthair ag an mbasbharra saincheaptha %1s: %3s", "commands.bossbar.get.value": "Tá luach %2s ag an mbasbharra saincheaptha %1s", "commands.bossbar.get.visible.hidden": "Tá an basbharra saincheaptha %s ceilte faoi láthair", "commands.bossbar.get.visible.visible": "Tá an basbharra saincheaptha %s faoi thaispeáint faoi láthair", "commands.bossbar.list.bars.none": "Níl aon bhasbharra saincheaptha i ngníomh", "commands.bossbar.list.bars.some": "Tá %s basbharra saincheaptha i gníomh: %s", "commands.bossbar.remove.success": "Baineadh basbharra saincheaptha %s", "commands.bossbar.set.color.success": "Athraíodh dath an bhasbharra shaincheaptha %s", "commands.bossbar.set.color.unchanged": "Athrú ar bith. Tá an dath cheana féin ag an mbasbharra", "commands.bossbar.set.max.success": "Athraíodh uasmhéid an bhasbharra saincheaptha %s go %s", "commands.bossbar.set.max.unchanged": "Athrú ar bith. Tá an uasmhéid cheana féin ag an mbasbharra", "commands.bossbar.set.name.success": "Athainmníodh an basbharra saincheaptha %s", "commands.bossbar.set.name.unchanged": "Athrú ar bith. Tá an ainm cheana féin ag an mbasbharra", "commands.bossbar.set.players.success.none": "Níl imreoir ar bith ag an mbasbharra saincheaptha %s", "commands.bossbar.set.players.success.some": "Tá %2s imreoir anois ag an mbasbharra saincheaptha %1s: %3s", "commands.bossbar.set.players.unchanged": "Athrú ar bith. Tá na himreoirí seo ar an mbasbharra cheana féin le duine ar bith a chur leo nó a bhaint astu", "commands.bossbar.set.style.success": "Athraíodh stíl an bhasbharra shaincheaptha %s", "commands.bossbar.set.style.unchanged": "Athrú ar bith. Tá an stíl cheana féin ag an mbasbharra", "commands.bossbar.set.value.success": "Athraíodh luach an bhasbharra shaincheaptha %s go %s", "commands.bossbar.set.value.unchanged": "Athrú ar bith. Tá an luach cheana féin ag an mbasbharra", "commands.bossbar.set.visibility.unchanged.hidden": "Athrú ar bith. Tá an basbharra ceilte cheana féin", "commands.bossbar.set.visibility.unchanged.visible": "Athrú ar bith. Tá an basbharra sofheicthe cheana féin", "commands.bossbar.set.visible.success.hidden": "Tá an basbharra saincheaptha %s ceilte anois", "commands.bossbar.set.visible.success.visible": "Tá an basbharra saincheaptha %s sofheicthe anois", "commands.bossbar.unknown": "Níl aon bhasbharra ann leis an ID '%s'", "commands.clear.success.multiple": "Baineadh %s earraí as %s imreoirí", "commands.clear.success.single": "Baineadh %s earraí d'imreoir %s", "commands.clear.test.multiple": "Aimsíodh %s earraí comhoiriúnach as %s imreoirí", "commands.clear.test.single": "Aimsíodh %s earraí comhoiriúnach d'imreoir %s", "commands.clone.failed": "Níor chlónáladh bloc ar bith", "commands.clone.overlap": "Ní féidir le forluí a bheith idir tionchar na faoinse agus an chinn scíbe", "commands.clone.success": "Clónáladh %s bloic go rathúil", "commands.clone.toobig": "An iomarca bloc sa cheantar sonraithe (uas %s, sonraithe %s)", "commands.data.block.get": "%s ar bhloc %s, %s, %s tar éis fachtóra méide %s, sin %s", "commands.data.block.invalid": "Ní aonán bloc é an bloc faoi sprioc", "commands.data.block.modified": "Athraíodh sonraí den bhloc %s, %s, %s", "commands.data.block.query": "Tá sonraí an bhloic %s, %s, %s a leanas: %s", "commands.data.entity.get": "%s ar %s tar éis fachtóir méide %s, sin %s", "commands.data.entity.invalid": "Ní féidir le sonraí imreora a athrú", "commands.data.entity.modified": "Athraíodh sonraí aonán do %s", "commands.data.entity.query": "Tá na sonraí aonáin seo a leanas ag %s: %s", "commands.data.get.invalid": "Ní féidir le %s a fháil; níl ach clibeanna uimhriúla amháin ceadaithe", "commands.data.get.multiple": "Ní ghlacann an argóint seo ach le haon luach NBT amháin", "commands.data.get.unknown": "Ní féidir le clib %s a fháil; níl clib ann", "commands.data.merge.failed": "Athrú ar bith, tá na luachanna cheana féin ag na hairíonna sonraithe", "commands.data.modify.expected_list": "Liosta a raibh ag súil leis, fuarthas: %s", "commands.data.modify.expected_object": "Rud a raibh ag súil leis, fuarthas: %s", "commands.data.modify.invalid_index": "Innéacs liosta mícheart: %s", "commands.datapack.disable.failed": "Níl an paca '%s' cumasaithe!", "commands.datapack.disable.success": "Díchumasaíodh paca sonraí %s", "commands.datapack.enable.failed": "Tá an paca '%s' cumasaithe cheana féin!", "commands.datapack.enable.success": "Cumasaíodh paca sonraí %s", "commands.datapack.list.available.none": "Níl paca sonraí ar bith le fáil", "commands.datapack.list.available.success": "Tá %s paca sonraí le fáil: %s", "commands.datapack.list.enabled.none": "Níl paca sonraí ar bith cumasaithe", "commands.datapack.list.enabled.success": "Tá %s paca sonraí cumasaithe: %s", "commands.datapack.unknown": "Paca sonraí anaithnid '%s'", "commands.debug.alreadyRunning": "Thosaigh an próifíleoir dífhabhtúcháin cheana", "commands.debug.notRunning": "Níor thosaigh an próifíleoir dífhabhtúcháin", "commands.debug.started": "Tosaigh próifíliú dífhabhtúcháin", "commands.debug.stopped": "Stopadh próifíliú dífhabhtúcháin tar éis %s soicind agus %s nóiméidín (%s nóiméidín sa tsoicind)", "commands.defaultgamemode.success": "Tá an mód cluiche réamhshocraithe %s anois", "commands.deop.failed": "Athrú ar bith. Ní oibreoir é an t-imreoir", "commands.deop.success": "Ní rinneadh %s ina n-oibreoir freastalaí", "commands.difficulty.failure": "Níor athraíodh an deacracht; tá sé cheana féin ar %s", "commands.difficulty.query": "Is %s í an deacracht", "commands.difficulty.success": "Tá an deacracht shocraithe anois ag %s", "commands.drop.no_held_items": "Níl an t-aonán in ann earra ar bith a choinneáil", "commands.drop.no_loot_table": "Níl bord creiche ag an aonán %s", "commands.drop.success.multiple": "Thit %s rud", "commands.drop.success.multiple_with_table": "Thit %s ón mbord creiche %s", "commands.drop.success.single": "Thit %s * %s", "commands.drop.success.single_with_table": "Thit %s * %s ón mbord creiche %s", "commands.effect.clear.everything.failed": "Níl aon éifeacht ar an sprioc a bhaineadh as", "commands.effect.clear.everything.success.multiple": "Gach éifeacht asbhainte ó %s spriocanna", "commands.effect.clear.everything.success.single": "Gach éifeacht asbhainte ó %s", "commands.effect.clear.specific.failed": "Níl an éifeacht iarrtha ag an sprioc", "commands.effect.clear.specific.success.multiple": "Éifeacht %s asbhainte ó %s spriocanna", "commands.effect.clear.specific.success.single": "Éifeacht %s asbhainte ó %s", "commands.effect.give.failed": "Ní rabhthas ábalta an éifeacht seo a chur i bhfeidhm (tá an sprioc slán ó éifeachtaí nó tá éifeacht níos láidre acu)", "commands.effect.give.success.multiple": "Éifeachtaí %s curtha i bhfeidhm ar %s spriocanna", "commands.effect.give.success.single": "Éifeacht %s curtha i bhfeidhm ar %s", "commands.enchant.failed": "Athrú ar bith. Níl aon earraí ag na spriocanna ina láimh nó ní féidir leis an asarlaí a chur i bhfeidhm", "commands.enchant.failed.entity": "Níl %s ina n-aonán bailí ar son an orduithe seo", "commands.enchant.failed.incompatible": "Ní féidir le %s an t-asarlaí sin a thacú", "commands.enchant.failed.itemless": "Níl earraí ina lámh ag %s", "commands.enchant.failed.level": "Is níos airde é %s ná an t-uasleibhéal de %s tacaithe ag an asarlaí sin", "commands.enchant.success.multiple": "Curadh asarlaí %s ar %s aonán", "commands.enchant.success.single": "Curadh asarlaí %s ar earraí de chuid %s", "commands.execute.blocks.toobig": "An iomarca bloc sa cheantar sonraithe (uas %s, sonraithe %s)", "commands.execute.conditional.fail": "Teipeadh an scrúdú", "commands.execute.conditional.fail_count": "Teipeadh an scrúdú, méid: %s", "commands.execute.conditional.pass": "Éiríodh leis an scrúdú", "commands.execute.conditional.pass_count": "Éiríodh leis an scrúdú, méid: %s", "commands.experience.add.levels.success.multiple": "Tugadh %s leibhéal taithí do %s imreoirí", "commands.experience.add.levels.success.single": "Tugadh %s leibhéal taithí do %s", "commands.experience.add.points.success.multiple": "Tugadh %s pointe taithí do %s imreoirí", "commands.experience.add.points.success.single": "Tugadh %s pointe taithí do %s", "commands.experience.query.levels": "Ta %2s leibhéal taithí ag %1s", "commands.experience.query.points": "Tá %2s pointí taithí ag %1s", "commands.experience.set.levels.success.multiple": "Socraíodh %s leibhéal taithí ar %s imreoirí", "commands.experience.set.levels.success.single": "Socraíodh %s leibhéal taithí ar %s", "commands.experience.set.points.invalid": "Ní féidir leis na pointí taithí a shocrú os cionn na huasmhéide do leibhéal reatha an imreora", "commands.experience.set.points.success.multiple": "Socraíodh %s pointí taithí ar %s imreoirí", "commands.experience.set.points.success.single": "Socraíodh %s pointí taithí ar %s", "commands.fill.failed": "Níor líonadh bloc ar bith", "commands.fill.success": "Líonadh %s bloc go rathúil", "commands.fill.toobig": "An iomarca bloc sa cheantar sonraithe (uas %s, sonraithe %s)", "commands.forceload.added.failure": "Níor mharcáladh smután ar bith le haghaidh lódála éigeantaí", "commands.forceload.added.multiple": "Marcáladh %s smután i %s, ó %s go %s le haghaidh lódála éigeantaí", "commands.forceload.added.none": "Ní bhfuarthas smután lódáilte go héigeantach i %s", "commands.forceload.added.single": "Marcáladh smután %s i %s le haghaidh lódála éigeantaí", "commands.forceload.list.multiple": "Fuarthas %s smután lódáilte go héigeantach i %s ag: %s", "commands.forceload.list.single": "Fuarthas smután lódáilte go héigeantach i %s ag: %s", "commands.forceload.query.failure": "Níl an smután ag %s i %s marcáilte le haghaidh lódála éigeantaí", "commands.forceload.query.success": "Tá an smután ag %s i %s marcáilte le haghaidh lódála éigeantaí", "commands.forceload.removed.all": "Dímharcáladh gach smután lódáilte go héigeantach i %s", "commands.forceload.removed.failure": "Níor baineadh smután ar bith den lódáil éigeantach", "commands.forceload.removed.multiple": "Dímharcáladh %s smután i %s ó %s go %s le haghaidh lódála éigeantaí", "commands.forceload.removed.single": "Dímharcáladh smután %s i %s le haghaidh lódála éigeantaí", "commands.forceload.toobig": "An iomarca smután sa limistéar sonraithe (%s an t-uasluach, %s sonraithe)", "commands.function.success.multiple": "Cuireadh %s orduithe i bhfeidhm ó %s feidhm", "commands.function.success.single": "Cuireadh %s orduithe i bhfeidhm ón fheidhm '%s'", "commands.gamemode.success.other": "Athraíodh mód cluiche %s go %s", "commands.gamemode.success.self": "Athraíodh do mhód cluiche féin go %s", "commands.gamerule.query": "Riail cluiche %s socraithe faoi láthair mar: %s", "commands.gamerule.set": "Riail cluiche %s socraithe anois mar: %s", "commands.give.success.multiple": "Tugadh %s %s chuig %s imreoirí", "commands.give.success.single": "Tugadh %s %s chuig %s", "commands.help.failed": "Ordú anaithnid nó cead in easnamh", "commands.kick.success": "Díbríodh %s: %s", "commands.kill.success.multiple": "Maraíodh %s aonáin", "commands.kill.success.single": "Scriosadh %s", "commands.list.players": "Tá %s den %s uasimreoirí ar líne: %s", "commands.locate.failed": "Ní féidir leis an struchtúr seo a aimsiú in aice láimhe", "commands.locate.success": "Tá in %s is gaire ag %s (%s bloc ar shiúl)", "commands.message.display.incoming": "Tugann %s cogar duit: %s", "commands.message.display.outgoing": "Tugann tú cogar do %s: %s", "commands.op.failed": "Athrú ar bith. Is oibreoir é cheana an t-imreoir", "commands.op.success": "Rinneadh %s ina n-oibreoir freastalaí", "commands.pardon.failed": "Níor athraíodh dada. Níl cosc ar an t-imreoir", "commands.pardon.success": "Maitheadh %s", "commands.pardonip.failed": "Níor athraíodh dada. Níl cosc ar an IP sin", "commands.pardonip.invalid": "Seoladh IP neamhbhailí", "commands.pardonip.success": "Maitheadh IP %s", "commands.particle.failed": "Ní raibh an gráinnín sofheicthe le duine ar bith", "commands.particle.success": "Cáithnín %s faoi thaispeánt", "commands.playsound.failed": "Tá an fhuaim ró-fhada le cloisteáil", "commands.playsound.success.multiple": "Seinneadh fuaim %s chuig %s imreoirí", "commands.playsound.success.single": "Seinneadh fuaim %s chuig %s", "commands.publish.alreadyPublished": "Tá cluiche ilimreortha óstáilte cheana féin ag an mport %s", "commands.publish.failed": "Ní féidir cluiche áitiúil a óstáil", "commands.publish.started": "Ag óstáil cluiche logánta ar phort %s", "commands.publish.success": "Tá cluiche ilimreortha óstáilte anois ag an mport %s", "commands.recipe.give.failed": "Oideas nua ar bith foghlamtha", "commands.recipe.give.success.multiple": "Díghlasaíodh %s oideas le %s imreoir", "commands.recipe.give.success.single": "Díghlasaíodh %s oideas do %s", "commands.recipe.take.failed": "Ní féidir le dearmad a rinne ar aon oideas", "commands.recipe.take.success.multiple": "Tógadh %s oideas as %s imreoir", "commands.recipe.take.success.single": "Tógadh %s oideas de %s", "commands.reload.success": "Ag athlódáil!", "commands.replaceitem.block.failed": "Ní coimeádán é an spriocbhloc seo", "commands.replaceitem.block.success": "Thángthas sliotán ag %s, %s, %s le %s ina áit", "commands.replaceitem.entity.failed": "Ní féidir le %s a chur i sliotán %s", "commands.replaceitem.entity.success.multiple": "Thángthas sliotán ar %s aonán le %s ina n-áit", "commands.replaceitem.entity.success.single": "Thángthas sliotán ar %s le %s ina áit", "commands.replaceitem.slot.inapplicable": "Níl sliotán %s ag an sprioc", "commands.save.alreadyOff": "Tá sábháil curtha ó fheidhm cheana", "commands.save.alreadyOn": "Tá sábháil curtha i bhfeidhm cheana", "commands.save.disabled": "Tá uath-shábháil díchumasaithe anois", "commands.save.enabled": "Tá uath-shábháil cumasaithe anois", "commands.save.failed": "Ní féidir leis an gcluiche a shábháil (an bhfuil do dhóthain spáis diosca agat?)", "commands.save.saving": "Ag sábháil an chluiche (fán nóiméad le do thoil!)", "commands.save.success": "Sábháladh an cluiche", "commands.schedule.created.function": "Feidhm pleanáilte '%s' ag %s nóiméidín ag am cluiche %s", "commands.schedule.created.tag": "Clib pleanáilte '%s' ag %s nóiméidín ag an cluiche %s", "commands.schedule.same_tick": "Ní féidir le pleanáil a dhéanamh leis an nóiméidín reatha", "commands.scoreboard.objectives.add.duplicate": "Tá aidhm ann cheana féin leis an ainm sin", "commands.scoreboard.objectives.add.longName": "Ní féidir le hainmneacha aidhme a bheith níos faide ná %s carachtar", "commands.scoreboard.objectives.add.success": "Cruthaíodh aidhm nua %s", "commands.scoreboard.objectives.display.alreadyEmpty": "Athrú ar bith. Is folamh é cheana an sliotán taispeána sin", "commands.scoreboard.objectives.display.alreadySet": "Athrú ar bith. Tá an aidhm sin léirithe cheana féin sa sliotán taispeána seo", "commands.scoreboard.objectives.display.cleared": "Glanadh aon aidhm sa sliotán taispeána %s", "commands.scoreboard.objectives.display.set": "Socraíodh sliotán taispeána %s don aidhm %s a léiriú", "commands.scoreboard.objectives.list.empty": "Níl aon aidhm ar bith", "commands.scoreboard.objectives.list.success": "Tá %s aidhm: %s", "commands.scoreboard.objectives.modify.displayname": "Athraíodh ainm taispeána don aidhm %s go %s", "commands.scoreboard.objectives.modify.rendertype": "Athraíodh sórt rindreála d'aidhm %s", "commands.scoreboard.objectives.remove.success": "Baineadh aidhm %s", "commands.scoreboard.players.add.success.multiple": "Cuireadh %s le %s do %s aonán", "commands.scoreboard.players.add.success.single": "Cuireadh %s le %s do %s (%s anois)", "commands.scoreboard.players.enable.failed": "Athrú ar bith. Is cumasaithe é cheana an truicear sin", "commands.scoreboard.players.enable.invalid": "Oibríonn Chumasaigh ar truicear-aidhm amháin", "commands.scoreboard.players.enable.success.multiple": "Cumasaíodh truicear %s do %s aonán", "commands.scoreboard.players.enable.success.single": "Truicear %s le haghaidh %s curtha i bhfeidhm", "commands.scoreboard.players.get.null": "Ní féidir le luach de %s le haghaidh %s a fháil: luach ar bith ann", "commands.scoreboard.players.get.success": "Tá %2s %3s ag %1s", "commands.scoreboard.players.list.empty": "Níl aon aonáin faoi rianú", "commands.scoreboard.players.list.entity.empty": "Níl scór ar bith ag %s a léiriú", "commands.scoreboard.players.list.entity.entry": "%s: %s", "commands.scoreboard.players.list.entity.success": "Tá %2s scór ag %1s:", "commands.scoreboard.players.list.success": "Tá %s aonán faoi rianú: %s", "commands.scoreboard.players.operation.success.multiple": "Nuashonraíodh %s do %s aonán", "commands.scoreboard.players.operation.success.single": "Socraigh %s do %s go %s", "commands.scoreboard.players.remove.success.multiple": "Baineadh %s as %s do %s aonán", "commands.scoreboard.players.remove.success.single": "Baineadh %s as %s do %s (%s anois)", "commands.scoreboard.players.reset.all.multiple": "Athshocraigh scóir uile do %s aonán", "commands.scoreboard.players.reset.all.single": "Athshocraigh scóir uile do %s", "commands.scoreboard.players.reset.specific.multiple": "Athshocraigh %s do %s aonán", "commands.scoreboard.players.reset.specific.single": "Athshocraigh %s do %s", "commands.scoreboard.players.set.success.multiple": "Socraigh %s do %s aonán go %s", "commands.scoreboard.players.set.success.single": "Socraigh %s do %s go %s", "commands.seed.success": "Síol: %s", "commands.setblock.failed": "Ní féidir leis an mbloc a chur", "commands.setblock.success": "Athraíodh an bloc ag %s, %s, %s", "commands.setidletimeout.success": "Is %s nóiméad é leathsheal an imreora léisciúil anois", "commands.setworldspawn.success": "Socraíodh ionad athionchollaithe an domhain go %s, %s, %s", "commands.spawnpoint.success.multiple": "Socraíodh an t-ionad athionchollaithe go %s, %s, %s le haghaidh %s imreoirí", "commands.spawnpoint.success.single": "Socraíodh an t-ionad athionchollaithe go %s, %s, %s le haghaidh %s", "commands.spreadplayers.failed.entities": "Ní féidir le %s aonán a leathadh thart ar %s, %s (an iomarca aonán sa spás - bain triail as leathadh %s ar uasmhéid)", "commands.spreadplayers.failed.teams": "Ní féidir le %s foireann a leathadh thart ar %s, %s (an iomarca aonán sa spás - bain triail as leathadh %s ar uasmhéid)", "commands.spreadplayers.success.entities": "Leath %s imreoirí timpeall ar %s, %s ag fad meánach le %s bloc eatarthu", "commands.spreadplayers.success.teams": "Leath %s foireann timpeall ar %s, %s ag fad meánach le %s bloc eatarthu", "commands.stop.stopping": "Ag stopadh an fhreastalaí", "commands.stopsound.success.source.any": "Stopadh gach fuaim '%s'", "commands.stopsound.success.source.sound": "Stopadh fuaim '%s' ar fhoinse '%s'", "commands.stopsound.success.sourceless.any": "Stopadh na fuaimeanna uile", "commands.stopsound.success.sourceless.sound": "Stopadh fuaim '%s'", "commands.summon.failed": "Ní féidir leis an t-aonán a ghairm", "commands.summon.success": "Gaireadh ar %s nua", "commands.tag.add.failed": "Tá clib cheana féin ar an sprioc nó tá an iomarca clibe aige", "commands.tag.add.success.multiple": "Cuireadh clib '%s' le %s aonán", "commands.tag.add.success.single": "Cuireadh clib '%s' le %s", "commands.tag.list.multiple.empty": "Níl aon chlib ar na %s aonán seo", "commands.tag.list.multiple.success": "Tá %2s clib in iomlán ag na %1s aonán: %3s", "commands.tag.list.single.empty": "Níl aon chlib ag %s", "commands.tag.list.single.success": "Tá %2s clib ag %1s: %3s", "commands.tag.remove.failed": "Níl an chlib seo ag an sprioc", "commands.tag.remove.success.multiple": "Baineadh clib '%s' de %s aonán", "commands.tag.remove.success.single": "Baineadh clib '%s' de %s", "commands.team.add.duplicate": "Tá foireann ann cheana féin leis an ainm sin", "commands.team.add.longName": "Ní féidir le ainmneacha foirne a bheith níos faide ná %s carachtar", "commands.team.add.success": "Cruthaíodh foireann %s", "commands.team.empty.success": "Baineadh %s ball den fhoireann %s", "commands.team.empty.unchanged": "Athrú ar bith. Tá an foireann folamh cheana", "commands.team.join.success.multiple": "Cuireadh %s ball le foireann %s", "commands.team.join.success.single": "Cuireadh %s le foireann %s", "commands.team.leave.success.multiple": "Baineadh %s ball as aon fhoireann", "commands.team.leave.success.single": "Baineadh %s as aon fhoireann", "commands.team.list.members.empty": "Níl aon bhall ar an bhfoireann %s", "commands.team.list.members.success": "Tá %2s ball ag an bhfoireann %1s: %3s", "commands.team.list.teams.empty": "Tá foireann ar bith", "commands.team.list.teams.success": "Tá %s foireann: %s", "commands.team.option.collisionRule.success": "Tá riail timpiste d'fhoireann %s \"%s\" anois", "commands.team.option.collisionRule.unchanged": "Athrú ar bith. Tá an luach sin ag an riail timpiste cheana", "commands.team.option.color.success": "Nuashonraíodh dath foirne %s go %s", "commands.team.option.color.unchanged": "Athrú ar bith. Tá an dath sin ag an bhfoireann sin cheana", "commands.team.option.deathMessageVisibility.success": "Tá léargas tuairisce bháis d'fhoireann %s \"%s\" anois", "commands.team.option.deathMessageVisibility.unchanged": "Athrú ar bith. Tá an luach sin ag an léargas tuairisce bháis cheana", "commands.team.option.friendlyfire.alreadyDisabled": "Athrú ar bith. Tá féinscaoileadh díchumasaithe cheana leis an bhfoireann sin", "commands.team.option.friendlyfire.alreadyEnabled": "Athrú ar bith. Tá féinscaoileadh cumasaithe cheana leis an bhfoireann sin", "commands.team.option.friendlyfire.disabled": "Díchumasaíodh féinscaoileadh le foireann %s", "commands.team.option.friendlyfire.enabled": "Cumasaíodh féinscaoileadh le foireann %s", "commands.team.option.name.success": "Nuashonraíodh ainm foirne %s", "commands.team.option.name.unchanged": "Athrú ar bith. Tá an t-ainm seo ag an bhfoireann sin cheana", "commands.team.option.nametagVisibility.success": "Tá léargas ainmchlibe d'fhoireann %s \"%s\" anois", "commands.team.option.nametagVisibility.unchanged": "Athrú ar bith. Tá an luach sin ag an léargas ainmchlibe cheana", "commands.team.option.prefix.success": "Socraíodh réimír foirne go %s", "commands.team.option.seeFriendlyInvisibles.alreadyDisabled": "Athrú ar bith. Ní féidir leis an bhfoireann sin comhimreoirí dofheicthe a fheiceáil cheana", "commands.team.option.seeFriendlyInvisibles.alreadyEnabled": "Athrú ar bith. Is féidir leis an bhfoireann sin comhimreoirí dofheicthe a fheiceáil cheana", "commands.team.option.seeFriendlyInvisibles.disabled": "Ní fhéidir le foireann %s comhimreoirí dofheicthe a fheiceáil a thuilleadh", "commands.team.option.seeFriendlyInvisibles.enabled": "Is féidir le foireann %s comhimreoirí dofheicthe a fheiceáil anois", "commands.team.option.suffix.success": "Socraíodh iarmhír foirne go %s", "commands.team.remove.success": "Baineadh foireann %s", "commands.teammsg.failed.noteam": "Caithfidh tú a bheith ar fhoireann chun teachtaireacht fhoirne a sheoladh", "commands.teleport.success.entity.multiple": "Teileapórtáladh %s aonán go %s", "commands.teleport.success.entity.single": "Teileapórtáladh %s go %s", "commands.teleport.success.location.multiple": "Teileapórtáladh %s aonán go %s, %s, %s", "commands.teleport.success.location.single": "Teileapórtáladh %s go %s,%s,%s", "commands.time.query": "Is é %s an t-am", "commands.time.set": "Socraíodh an t-am go %s", "commands.title.cleared.multiple": "Scriosadh teidil le %s imreoirí", "commands.title.cleared.single": "Scriosadh teidil le %s", "commands.title.reset.multiple": "Athshocraigh roghanna teidil le %s imreoirí", "commands.title.reset.single": "Athshocraigh roghanna teidil le %s", "commands.title.show.actionbar.multiple": "Tá teideal nua an ghníomhbharra le %s imreoirí léirithe", "commands.title.show.actionbar.single": "Tá teideal nua an ghníomhbharra le %s léirithe", "commands.title.show.subtitle.multiple": "Tá an fotheideal nua le %s imreoirí léirithe", "commands.title.show.subtitle.single": "Tá an fotheideal nua le %s léirithe", "commands.title.show.title.multiple": "Tá an teideal nua le %s imreoirí léirithe", "commands.title.show.title.single": "Tá an teideal nua le %s léirithe", "commands.title.times.multiple": "Athraíodh am léirithe an teidil le %s imreoirí", "commands.title.times.single": "Athraíodh am léirithe an teidil le %s", "commands.trigger.add.success": "%s tionscanta (curtha %s leis an méid)", "commands.trigger.failed.invalid": "Is féidir leat ach 'truicear'-aidhmeanna amháin a thionscnamh", "commands.trigger.failed.unprimed": "Ní féidir leis an aidhm seo a thionscnamh fós", "commands.trigger.set.success": "%s tionscanta (socraíodh méid go %s)", "commands.trigger.simple.success": "%s tionscanta", "commands.weather.set.clear": "Socraigh an aimsir ar gheal", "commands.weather.set.rain": "Socraigh an aimsir ar báisteach", "commands.weather.set.thunder": "Socraigh an aimsir ar báisteach & toirneach", "commands.whitelist.add.failed": "Tá an t-imreoir fós ar an mbánliosta", "commands.whitelist.add.success": "Cuireadh %s leis an liosta bán", "commands.whitelist.alreadyOff": "Níl an bánliosta air cheana féin", "commands.whitelist.alreadyOn": "Tá an bánliosta air cheana", "commands.whitelist.disabled": "Níl an bánliosta air anois", "commands.whitelist.enabled": "Tá an bánliosta air anois", "commands.whitelist.list": "Tá %s imreoirí ar an mbánliosta: %s", "commands.whitelist.none": "Níl imreoir ar bith ar an mbánliosta", "commands.whitelist.reloaded": "Athlódáladh an liosta bán", "commands.whitelist.remove.failed": "Níl an t-imreoir ar an mbánliosta", "commands.whitelist.remove.success": "Baineadh %s den liosta bán", "commands.worldborder.center.failed": "Athrú ar bith. Tá lár teorainn an domhain ann cheana féin", "commands.worldborder.center.success": "Socraigh lár teorainn an domhain go %s, %s", "commands.worldborder.damage.amount.failed": "Athrú ar bith. Tá an mhéid sin cheana féin ag dámaiste do theorainn an domhain", "commands.worldborder.damage.amount.success": "Socraigh am dámaste de theorann an domhain go %s soicind", "commands.worldborder.damage.buffer.failed": "Athrú ar bith. Tá anfad cheana féin ag an maolán damásite do theorainn an domhain", "commands.worldborder.damage.buffer.success": "Socraigh maolán damáiste de theorann an domhain go %s bloc", "commands.worldborder.get": "Tá teorann an domhain %s bloc le fad faoi láthair", "commands.worldborder.set.failed.big.": "Ní féidir le teorann an domhain a bheith níos mó ná 60,000,000 ar leathan", "commands.worldborder.set.failed.nochange": "Athrú ar bith. Is é an mhéid sin cheana é teorann an domhain", "commands.worldborder.set.failed.small.": "Ní féidir le teorann an domhain a bheith níos lú ná 1 bhloc ar leathan", "commands.worldborder.set.grow": "Tá teorann an domhain ag méadú go %s bloc le fad i rith %s soicind", "commands.worldborder.set.immediate": "Socraigh teorann an domhain go %s bloc le fad", "commands.worldborder.set.shrink": "Tá teorann an domhain ag leasú go %s bloc le fad i rith %s soicind", "commands.worldborder.warning.distance.failed": "Athrú ar bith. Tá an fad cheana féin ag teorainn an domhain", "commands.worldborder.warning.distance.success": "Socraigh fad rabhaidh de theorann an domhain go %s bloc", "commands.worldborder.warning.time.failed": "Athrú ar bith. Is é an mhéid ama cheana féin ag rabhadh de theorainn an domhan", "commands.worldborder.warning.time.success": "Socraigh am rabhaidh de theorann an domhain go %s soicind", "connect.aborted": "Cuirtear deireadh leis", "connect.authorizing": "Ag logáil isteach...", "connect.connecting": "Ag ceangal leis an bhfreastalaí...", "connect.encrypting": "Ag criptiú...", "connect.failed": "Theip ar cheangal leis an bhfreastalaí", "connect.joining": "Ag dul isteach sa domhan...", "connect.negotiating": "Ag déanadh idirbheartaíochta...", "container.barrel": "Bairille", "container.beacon": "Rabhcán", "container.blast_furnace": "Foirnéis Soinneáin", "container.brewing": "Seastán Grúdaireacht", "container.cartography_table": "Bord Cartagrafaíochta", "container.chest": "Cófra", "container.chestDouble": "Cófra Mór", "container.crafting": "Ceardaíocht", "container.creative": "Roghnú Earra", "container.dispenser": "Teilgeoir", "container.dropper": "Dáilleoir", "container.enchant": "Asarlaíocht", "container.enchant.clue": "%s . . . ?", "container.enchant.lapis.many": "%s Bloic Lapis Lazuli", "container.enchant.lapis.one": "Bloc amháin Lapis Lazuli", "container.enchant.level.many": "%s Leibhéil Asarlaíochta", "container.enchant.level.one": "Leibhéal amháin Asarlaíochta", "container.enchant.level.requirement": "Leibhéal de dhíth: %s", "container.enderchest": "Cófra na Críche", "container.furnace": "Foirnéis", "container.grindstone_title": "Cóiriú agus draíocht a bhriseadh", "container.hopper": "Crannóg Earraí", "container.inventory": "Fardal", "container.isLocked": "%s faoi ghlas!", "container.lectern": "Léachtán", "container.loom": "Seol", "container.repair": "Deisigh & Ainmnigh", "container.repair.cost": "Costas Asarlaíochta: %1s", "container.repair.expensive": "Ró-chostasach!", "container.shulkerBox": "Bosca Slíogadóra", "container.shulkerBox.more": "agus %s eile...", "container.smoker": "Deatóir", "container.spectatorCantOpen": "Ní féidir é a oscailt. Níor gineadh an chreach fós.", "container.stonecutter": "Gearrthóir Cloiche", "controls.reset": "Athshocraigh", "controls.resetAll": "Athshocraigh Eochracha", "controls.title": "Rialtáin", "createWorld.customize.buffet.biome": "Roghnaigh bithóm le do thoil", "createWorld.customize.buffet.generator": "Roghnaigh cineál gineadóra le do thoil", "createWorld.customize.buffet.generatortype": "Gineadóir domhain:", "createWorld.customize.buffet.title": "Saincheapadh Dhomhan Buifé", "createWorld.customize.custom.baseSize": "Bun-méid Doimhneachta", "createWorld.customize.custom.biomeDepthOffset": "Taobhrianadh Doimhneacht Bithóim", "createWorld.customize.custom.biomeDepthWeight": "Treise Doimhneacht Bithóim", "createWorld.customize.custom.biomeScaleOffset": "Taobhrianadh Scála Bithóim", "createWorld.customize.custom.biomeScaleWeight": "Treise Scála Bithóim", "createWorld.customize.custom.biomeSize": "Méid Bithóim", "createWorld.customize.custom.center": "Lárairde", "createWorld.customize.custom.confirm1": "Forscríobhfar do shocruithe reatha", "createWorld.customize.custom.confirm2": "agus ní féidir iad a athshlánú.", "createWorld.customize.custom.confirmTitle": "Rabhadh!", "createWorld.customize.custom.coordinateScale": "Scála Cothrománach", "createWorld.customize.custom.count": "Iarrachtaí Giniúna", "createWorld.customize.custom.defaults": "Réamhshocruithe", "createWorld.customize.custom.depthNoiseScaleExponent": "Easpónant Thorann Doimhneachta", "createWorld.customize.custom.depthNoiseScaleX": "Scála Torann Doimhneachta X", "createWorld.customize.custom.depthNoiseScaleZ": "Scála Torann Doimhneachta Z", "createWorld.customize.custom.dungeonChance": "Uimhir Doinsiún", "createWorld.customize.custom.fixedBiome": "Bithóm", "createWorld.customize.custom.heightScale": "Scála Ingearach", "createWorld.customize.custom.lavaLakeChance": "Teirce Locha Laibhe", "createWorld.customize.custom.lowerLimitScale": "Scála Íosteorainn", "createWorld.customize.custom.mainNoiseScaleX": "Scála Príomhthorainn X", "createWorld.customize.custom.mainNoiseScaleY": "Scála Príomhthorainn Y", "createWorld.customize.custom.mainNoiseScaleZ": "Scála Príomhthorainn Z", "createWorld.customize.custom.maxHeight": "Uasairde", "createWorld.customize.custom.minHeight": "Íosairde", "createWorld.customize.custom.next": "Lch Eile", "createWorld.customize.custom.page0": "Socruithe Bunúsacha", "createWorld.customize.custom.page1": "Socruithe Mianta", "createWorld.customize.custom.page2": "Ardsocruithe (Úsáideoirí Saineolaíocha Amháin!)", "createWorld.customize.custom.page3": "Ardsocruithe Eile (Úsáideoirí Saineolaíocha Amháin!)", "createWorld.customize.custom.preset.caveChaos": "Uaimheanna an Anoird", "createWorld.customize.custom.preset.caveDelight": "Áthas an Uaimheadóra", "createWorld.customize.custom.preset.drought": "Triomach", "createWorld.customize.custom.preset.goodLuck": "Ádh Mór", "createWorld.customize.custom.preset.isleLand": "Tír na nOileán", "createWorld.customize.custom.preset.mountains": "Sléibhte Neimhe", "createWorld.customize.custom.preset.waterWorld": "Dobhardhomhan", "createWorld.customize.custom.presets": "Réamhshocruithe", "createWorld.customize.custom.presets.title": "Socraigh Réamhshocruithe Domhan", "createWorld.customize.custom.prev": "Lch Roimhe", "createWorld.customize.custom.randomize": "Randamaigh", "createWorld.customize.custom.riverSize": "Méid Abhann", "createWorld.customize.custom.seaLevel": "Leibhéal na Mara", "createWorld.customize.custom.size": "Méid Giniúna", "createWorld.customize.custom.spread": "Airde Scaipthe", "createWorld.customize.custom.stretchY": "Síneadh Ingearach", "createWorld.customize.custom.upperLimitScale": "Scála Uasteorainn", "createWorld.customize.custom.useCaves": "Pluaiseanna", "createWorld.customize.custom.useDungeons": "Doinsiúin", "createWorld.customize.custom.useLavaLakes": "Locha Laibhe", "createWorld.customize.custom.useLavaOceans": "Aigéin Laibhe", "createWorld.customize.custom.useMansions": "Árais na gCoillearnach", "createWorld.customize.custom.useMineShafts": "Sloic Mhianaigh", "createWorld.customize.custom.useMonuments": "Séadchomharthaí Aigéin", "createWorld.customize.custom.useOceanRuins": "Fothracha Aigéin", "createWorld.customize.custom.useRavines": "Ailteanna", "createWorld.customize.custom.useStrongholds": "Daingin", "createWorld.customize.custom.useTemples": "Teampaill", "createWorld.customize.custom.useVillages": "Sráidbhailte", "createWorld.customize.custom.useWaterLakes": "Locha Uisce", "createWorld.customize.custom.waterLakeChance": "Teirce Locha Uisce", "createWorld.customize.flat.height": "Airde", "createWorld.customize.flat.layer": "%s", "createWorld.customize.flat.layer.bottom": "Bun - %s", "createWorld.customize.flat.layer.top": "Barr - %s", "createWorld.customize.flat.removeLayer": "Bain Scair De", "createWorld.customize.flat.tile": "Ábhar na Scaire", "createWorld.customize.flat.title": "Saincheapadh Domhain Shárchothroim", "createWorld.customize.preset.bottomless_pit": "Poll Duibheagáin", "createWorld.customize.preset.classic_flat": "Cothrom Bunúsach", "createWorld.customize.preset.desert": "Fásach", "createWorld.customize.preset.overworld": "Barrdhomhain", "createWorld.customize.preset.redstone_ready": "An Ré Deargchloiche", "createWorld.customize.preset.snowy_kingdom": "Ríocht an Sneachta", "createWorld.customize.preset.the_void": "An Folús", "createWorld.customize.preset.tunnelers_dream": "Aisling an Tochaltóra", "createWorld.customize.preset.water_world": "Dobhardhomhan", "createWorld.customize.presets": "Réamhshocruithe", "createWorld.customize.presets.list": "Nó, seo duit roinnt réamhshocruithe a rinne muid roimh ré!", "createWorld.customize.presets.select": "Úsáid an Réamhshocrú", "createWorld.customize.presets.share": "Ar mhaith leath do réamhshocrú a roinnt? Úsáid an bosca thíos!", "createWorld.customize.presets.title": "Roghnaigh Réamhshocrú", "death.attack.anvil": "Thit inneoin ar %1s agus bascadh í/é", "death.attack.anvil.player": "Bhí %1s brúite faoi inneoin atá ag titim nuair a throideann siad le %2s", "death.attack.arrow": "Lámhach %2s %1s", "death.attack.arrow.item": "Lámhach %2s %1s le %3s", "death.attack.cactus": "Fuair %1s bás den phriocadh", "death.attack.cactus.player": "Bhuail %1s i gcoinne cachtais agus é/í ag iarraidh éalú ó %2s", "death.attack.cramming": "Róbhrúdh %1s", "death.attack.cramming.player": "Bhí %1s brúite ag %2s", "death.attack.dragonBreath": "Róstadh %1s in anáil dragain", "death.attack.dragonBreath.player": "Bhí %1s leáite i dtine dragain ag %2s", "death.attack.drown": "Bádh %1s", "death.attack.drown.player": "Bádh %1s agus é/í ag iarraidh éalú ó %2s", "death.attack.even_more_magic": "Maraíodh %1s le níos mó draíocht fós", "death.attack.explosion": "Phléasc %1s", "death.attack.explosion.player": "Phléasc %2s %1s", "death.attack.explosion.player.item": "Phléasc %2s %1s ina smionagar le %3s", "death.attack.fall": "Bhuail %1s an talamh go ró-throm", "death.attack.fall.player": "Bhuail %1s an talamh go crua ag iarraidh éalú ó %2s", "death.attack.fallingBlock": "Thit bloc ar %1s agus bascadh í/é", "death.attack.fallingBlock.player": "Bhí %1s brúite faoi bloc atá ag titim nuair a throideann siad le %2s", "death.attack.fireball": "Mharaigh %2s %1s le caor thine", "death.attack.fireball.item": "Mharaigh %2s %1s le caor thine agus %3s", "death.attack.fireworks": "D'imigh %1s de phléasc", "death.attack.fireworks.player": "Las %1s thar cionn mar thine ealaíne nuair a throideann siad le %2s", "death.attack.flyIntoWall": "Fuair %1s taithí ar fhuinneamh cinéiteach", "death.attack.flyIntoWall.player": "Fuair %1s taithí ar fuinneamh cinéiteach ag iarraidh éalú ó %2s", "death.attack.generic": "Fuair %1s bás", "death.attack.generic.player": "Mharaigh %2s %1s", "death.attack.hotFloor": "Faigheann %1s amach go mbeadh laibhe é an t-urlár", "death.attack.hotFloor.player": "Shiúil %1s isteach sa teorainn chomhraic mar gheall ar %2s", "death.attack.inFire": "D'imigh %1s in aon bhladhm amháin", "death.attack.inFire.player": "Shiúil %1s isteach sa tine agus é/í ag troid le %2s", "death.attack.inWall": "Plúchadh %1s i mballa", "death.attack.inWall.player": "Plúchadh %1s i mballa nuair a throideann siad le %2s", "death.attack.indirectMagic": "Mharaigh %2s %1s leis an draíocht", "death.attack.indirectMagic.item": "Mharaigh %2s %1s le %3s", "death.attack.lava": "Thug %1s iarracht ar snámh i laibhe", "death.attack.lava.player": "Thug %1s iarracht ar snámh i laibhe chun éalú ó %2s", "death.attack.lightningBolt": "Bhuail splanc thintrí %1s", "death.attack.lightningBolt.player": "Bhí %1s buailte le tintreach nuair a throideann siad le %2s", "death.attack.magic": "Maraíodh %1s leis an draíocht", "death.attack.message_too_long": "Déanta na fírinne, bhí an teachtaireacht rófhada le soláthar ina iomlán. Tá brón orainn. Seo é leagan gan fhormáidiú: %s", "death.attack.mob": "Bhásaigh %2s %1s", "death.attack.mob.item": "Bhásaigh %2s %1s le %3s", "death.attack.netherBed.link": "Dearadh Cluiche Intinneach", "death.attack.netherBed.message": "Mharaigh %2s %1s", "death.attack.onFire": "Dódh beo beathach %1s", "death.attack.onFire.player": "Dódh %1s ina smól agus é/í ag troid le %2s", "death.attack.outOfWorld": "Thit %1s amach as an domhan", "death.attack.outOfWorld.player": "Níor mhaith le %1s a bheith ina saol sa domhan céanna le %2s", "death.attack.player": "Chuir %1s bás ar %2s", "death.attack.player.item": "Bhásaigh %2s %1s le %3s", "death.attack.starve": "Fuair %1s bás den ocras", "death.attack.starve.player": "Fuair %1s bás den ocras nuair a throideann siad le %2s", "death.attack.sweetBerryBush": "Maraíodh %1s le priocadh ó chrann caora milse", "death.attack.sweetBerryBush.player": "Phrioc tom caor milis an t-anam as %1s agus é/í ag iarraidh éalú ó %2s", "death.attack.thorns": "Maraíodh %1s agus é/í ag iarraidh %2s a ghortú", "death.attack.thorns.item": "Fuair %1s bás le %3s nuair a bhí siad ag iarradh %2s á ngortú", "death.attack.thrown": "Ghread %2s %1s", "death.attack.thrown.item": "Ghread %2s %1s le %3s", "death.attack.trident": "Bhí %1s sáite ag %2s", "death.attack.trident.item": "Bhí %1s sáite ag %2s le %3s", "death.attack.wither": "Seargadh %1s", "death.attack.wither.player": "Díscíodh %1s i dtroid le %2s", "death.fell.accident.generic": "Thit %1s ó hairde mhór", "death.fell.accident.ladder": "Thit %1s de dréimire", "death.fell.accident.vines": "Thit %1s d'fhéithleog éigin", "death.fell.accident.water": "Thit %1s amach as an uisce", "death.fell.assist": "Dhaor %2s %1s chun titime", "death.fell.assist.item": "Dhaor %2s %1s chun titime le %3s", "death.fell.finish": "Thit %1s rófhada ar fad agus thug %2s buille scoir dó/di", "death.fell.finish.item": "Thit %1s rófhada ar fad agus thug %2s buille scoir dó/di le %3s", "death.fell.killer": "Daoradh %1s chun titime", "deathScreen.deleteWorld": "Scrios domhan", "deathScreen.leaveServer": "Fág an freastalaí", "deathScreen.quit.confirm": "An bhfuil tú cinnte gur maith leat scoradh den chluiche?", "deathScreen.respawn": "Athionchollaigh", "deathScreen.score": "Scór", "deathScreen.spectate": "Bí i do bhreathnóir", "deathScreen.title": "Fuair tú bás!", "deathScreen.title.hardcore": "Cluiche thart!", "deathScreen.titleScreen": "Scáileán Teidil", "debug.advanced_tooltips.help": "F3 + H = Ardnodanna uirlise", "debug.advanced_tooltips.off": "Ardnodanna uirlise: ceilte", "debug.advanced_tooltips.on": "Ardnodanna uirlise: léirithe", "debug.chunk_boundaries.help": "F3 + G = Taispeáin teorainneacha smután", "debug.chunk_boundaries.off": "Teorainneacha an smutáin: ceilte", "debug.chunk_boundaries.on": "Teorainneacha an smutáin: infheicthe", "debug.clear_chat.help": "F3 + D = Glan comhrá", "debug.copy_location.help": "F3 + C = Cóipeáil ionad mar ordú /tp, brú ar F3 + C don chluiche a chliseadh", "debug.copy_location.message": "Ionad cóipeáilte ar ghearrthaisce", "debug.crash.message": "F3 + C faoi bhrú. Clisfear an cluiche mura scaoiltear iad.", "debug.crash.warning": "Cliseadh sa %s...", "debug.creative_spectator.error": "Ní rabhthas ábalta mód cluiche a athrú, cead in easnamh", "debug.creative_spectator.help": "F3 + N = Cúrsáil idir cruthaitheach <-> féachadóir", "debug.cycle_renderdistance.help": "F3 + F = Cúrsáil trí fhad rindreála (brúigh Iomlaoid agus droim a chur ar ais)", "debug.cycle_renderdistance.message": "Fad Rindreála: %s", "debug.help.help": "F3 + Q = Léirigh an liosta seo", "debug.help.message": "Ceangail na gClé:", "debug.inspect.client.block": "Sonraí bloic cóipeáilte ó thaobh an chliaint ar ghearrthaisce", "debug.inspect.client.entity": "Sonraí aonáin cóipeáilte ó thaobh an chliaint ar ghearrthaisce", "debug.inspect.help": "F3 + I = Cóipeáil aonán nó sonraí bloic ar ghearrthaisce", "debug.inspect.server.block": "Sonraí bloic cóipeáilte ó thaobh an fhreastalaí ar ghearrthaisce", "debug.inspect.server.entity": "Sonraí aonáin cóipeáilte ó thaobh an fhreastalaí ar ghearrthaisce", "debug.pause.help": "F3 + Esc = Cuir an cluiche ar sos gan an roghchlár (más féidir)", "debug.pause_focus.help": "F3 + P = Cur sos nuair a chailltear fócas", "debug.pause_focus.off": "Sos tar éis caillte fócais: díchumasaithe", "debug.pause_focus.on": "Sos tar éis caillte fócais: cumasaithe", "debug.prefix": "[Debug]:", "debug.reload_chunks.help": "F3 + A = Athlódáil smutáin", "debug.reload_chunks.message": "Ag athlódáil gach smután", "debug.reload_resourcepacks.help": "F3 + T = Athlódáil pacáistí acmhainní", "debug.reload_resourcepacks.message": "Athlódáladh pacáistí acmhainní", "debug.show_hitboxes.help": "F3 + B = Léirigh bualbhoscaí", "debug.show_hitboxes.off": "Bualbhoscaí: ceilte", "debug.show_hitboxes.on": "Bualbhoscaí: léirithe", "demo.day.1": "Mairfidh an leagan taispeána seo cúig lá cluiche, déan do dhícheall!", "demo.day.2": "Lá a Dó", "demo.day.3": "Lá a Trí", "demo.day.4": "Lá a Ceathair", "demo.day.5": "Seo é do lá deireanach!", "demo.day.6": "Chuaigh tú tríd do cúigiú lá, bain úsáid as %s chun íomha de do chruthú a shábháil", "demo.day.warning": "Tá d'am beagnach istigh!", "demo.demoExpired": "Tá an t-am taispeána thart!", "demo.help.buy": "Ceannaigh Anois!", "demo.help.fullWrapped": "Mairfidh an leagan taispeána seo ar feadh 5 lá cluiche (thart ar uair agus 40 nóiméad fíor-ama). Féach “Buanna” le haghaidh leideanna! Bain taitneamh as!", "demo.help.inventory": "Úsáid %1s chun d'fhardal a oscailt", "demo.help.jump": "Léim trí bhrú ar %1s", "demo.help.later": "Lean leis an gcluiche!", "demo.help.movement": "Úsáid %1s, %2s, %3s, %4s agus an luch chun bogadh thart", "demo.help.movementMouse": "Bain úsáid as an luch le breathnú tharat", "demo.help.movementShort": "Bog trí bhrú ar %1s, %2s, %3s, %4s", "demo.help.title": "Mód Taispeána Minecraft", "demo.remainingTime": "Am fágtha: %s", "demo.reminder": "Tá an t-am taispeána thart, ceannaigh an cluiche chun leanúint ar aghaidh nó cruthaigh domhan nua!", "difficulty.lock.question": "An bhfuil tú cinnte gur maith leat deacracht an domhain seo a ghlasáil? Socrófar deacracht an domhain seo go %1s agus ní bheidh tú in ann í a athrú choíche.", "difficulty.lock.title": "Glasáil Deacracht", "disconnect.closed": "Ceangal dúnta", "disconnect.disconnected": "Dhícheangail an Freastalaí thú", "disconnect.endOfStream": "Deireadh an tsrutha", "disconnect.genericReason": "%s", "disconnect.kicked": "Díbeartha den chluiche", "disconnect.loginFailed": "Theip ar logáil isteach", "disconnect.loginFailedInfo": "Theip ar logáil isteach: %s", "disconnect.loginFailedInfo.invalidSession": "Seisiún neamhbhailí (Atosaigh an cluiche agus an lainseálaí)", "disconnect.loginFailedInfo.serversUnavailable": "Tá na freastalaithe fíordheimhniúcháin as líne faoi láthair le haghaidh cothabhála.", "disconnect.lost": "Ceangal Caillte", "disconnect.overflow": "Róshreabhadh maoláin", "disconnect.quitting": "Ag scor", "disconnect.spam": "Díbeartha de bharr sheoladh turscair", "disconnect.timeout": "Thar am", "effect.effectNotFound": "Éifeacht anaithnid: %s", "effect.minecraft.absorption": "Ionsúchán", "effect.minecraft.bad_omen": "Drochthuar", "effect.minecraft.blindness": "Daille", "effect.minecraft.conduit_power": "Cumhacht Seolphíobáin", "effect.minecraft.dolphins_grace": "Grástúlacht na Deilfe", "effect.minecraft.fire_resistance": "Dó-obacht", "effect.minecraft.glowing": "Lonrú", "effect.minecraft.haste": "Deifir", "effect.minecraft.health_boost": "Neartú Sláinte", "effect.minecraft.hero_of_the_village": "Laoch an tSráidbhaile", "effect.minecraft.hunger": "Ocras", "effect.minecraft.instant_damage": "Damáiste Láithreach", "effect.minecraft.instant_health": "Leigheas Láithreach", "effect.minecraft.invisibility": "Dofheictheacht", "effect.minecraft.jump_boost": "Neartú Léime", "effect.minecraft.levitation": "Eadarbhuasú", "effect.minecraft.luck": "Ádh", "effect.minecraft.mining_fatigue": "Tuirse Mianadóireachta", "effect.minecraft.nausea": "Masmas", "effect.minecraft.night_vision": "Radharc san Oíche", "effect.minecraft.poison": "Nimh", "effect.minecraft.regeneration": "Athghiniúint", "effect.minecraft.resistance": "Friotaíocht", "effect.minecraft.saturation": "Sáithiúchán", "effect.minecraft.slow_falling": "Mallthitim", "effect.minecraft.slowness": "Moille", "effect.minecraft.speed": "Luas", "effect.minecraft.strength": "Neart", "effect.minecraft.unluck": "Mí-ádh", "effect.minecraft.water_breathing": "Análú in Uisce", "effect.minecraft.weakness": "Laige", "effect.minecraft.wither": "Seargthóir", "effect.none": "Gan éifeacht i bhfeidhm", "enchantment.level.1": "I", "enchantment.level.10": "X", "enchantment.level.2": "II", "enchantment.level.3": "III", "enchantment.level.4": "IV", "enchantment.level.5": "V", "enchantment.level.6": "VI", "enchantment.level.7": "VII", "enchantment.level.8": "VIII", "enchantment.level.9": "IX", "enchantment.minecraft.aqua_affinity": "Báúlacht Uisce", "enchantment.minecraft.bane_of_arthropods": "Milleadh na nArtrapód", "enchantment.minecraft.binding_curse": "Mallacht an Cheangail", "enchantment.minecraft.blast_protection": "Cosaint ar Phléasc", "enchantment.minecraft.channeling": "Díriú", "enchantment.minecraft.depth_strider": "Coisí an Duibheagáin", "enchantment.minecraft.efficiency": "Éifeachtúlacht", "enchantment.minecraft.feather_falling": "Titim mar Chleite", "enchantment.minecraft.fire_aspect": "Dreach Dóite", "enchantment.minecraft.fire_protection": "Cosaint ar Thine", "enchantment.minecraft.flame": "Lasair", "enchantment.minecraft.fortune": "Rathúnas", "enchantment.minecraft.frost_walker": "Coisí an tSeaca", "enchantment.minecraft.impaling": "Sá", "enchantment.minecraft.infinity": "Éigríoch", "enchantment.minecraft.knockback": "Cnag Siar", "enchantment.minecraft.looting": "Creachadóireacht", "enchantment.minecraft.loyalty": "Dílseacht", "enchantment.minecraft.luck_of_the_sea": "Ádh na Mara", "enchantment.minecraft.lure": "Baoite", "enchantment.minecraft.mending": "Deisiúchán", "enchantment.minecraft.multishot": "Trí Urchar", "enchantment.minecraft.piercing": "Polladh", "enchantment.minecraft.power": "Cumhacht", "enchantment.minecraft.projectile_protection": "Cosaint ar Dhiúracáin", "enchantment.minecraft.protection": "Cosaint", "enchantment.minecraft.punch": "Bualadh", "enchantment.minecraft.quick_charge": "Lódáil Tapaidh", "enchantment.minecraft.respiration": "Análú", "enchantment.minecraft.riptide": "Sruth Cuilitheála", "enchantment.minecraft.sharpness": "Géire", "enchantment.minecraft.silk_touch": "Fíneáltacht", "enchantment.minecraft.smite": "Treascair", "enchantment.minecraft.sweeping": "Scuabadh Géar", "enchantment.minecraft.thorns": "Dealga", "enchantment.minecraft.unbreaking": "Dobhriste", "enchantment.minecraft.vanishing_curse": "Mallacht an Neamhbhuaine", "enchantment.unknown": "Asarlaí anaithnid: %s", "entity.minecraft.area_effect_cloud": "Néal Tionchair Áitiúil", "entity.minecraft.armor_stand": "Seastán Cathéide", "entity.minecraft.arrow": "Saighead", "entity.minecraft.bat": "Ialtóg", "entity.minecraft.blaze": "Lasaire", "entity.minecraft.boat": "Bád", "entity.minecraft.cat": "Cat", "entity.minecraft.cave_spider": "Damhán Alla Pluaise", "entity.minecraft.chest_minecart": "Cairt Mianaigh le Cófra", "entity.minecraft.chicken": "Sicín", "entity.minecraft.cod": "Trosc", "entity.minecraft.command_block_minecart": "Cairt Mianaigh le Bloc Ordaithe", "entity.minecraft.cow": "Bó", "entity.minecraft.creeper": "Téaltóir", "entity.minecraft.dolphin": "Deilf", "entity.minecraft.donkey": "Asal", "entity.minecraft.dragon_fireball": "Caor Thine an Dragain", "entity.minecraft.drowned": "Báiteach", "entity.minecraft.egg": "Ubh Caite", "entity.minecraft.elder_guardian": "Coimeádaí Sinsearach", "entity.minecraft.end_crystal": "Criostal na Críche", "entity.minecraft.ender_dragon": "Dragan na Críche", "entity.minecraft.ender_pearl": "Péarla Críochadóra Caite", "entity.minecraft.enderman": "Críochnaitheoir", "entity.minecraft.endermite": "Fríd na Críche", "entity.minecraft.evoker": "Gairmneachán", "entity.minecraft.evoker_fangs": "Gairmneachán ag taispeáint a fhiacla", "entity.minecraft.experience_bottle": "Buidéal Caite Asarlaíochta", "entity.minecraft.experience_orb": "Cruinneog Thaithí", "entity.minecraft.eye_of_ender": "Súil na Críche", "entity.minecraft.falling_block": "Bloc ag Titim", "entity.minecraft.fireball": "Caor Thine", "entity.minecraft.firework_rocket": "Roicéad Tine Ealaíne", "entity.minecraft.fishing_bobber": "Buimbiléad", "entity.minecraft.fox": "Sionnach", "entity.minecraft.furnace_minecart": "Cairt Mianaigh le Foirnéis", "entity.minecraft.ghast": "Uafaireach", "entity.minecraft.giant": "Fathach", "entity.minecraft.guardian": "Coimeádaí", "entity.minecraft.hopper_minecart": "Cairt Mianaigh le Crannóg", "entity.minecraft.horse": "Capall", "entity.minecraft.husk": "Seargán", "entity.minecraft.illusioner": "Cluanaire súl", "entity.minecraft.iron_golem": "Gólam Iarainn", "entity.minecraft.item": "Earra", "entity.minecraft.item_frame": "Fráma Earra", "entity.minecraft.killer_bunny": "An Coinín Marfach", "entity.minecraft.leash_knot": "Snaidhm Éille", "entity.minecraft.lightning_bolt": "Splanc Thintrí", "entity.minecraft.llama": "Láma", "entity.minecraft.llama_spit": "Seile Láma", "entity.minecraft.magma_cube": "Ciúb Magma", "entity.minecraft.minecart": "Cairt Mianaigh", "entity.minecraft.mooshroom": "Múúisiriún", "entity.minecraft.mule": "Miúil", "entity.minecraft.ocelot": "Osalat", "entity.minecraft.painting": "Pictiúr", "entity.minecraft.panda": "Panda", "entity.minecraft.parrot": "Pearóid", "entity.minecraft.phantom": "Púca", "entity.minecraft.pig": "Muc", "entity.minecraft.pillager": "Creachadóir", "entity.minecraft.player": "Imreoir", "entity.minecraft.polar_bear": "Béar Bán", "entity.minecraft.potion": "Posóid", "entity.minecraft.pufferfish": "Iasc Bolgach", "entity.minecraft.rabbit": "Coinín", "entity.minecraft.ravager": "Sladaire", "entity.minecraft.salmon": "Bradán", "entity.minecraft.sheep": "Caora", "entity.minecraft.shulker": "Slíogadóir", "entity.minecraft.shulker_bullet": "Piléar Slíogadóra", "entity.minecraft.silverfish": "Gilín", "entity.minecraft.skeleton": "Cnámharlach", "entity.minecraft.skeleton_horse": "Capall Cnámharlaigh", "entity.minecraft.slime": "Slam", "entity.minecraft.small_fireball": "Caor Thine Bheag", "entity.minecraft.snow_golem": "Gólam Sneachta", "entity.minecraft.snowball": "Meall Sneachta", "entity.minecraft.spawner_minecart": "Cairt Mianaigh le Gineadóir", "entity.minecraft.spectral_arrow": "Saighead Síofrúil", "entity.minecraft.spider": "Damhán Alla", "entity.minecraft.squid": "Scuid", "entity.minecraft.stray": "Fánaí", "entity.minecraft.tnt": "TNT Prímeáilte", "entity.minecraft.tnt_minecart": "Cairt Mianaigh le TNT", "entity.minecraft.trader_llama": "Láma Trádálaí", "entity.minecraft.trident": "Trírinn", "entity.minecraft.tropical_fish": "Iasc Trópaiceach", "entity.minecraft.tropical_fish.predefined.0": "Gairéadach na hEite Flannbhuí", "entity.minecraft.tropical_fish.predefined.1": "Earrspíonach Fadsocach", "entity.minecraft.tropical_fish.predefined.10": "Íol na Múrach", "entity.minecraft.tropical_fish.predefined.11": "Aingeal Mara Sciamhach", "entity.minecraft.tropical_fish.predefined.12": "Iasc Pearóide", "entity.minecraft.tropical_fish.predefined.13": "Aingiliasc Ríona", "entity.minecraft.tropical_fish.predefined.14": "Ciclid Dearg", "entity.minecraft.tropical_fish.predefined.15": "Ceannruán Deargliopach", "entity.minecraft.tropical_fish.predefined.16": "Sclamhaire Dearg", "entity.minecraft.tropical_fish.predefined.17": "Snáitheiteach", "entity.minecraft.tropical_fish.predefined.18": "Gairéadach Craorag", "entity.minecraft.tropical_fish.predefined.19": "Iasc Truicir", "entity.minecraft.tropical_fish.predefined.2": "Earrspíonach Gorm", "entity.minecraft.tropical_fish.predefined.20": "Iasc Pearóide Earrbhuí", "entity.minecraft.tropical_fish.predefined.21": "Earrspíonach Buí", "entity.minecraft.tropical_fish.predefined.3": "Aingeal Mara na gCeithre Súl", "entity.minecraft.tropical_fish.predefined.4": "Ciclid", "entity.minecraft.tropical_fish.predefined.5": "Gairéadach", "entity.minecraft.tropical_fish.predefined.6": "Iasc Troda Rósach", "entity.minecraft.tropical_fish.predefined.7": "Droim Breac", "entity.minecraft.tropical_fish.predefined.8": "Sclamhaire Dearg Impireach", "entity.minecraft.tropical_fish.predefined.9": "Iasc Gabhair Buí", "entity.minecraft.tropical_fish.type.betty": "Beití", "entity.minecraft.tropical_fish.type.blockfish": "Iasc Bloic", "entity.minecraft.tropical_fish.type.brinely": "Goirteán", "entity.minecraft.tropical_fish.type.clayfish": "Iasc Cré", "entity.minecraft.tropical_fish.type.dasher": "Ruathaire", "entity.minecraft.tropical_fish.type.flopper": "Flupaire", "entity.minecraft.tropical_fish.type.glitter": "Glioscarnach", "entity.minecraft.tropical_fish.type.kob": "Caobach", "entity.minecraft.tropical_fish.type.snooper": "Póirseálaí", "entity.minecraft.tropical_fish.type.spotty": "Spotach", "entity.minecraft.tropical_fish.type.stripey": "Stríocach", "entity.minecraft.tropical_fish.type.sunstreak": "Léas Gréine", "entity.minecraft.turtle": "Turtar", "entity.minecraft.vex": "Buaireán", "entity.minecraft.villager": "Sráideánach", "entity.minecraft.villager.armorer": "Armadóir", "entity.minecraft.villager.butcher": "Búistéir", "entity.minecraft.villager.cartographer": "Cartagrafaí", "entity.minecraft.villager.cleric": "Cléireach", "entity.minecraft.villager.farmer": "Feirmeoir", "entity.minecraft.villager.fisherman": "Iascaire", "entity.minecraft.villager.fletcher": "Déantóir Saighead", "entity.minecraft.villager.leatherworker": "Ceardaí Leathair", "entity.minecraft.villager.librarian": "Leabharlannaí", "entity.minecraft.villager.mason": "Saor Cloiche", "entity.minecraft.villager.nitwit": "Cloigneachán", "entity.minecraft.villager.none": "Sráideánach", "entity.minecraft.villager.shepherd": "Aoire", "entity.minecraft.villager.toolsmith": "Gabha Uirlisí", "entity.minecraft.villager.weaponsmith": "Gabha Arm", "entity.minecraft.vindicator": "Dlisteanóir", "entity.minecraft.wandering_trader": "Trádálaí Fánaíochta", "entity.minecraft.witch": "Cailleach", "entity.minecraft.wither": "Wither", "entity.minecraft.wither_skeleton": "Cnámharlach Seargthóra", "entity.minecraft.wither_skull": "Cloigeann Seargthóra", "entity.minecraft.wolf": "Mac Tíre", "entity.minecraft.zombie": "Zombaí", "entity.minecraft.zombie_horse": "Capall Zombaí", "entity.minecraft.zombie_pigman": "Mucachán Zombaí", "entity.minecraft.zombie_villager": "Sráideánach Zombaí", "entity.notFound": "Aonán anaithnid: %s", "event.minecraft.raid": "Ruaig", "event.minecraft.raid.defeat": "Aisghabháil", "event.minecraft.raid.raiders_remaining": "Creachairí fágtha: %s", "event.minecraft.raid.victory": "Bua", "filled_map.buried_treasure": "Léarscáil Thaisce faoi Thalamh", "filled_map.id": "Id #%s", "filled_map.level": "(Leibhéal %s%s)", "filled_map.locked": "Glasáilte", "filled_map.mansion": "Léarscáil Taiscéalaí Coillearnaí", "filled_map.monument": "Léarscáil Taiscéalaí Aigéin", "filled_map.scale": "Scála 1:%s", "filled_map.unknown": "Léarscáil Anaithnid", "gameMode.adventure": "Mód Eachtra", "gameMode.changed": "Nuashonraíodh do mhód chluiche go %s", "gameMode.creative": "Mód Cruthaitheach", "gameMode.hardcore": "Mód Antoisceach!", "gameMode.spectator": "Mód Féachadóra", "gameMode.survival": "Mód Marthanais", "generator.amplified": "MÉADAITHE", "generator.amplified.info": "Nóta: Ar feadh spraoi, ríomhaire féitheogach riachtanach", "generator.buffet": "Boiseog", "generator.customized": "Saincheaptha", "generator.debug_all_block_states": "Mód Dífhabhtúcháin", "generator.default": "Réamhshocrú", "generator.flat": "Sárchothrom", "generator.largeBiomes": "Bithóim Mhóra", "generator.minecraft.caves": "Pluaiseanna", "generator.minecraft.floating_islands": "Oileáin Foluineacha", "generator.minecraft.surface": "Dromchla", "gui.advancements": "Forbairtí", "gui.all": "Gach", "gui.back": "Siar", "gui.cancel": "Cealaigh", "gui.done": "Déanta", "gui.down": "Síos", "gui.narrate.button": "Cnaipe %s", "gui.narrate.editBox": "%s athraigh bosca: %s", "gui.narrate.slider": "Sleamhnán %s", "gui.no": "Níl", "gui.none": "Ceann ar bith", "gui.ok": "Óicé", "gui.proceed": "Dul ar aghaidh", "gui.recipebook.moreRecipes": "Deaschliceáil le tuilleadh", "gui.recipebook.toggleRecipes.all": "Gach oideas", "gui.recipebook.toggleRecipes.blastable": "Inphléasctha faoi thaispeáint", "gui.recipebook.toggleRecipes.craftable": "Oidis Sochruthaithe", "gui.recipebook.toggleRecipes.smeltable": "Oidis Sobhruithnithe", "gui.recipebook.toggleRecipes.smokable": "Rudaí is féidir a dheatú", "gui.stats": "Staitisticí", "gui.toMenu": "Ar ais don liosta freastalaithe", "gui.toTitle": "Ar ais don scáileán teidil", "gui.up": "Suas", "gui.yes": "Tá", "inventory.binSlot": "Scrios Earra", "inventory.hotbarInfo": "Sábháil barra uirlisí le %1s+%2s", "inventory.hotbarSaved": "Sábháladh barra uirlisí (tabhair ar ais le %1s+%2s)", "item.canBreak": "Briseann sé:", "item.canPlace": "Is féidir é a chur ar:", "item.color": "Dath: %s", "item.durability": "Buanfas: %s / %s", "item.dyed": "Daite", "item.minecraft.acacia_boat": "Bád Acaicia", "item.minecraft.apple": "Úll", "item.minecraft.armor_stand": "Seastán Cathéide", "item.minecraft.arrow": "Saighead", "item.minecraft.baked_potato": "Práta Bácáilte", "item.minecraft.bat_spawn_egg": "Ubh Ghinte Ialtóg", "item.minecraft.beef": "Mairteoil Amh", "item.minecraft.beetroot": "Biatas", "item.minecraft.beetroot_seeds": "Síol Biatais", "item.minecraft.beetroot_soup": "Anraith Biatas", "item.minecraft.birch_boat": "Bád Beithe", "item.minecraft.black_dye": "Dath Dubh", "item.minecraft.blaze_powder": "Púdar Lasaire", "item.minecraft.blaze_rod": "Slat Lasaire", "item.minecraft.blaze_spawn_egg": "Ubh Ghinte Lasairí", "item.minecraft.blue_dye": "Dath Gorm", "item.minecraft.bone": "Cnámh", "item.minecraft.bone_meal": "Min Chnámh", "item.minecraft.book": "Leabhar", "item.minecraft.bow": "Bogha", "item.minecraft.bowl": "Babhla", "item.minecraft.bread": "Arán", "item.minecraft.brewing_stand": "Seastán Grúdaireachta", "item.minecraft.brick": "Bríce", "item.minecraft.brown_dye": "Dath Donn", "item.minecraft.bucket": "Buicéad", "item.minecraft.carrot": "Cairéad", "item.minecraft.carrot_on_a_stick": "Cairéad ar Maide", "item.minecraft.cat_spawn_egg": "Gair Cat", "item.minecraft.cauldron": "Coire", "item.minecraft.cave_spider_spawn_egg": "Ubh Ghinte Damháin Alla Pluaise", "item.minecraft.chainmail_boots": "Bróga Lúbmháille", "item.minecraft.chainmail_chestplate": "Lúireach Lúbmháille", "item.minecraft.chainmail_helmet": "Clogad Lúbmháille", "item.minecraft.chainmail_leggings": "Loirgeáin Lúbmháille", "item.minecraft.charcoal": "Gualach", "item.minecraft.chest_minecart": "Cairt Mianaigh le Cófra", "item.minecraft.chicken": "Sicín Amh", "item.minecraft.chicken_spawn_egg": "Ubh Ghinte Sicíní", "item.minecraft.chorus_fruit": "Toradh Curfá", "item.minecraft.clay_ball": "Cré", "item.minecraft.clock": "Clog", "item.minecraft.coal": "Gual", "item.minecraft.cocoa_beans": "Pónairí Cacó", "item.minecraft.cod": "Trosc Amh", "item.minecraft.cod_bucket": "Buicéad Troisc", "item.minecraft.cod_spawn_egg": "Ubh Ghinte Trosc", "item.minecraft.command_block_minecart": "Cairt Mianaigh le Bloc Ordaithe", "item.minecraft.compass": "Compás", "item.minecraft.cooked_beef": "Stéig", "item.minecraft.cooked_chicken": "Sicín Cócaráilte", "item.minecraft.cooked_cod": "Trosc Cócaráilte", "item.minecraft.cooked_mutton": "Caoireoil Cócaráilte", "item.minecraft.cooked_porkchop": "Gríscín Muiceola Cócaráilte", "item.minecraft.cooked_rabbit": "Coinín Cócaráilte", "item.minecraft.cooked_salmon": "Bradán Cócaráilte", "item.minecraft.cookie": "Briosca", "item.minecraft.cow_spawn_egg": "Ubh Ghinte Bó", "item.minecraft.creeper_banner_pattern": "Patrún Brataí", "item.minecraft.creeper_banner_pattern.desc": "Creeper", "item.minecraft.creeper_head": "Ceann Téaltóra", "item.minecraft.creeper_spawn_egg": "Ubh Ghinte Téaltóirí", "item.minecraft.crossbow": "Crosbhogha", "item.minecraft.crossbow.projectile": "Diúracán:", "item.minecraft.cyan_dye": "Ruaim Chian", "item.minecraft.dark_oak_boat": "Bád Darach Duibhe", "item.minecraft.debug_stick": "Baitín Dífhabhtaithe", "item.minecraft.debug_stick.empty": "Níl aon airí ag %s", "item.minecraft.debug_stick.select": "\"%s\" roghnaithe (%s)", "item.minecraft.debug_stick.update": "\"%s\" go %s", "item.minecraft.diamond": "Diamant", "item.minecraft.diamond_axe": "Tua Dhiamaint", "item.minecraft.diamond_boots": "Bróga Diamaint", "item.minecraft.diamond_chestplate": "Uchtach Diamaint", "item.minecraft.diamond_helmet": "Clogad Diamaint", "item.minecraft.diamond_hoe": "Grafóg Dhiamaint", "item.minecraft.diamond_horse_armor": "Cathéide Dhiamaint do Chapall", "item.minecraft.diamond_leggings": "Loirgneáin Diamaint", "item.minecraft.diamond_pickaxe": "Piocóid Diamaint", "item.minecraft.diamond_shovel": "Sluasaid Diamaint", "item.minecraft.diamond_sword": "Claíomh Diamaint", "item.minecraft.dolphin_spawn_egg": "Ubh Ghinte Deilfeanna", "item.minecraft.donkey_spawn_egg": "Ubh Ghinte Asal", "item.minecraft.dragon_breath": "Anáil Dragain", "item.minecraft.dragon_head": "Ceann Dragain", "item.minecraft.dried_kelp": "Ceilp Triomaithe", "item.minecraft.drowned_spawn_egg": "Ubh Ghinte Báiteachán", "item.minecraft.egg": "Ubh", "item.minecraft.elder_guardian_spawn_egg": "Ubh Ghinte Coimeádaithe Sinsearacha", "item.minecraft.elytra": "Eilitreaim", "item.minecraft.emerald": "Smaragaid", "item.minecraft.enchanted_book": "Leabhar Faoi Dhraíocht", "item.minecraft.enchanted_golden_apple": "Úll Óir Gleoite", "item.minecraft.end_crystal": "Criostal na Críche", "item.minecraft.ender_eye": "Súil na Críche", "item.minecraft.ender_pearl": "Péarla na Críche", "item.minecraft.enderman_spawn_egg": "Ubh Ghinte Críochnaitheoirí", "item.minecraft.endermite_spawn_egg": "Ubh Ghinte Frídí na Críche", "item.minecraft.evoker_spawn_egg": "Ubh Ghinte Gairmneachán", "item.minecraft.experience_bottle": "Buidéal Asarlaíochta", "item.minecraft.feather": "Cleite", "item.minecraft.fermented_spider_eye": "Súil Damháin Alla Coipthe", "item.minecraft.filled_map": "Léarscáil", "item.minecraft.fire_charge": "Lánán Tine", "item.minecraft.firework_rocket": "Roicéad Tine Ealaíne", "item.minecraft.firework_rocket.flight": "Tréimhse Eitilte:", "item.minecraft.firework_star": "Réalta Tine Ealaíne", "item.minecraft.firework_star.black": "Dubh", "item.minecraft.firework_star.blue": "Gorm", "item.minecraft.firework_star.brown": "Donn", "item.minecraft.firework_star.custom_color": "Saincheaptha", "item.minecraft.firework_star.cyan": "Cian", "item.minecraft.firework_star.fade_to": "Céimnigh go", "item.minecraft.firework_star.flicker": "Drithleach", "item.minecraft.firework_star.gray": "Liath", "item.minecraft.firework_star.green": "Uaine", "item.minecraft.firework_star.light_blue": "Bánghorm", "item.minecraft.firework_star.light_gray": "Fionnliath", "item.minecraft.firework_star.lime": "Líomach", "item.minecraft.firework_star.magenta": "Maigeanta", "item.minecraft.firework_star.orange": "Oráisteach", "item.minecraft.firework_star.pink": "Bándearg", "item.minecraft.firework_star.purple": "Corcra", "item.minecraft.firework_star.red": "Dearg", "item.minecraft.firework_star.shape": "Cruth Anaithnid", "item.minecraft.firework_star.shape.burst": "Pléascach", "item.minecraft.firework_star.shape.creeper": "I gCruth Téaltóra", "item.minecraft.firework_star.shape.large_ball": "Liathróid Mhór", "item.minecraft.firework_star.shape.small_ball": "Liathróid Bheag", "item.minecraft.firework_star.shape.star": "Réaltchruthach", "item.minecraft.firework_star.trail": "Rian", "item.minecraft.firework_star.white": "Bán", "item.minecraft.firework_star.yellow": "Buí", "item.minecraft.fishing_rod": "Slat Iascaigh", "item.minecraft.flint": "Breochloch", "item.minecraft.flint_and_steel": "Breochloch is Cruach", "item.minecraft.flower_banner_pattern": "Patrún Brataí", "item.minecraft.flower_banner_pattern.desc": "Bláth", "item.minecraft.flower_pot": "Pota Bláthanna", "item.minecraft.fox_spawn_egg": "Ubh Ghinte Sionnaigh", "item.minecraft.furnace_minecart": "Cairt Mianaigh le Foirnéis", "item.minecraft.ghast_spawn_egg": "Ubh Ghinte Uafaireach", "item.minecraft.ghast_tear": "Deoir an Uafairigh", "item.minecraft.glass_bottle": "Buidéal Gloine", "item.minecraft.glistering_melon_slice": "Gearradh Mealbhacán Súilíneach", "item.minecraft.globe_banner_pattern": "Patrún Brataí", "item.minecraft.globe_banner_pattern.desc": "Cruinne", "item.minecraft.glowstone_dust": "Deannach Lonnraíte", "item.minecraft.gold_ingot": "Tinne Óir", "item.minecraft.gold_nugget": "Cnap Óir", "item.minecraft.golden_apple": "Úll Óir", "item.minecraft.golden_axe": "Tua Óir", "item.minecraft.golden_boots": "Bróga Óir", "item.minecraft.golden_carrot": "Cairéad Óir", "item.minecraft.golden_chestplate": "Uchtach Óir", "item.minecraft.golden_helmet": "Clogad Óir", "item.minecraft.golden_hoe": "Grafóg Óir", "item.minecraft.golden_horse_armor": "Eacharmúr Ór", "item.minecraft.golden_leggings": "Loirgneáin Óir", "item.minecraft.golden_pickaxe": "Piocóid Óir", "item.minecraft.golden_shovel": "Sluasaid Óir", "item.minecraft.golden_sword": "Claíomh Óir", "item.minecraft.gray_dye": "Ruaim Liath", "item.minecraft.green_dye": "Dath Uaine", "item.minecraft.guardian_spawn_egg": "Ubh Ghinte Coimeádaithe", "item.minecraft.gunpowder": "Púdar Gunna", "item.minecraft.heart_of_the_sea": "Croí na Mara", "item.minecraft.hopper_minecart": "Cairt Mianaigh le Crannóg", "item.minecraft.horse_spawn_egg": "Ubh Ghinte Capall", "item.minecraft.husk_spawn_egg": "Ubh Ghinte Seargán", "item.minecraft.ink_sac": "Sac Dúigh", "item.minecraft.iron_axe": "Tua Iarainn", "item.minecraft.iron_boots": "Bróga Iarainn", "item.minecraft.iron_chestplate": "Uchtach Iarainn", "item.minecraft.iron_helmet": "Clogad Iarainn", "item.minecraft.iron_hoe": "Grafóg Iarainn", "item.minecraft.iron_horse_armor": "Cathéide Iarainn do Chapall", "item.minecraft.iron_ingot": "Tinne Iarainn", "item.minecraft.iron_leggings": "Loirgneáin Iarainn", "item.minecraft.iron_nugget": "Cnap Iarainn", "item.minecraft.iron_pickaxe": "Piocóid Iarainn", "item.minecraft.iron_shovel": "Sluasaid Iarainn", "item.minecraft.iron_sword": "Claíomh Iarainn", "item.minecraft.item_frame": "Fráma Earra", "item.minecraft.jungle_boat": "Bád Adhmad Dufaire", "item.minecraft.knowledge_book": "Leabhar Eolais", "item.minecraft.lapis_lazuli": "Lapis Lazuli", "item.minecraft.lava_bucket": "Buicéad Laibhe", "item.minecraft.lead": "Iall", "item.minecraft.leather": "Leathar", "item.minecraft.leather_boots": "Bróga Leathair", "item.minecraft.leather_chestplate": "Ionar Leathair", "item.minecraft.leather_helmet": "Caipín Leathair", "item.minecraft.leather_horse_armor": "Cathéide Leathair na gCapall", "item.minecraft.leather_leggings": "Bríste Leathair", "item.minecraft.light_blue_dye": "Ruaim Bhánghorm", "item.minecraft.light_gray_dye": "Ruaim Fhionnliath", "item.minecraft.lime_dye": "Ruaim Líomach", "item.minecraft.lingering_potion": "Posóid Righin", "item.minecraft.lingering_potion.effect.awkward": "Posóid Righin Chiotach", "item.minecraft.lingering_potion.effect.empty": "Posóid Righin Dochumtha", "item.minecraft.lingering_potion.effect.fire_resistance": "Posóid Righin na Dó-obachta", "item.minecraft.lingering_potion.effect.harming": "Posóid Righin an Dochair", "item.minecraft.lingering_potion.effect.healing": "Posóid Righin an Leighis", "item.minecraft.lingering_potion.effect.invisibility": "Posóid Righin na Dofheictheachta", "item.minecraft.lingering_potion.effect.leaping": "Posóid Righin na Léime", "item.minecraft.lingering_potion.effect.levitation": "Posóid Righin an Eadarbhuasaithe", "item.minecraft.lingering_potion.effect.luck": "Posóid Righin an Áidh", "item.minecraft.lingering_potion.effect.mundane": "Posóid Righin Leamh", "item.minecraft.lingering_potion.effect.night_vision": "Posóid Righin Radharc san Oíche", "item.minecraft.lingering_potion.effect.poison": "Posóid Righin na Nimhe", "item.minecraft.lingering_potion.effect.regeneration": "Posóid Righin na hAthghiniúna", "item.minecraft.lingering_potion.effect.slow_falling": "Posóid Righin na Mallthitime", "item.minecraft.lingering_potion.effect.slowness": "Posóid Righin na Moille", "item.minecraft.lingering_potion.effect.strength": "Posóid Righin an Nirt", "item.minecraft.lingering_potion.effect.swiftness": "Posóid Righin an Luais", "item.minecraft.lingering_potion.effect.thick": "Posóid Righin Thiubh", "item.minecraft.lingering_potion.effect.turtle_master": "Posóid Righin Mháistir na dTurtar", "item.minecraft.lingering_potion.effect.water": "Buidéal Uisce Righin", "item.minecraft.lingering_potion.effect.water_breathing": "Posóid Righin Análú in Uisce", "item.minecraft.lingering_potion.effect.weakness": "Posóid Righin na Laige", "item.minecraft.llama_spawn_egg": "Ubh Ghinte Lámaí", "item.minecraft.magenta_dye": "Ruaim Mhaigeanta", "item.minecraft.magma_cream": "Uachtar Magma", "item.minecraft.magma_cube_spawn_egg": "Ubh Ghinte Ciúbanna Magma", "item.minecraft.map": "Léarscáil Bhán", "item.minecraft.melon_seeds": "Síolta Mealbhacáin", "item.minecraft.melon_slice": "Gearradh Mealbhacán", "item.minecraft.milk_bucket": "Buicéad Bainne", "item.minecraft.minecart": "Cairt Mianaigh", "item.minecraft.mojang_banner_pattern": "Patrún Brataí", "item.minecraft.mojang_banner_pattern.desc": "Rud", "item.minecraft.mooshroom_spawn_egg": "Ubh Ghinte Múúisiriún", "item.minecraft.mule_spawn_egg": "Ubh Ghinte Miúileanna", "item.minecraft.mushroom_stew": "Stobhach Muisiriún", "item.minecraft.music_disc_11": "Diosca Ceoil", "item.minecraft.music_disc_11.desc": "C418 - 11", "item.minecraft.music_disc_13": "Diosca Ceoil", "item.minecraft.music_disc_13.desc": "C418 - 13", "item.minecraft.music_disc_blocks": "Diosca Ceoil", "item.minecraft.music_disc_blocks.desc": "C418 - blocks", "item.minecraft.music_disc_cat": "Diosca Ceoil", "item.minecraft.music_disc_cat.desc": "C418 - cat", "item.minecraft.music_disc_chirp": "Diosca Ceoil", "item.minecraft.music_disc_chirp.desc": "C418 - chirp", "item.minecraft.music_disc_far": "Diosca Ceoil", "item.minecraft.music_disc_far.desc": "C418 - far", "item.minecraft.music_disc_mall": "Diosca Ceoil", "item.minecraft.music_disc_mall.desc": "C418 - mall", "item.minecraft.music_disc_mellohi": "Diosca Ceoil", "item.minecraft.music_disc_mellohi.desc": "C418 - mellohi", "item.minecraft.music_disc_stal": "Diosca Ceoil", "item.minecraft.music_disc_stal.desc": "C418 - stal", "item.minecraft.music_disc_strad": "Diosca Ceoil", "item.minecraft.music_disc_strad.desc": "C418 - strad", "item.minecraft.music_disc_wait": "Diosca Ceoil", "item.minecraft.music_disc_wait.desc": "C418 - wait", "item.minecraft.music_disc_ward": "Diosca Ceoil", "item.minecraft.music_disc_ward.desc": "C418 - ward", "item.minecraft.mutton": "Caoireoil Amh", "item.minecraft.name_tag": "Lipéad Ainm", "item.minecraft.nautilus_shell": "Blaosc Nátalais", "item.minecraft.nether_brick": "Bloc Íochtarbhrící", "item.minecraft.nether_star": "Réalta an Íochtair", "item.minecraft.nether_wart": "Mus an Íochtair", "item.minecraft.oak_boat": "Bád Darach", "item.minecraft.ocelot_spawn_egg": "Ubh Ghinte Osalat", "item.minecraft.orange_dye": "Ruaim Oráisteach", "item.minecraft.painting": "Pictiúr", "item.minecraft.panda_spawn_egg": "Gair Panda", "item.minecraft.paper": "Páipéar", "item.minecraft.parrot_spawn_egg": "Ubh Ghinte Pearóidí", "item.minecraft.phantom_membrane": "Seicin Púca", "item.minecraft.phantom_spawn_egg": "Ubh Ghinte Púcaí", "item.minecraft.pig_spawn_egg": "Ubh Ghinte Muc", "item.minecraft.pillager_spawn_egg": "Gair Creachadóir", "item.minecraft.pink_dye": "Ruaim Bhándearg", "item.minecraft.poisonous_potato": "Práta Nimhiúil", "item.minecraft.polar_bear_spawn_egg": "Ubh Ghinte Béar Bán", "item.minecraft.popped_chorus_fruit": "Toradh Curfá Rósta", "item.minecraft.porkchop": "Gríscín Muiceola Amh", "item.minecraft.potato": "Práta", "item.minecraft.potion": "Posóid", "item.minecraft.potion.effect.awkward": "Posóid Chiotach", "item.minecraft.potion.effect.empty": "Posóid Dochumtha", "item.minecraft.potion.effect.fire_resistance": "Posóid na Dó-obachta", "item.minecraft.potion.effect.harming": "Posóid an Dochair", "item.minecraft.potion.effect.healing": "Posóid an Leighis", "item.minecraft.potion.effect.invisibility": "Posóid na Dofheictheachta", "item.minecraft.potion.effect.leaping": "Posóid na Léime", "item.minecraft.potion.effect.levitation": "Posóid an Eadarbhuasaithe", "item.minecraft.potion.effect.luck": "Posóid an Áidh", "item.minecraft.potion.effect.mundane": "Posóid Leamh", "item.minecraft.potion.effect.night_vision": "Posóid Radharc san Oíche", "item.minecraft.potion.effect.poison": "Posóid na Nimhe", "item.minecraft.potion.effect.regeneration": "Posóid na hAthghiniúna", "item.minecraft.potion.effect.slow_falling": "Posóid na Mallthitime", "item.minecraft.potion.effect.slowness": "Posóid na Moille", "item.minecraft.potion.effect.strength": "Posóid an Nirt", "item.minecraft.potion.effect.swiftness": "Posóid an Luais", "item.minecraft.potion.effect.thick": "Posóid Thiubh", "item.minecraft.potion.effect.turtle_master": "Posóid Mháistir na dTurtar", "item.minecraft.potion.effect.water": "Buidéal Uisce", "item.minecraft.potion.effect.water_breathing": "Posóid Análú in Uisce", "item.minecraft.potion.effect.weakness": "Posóid na Laige", "item.minecraft.prismarine_crystals": "Criostail Phriosmuirínigh", "item.minecraft.prismarine_shard": "Scealp Phriosmuirínigh", "item.minecraft.pufferfish": "Iasc Bolgach", "item.minecraft.pufferfish_bucket": "Buicéad Iasc Bolgach", "item.minecraft.pufferfish_spawn_egg": "Ubh Ghinte Iasc Bolgach", "item.minecraft.pumpkin_pie": "Pióg Phuimcín", "item.minecraft.pumpkin_seeds": "Síolta Puimcín", "item.minecraft.purple_dye": "Ruaim Chorcra", "item.minecraft.quartz": "Grianchloch an Íochtair", "item.minecraft.rabbit": "Coinín Amh", "item.minecraft.rabbit_foot": "Cos Coinín", "item.minecraft.rabbit_hide": "Craiceann Coinín", "item.minecraft.rabbit_spawn_egg": "Ubh Ghinte Coiníní", "item.minecraft.rabbit_stew": "Stobhach Coinín", "item.minecraft.ravager_spawn_egg": "Gair Sladaire", "item.minecraft.red_dye": "Dath Dearg", "item.minecraft.redstone": "Deannach Deargchloiche", "item.minecraft.rotten_flesh": "Feoil Lofa", "item.minecraft.saddle": "Diallait", "item.minecraft.salmon": "Bradán Amh", "item.minecraft.salmon_bucket": "Buicéad Bradáin", "item.minecraft.salmon_spawn_egg": "Ubh Ghinte Bradán", "item.minecraft.scute": "Ceiritin", "item.minecraft.shears": "Deimheas", "item.minecraft.sheep_spawn_egg": "Ubh Ghinte Caorach", "item.minecraft.shield": "Sciath", "item.minecraft.shield.black": "Sciath Dhubh", "item.minecraft.shield.blue": "Sciath Ghorm", "item.minecraft.shield.brown": "Sciath Dhonn", "item.minecraft.shield.cyan": "Sciath Chian", "item.minecraft.shield.gray": "Sciath Liath", "item.minecraft.shield.green": "Sciath Uaine", "item.minecraft.shield.light_blue": "Sciath Bhánghorm", "item.minecraft.shield.light_gray": "Sciath Fhionnliath", "item.minecraft.shield.lime": "Sciath Líomach", "item.minecraft.shield.magenta": "Sciath Mhaigeanta", "item.minecraft.shield.orange": "Sciath Oráisteach", "item.minecraft.shield.pink": "Sciath Bhándearg", "item.minecraft.shield.purple": "Sciath Chorcra", "item.minecraft.shield.red": "Sciath Dhearg", "item.minecraft.shield.white": "Sciath Bhán", "item.minecraft.shield.yellow": "Sciath Bhuí", "item.minecraft.shulker_shell": "Blaosc Slíogadóra", "item.minecraft.shulker_spawn_egg": "Ubh Ghinte Slíogadóirí", "item.minecraft.sign": "Sínigh", "item.minecraft.silverfish_spawn_egg": "Ubh Ghinte Gilíní", "item.minecraft.skeleton_horse_spawn_egg": "Ubh Ghinte Capall Cnámharlaigh", "item.minecraft.skeleton_skull": "Cloigeann Cnámharlaigh", "item.minecraft.skeleton_spawn_egg": "Ubh Ghinte Cnámharlach", "item.minecraft.skull_banner_pattern": "Patrún Brataí", "item.minecraft.skull_banner_pattern.desc": "Cloigeann", "item.minecraft.slime_ball": "Liathróid Slaim", "item.minecraft.slime_spawn_egg": "Ubh Ghinte Slam", "item.minecraft.snowball": "Meall Sneachta", "item.minecraft.spectral_arrow": "Saighead Síofrúil", "item.minecraft.spider_eye": "Súil Damháin Alla", "item.minecraft.spider_spawn_egg": "Ubh Ghinte Damhán Alla", "item.minecraft.splash_potion": "Posóid Theilgeach", "item.minecraft.splash_potion.effect.awkward": "Posóid Theilgeach Chiotach", "item.minecraft.splash_potion.effect.empty": "Posóid Theilgeach Dochumtha", "item.minecraft.splash_potion.effect.fire_resistance": "Posóid Theilgeach na Dó-obachta", "item.minecraft.splash_potion.effect.harming": "Posóid Theilgeach an Dochair", "item.minecraft.splash_potion.effect.healing": "Posóid Theilgeach an Leighis", "item.minecraft.splash_potion.effect.invisibility": "Posóid Theilgeach na Dofheictheachta", "item.minecraft.splash_potion.effect.leaping": "Posóid Theilgeach na Léime", "item.minecraft.splash_potion.effect.levitation": "Posóid Theilgeach an Eadarbhuasaithe", "item.minecraft.splash_potion.effect.luck": "Posóid Theilgeach an Áidh", "item.minecraft.splash_potion.effect.mundane": "Posóid Theilgeach Leamh", "item.minecraft.splash_potion.effect.night_vision": "Posóid Theilgeach Radharc san Oíche", "item.minecraft.splash_potion.effect.poison": "Posóid Theilgeach na Nimhe", "item.minecraft.splash_potion.effect.regeneration": "Posóid Theilgeach na hAthghiniúna", "item.minecraft.splash_potion.effect.slow_falling": "Posóid Theilgeach na Mallthitime", "item.minecraft.splash_potion.effect.slowness": "Posóid Theilgeach na Moille", "item.minecraft.splash_potion.effect.strength": "Posóid Theilgeach an Nirt", "item.minecraft.splash_potion.effect.swiftness": "Posóid Theilgeach an Luais", "item.minecraft.splash_potion.effect.thick": "Posóid Theilgeach Thiubh", "item.minecraft.splash_potion.effect.turtle_master": "Posóid Theilgeach Mháistir na dTurtar", "item.minecraft.splash_potion.effect.water": "Buidéal Uisce Teilgeach", "item.minecraft.splash_potion.effect.water_breathing": "Posóid Steallta Análú in Uisce", "item.minecraft.splash_potion.effect.weakness": "Posóid Theilgeach na Laige", "item.minecraft.spruce_boat": "Bád Sprúis", "item.minecraft.squid_spawn_egg": "Ubh Ghinte Scuideanna", "item.minecraft.stick": "Maide", "item.minecraft.stone_axe": "Tua Chloiche", "item.minecraft.stone_hoe": "Grafóg Chloiche", "item.minecraft.stone_pickaxe": "Piocóid Chloiche", "item.minecraft.stone_shovel": "Sluasaid Chloiche", "item.minecraft.stone_sword": "Claíomh Cloiche", "item.minecraft.stray_spawn_egg": "Ubh Ghinte Fánaithe", "item.minecraft.string": "Sreangán", "item.minecraft.sugar": "Siúcra", "item.minecraft.suspicious_stew": "Stobhach Amhrasach", "item.minecraft.sweet_berries": "Caora Milse", "item.minecraft.tipped_arrow": "Saighead Biorach", "item.minecraft.tipped_arrow.effect.awkward": "Saighead Biorach", "item.minecraft.tipped_arrow.effect.empty": "Saighead Biorach Dochumtha", "item.minecraft.tipped_arrow.effect.fire_resistance": "Saighead na Dó-obachta", "item.minecraft.tipped_arrow.effect.harming": "Saighead an Dochair", "item.minecraft.tipped_arrow.effect.healing": "Saighead an Leighis", "item.minecraft.tipped_arrow.effect.invisibility": "Saighead na Dofheictheachta", "item.minecraft.tipped_arrow.effect.leaping": "Saighead na Léime", "item.minecraft.tipped_arrow.effect.levitation": "Saighead an Eadarbhuasaithe", "item.minecraft.tipped_arrow.effect.luck": "Saighead an Áidh", "item.minecraft.tipped_arrow.effect.mundane": "Saighead Biorach", "item.minecraft.tipped_arrow.effect.night_vision": "Saighead Radharc san Oíche", "item.minecraft.tipped_arrow.effect.poison": "Saighead na Nimhe", "item.minecraft.tipped_arrow.effect.regeneration": "Saighead na hAthghiniúna", "item.minecraft.tipped_arrow.effect.slow_falling": "Saighead na Mallthitime", "item.minecraft.tipped_arrow.effect.slowness": "Saighead na Moille", "item.minecraft.tipped_arrow.effect.strength": "Saighead an Nirt", "item.minecraft.tipped_arrow.effect.swiftness": "Saighead an Luais", "item.minecraft.tipped_arrow.effect.thick": "Saighead Biorach", "item.minecraft.tipped_arrow.effect.turtle_master": "Saighead Mháistir na dTurtar", "item.minecraft.tipped_arrow.effect.water": "Saighead Steallaidh", "item.minecraft.tipped_arrow.effect.water_breathing": "Saighead Análú in Uisce", "item.minecraft.tipped_arrow.effect.weakness": "Saighead na Laige", "item.minecraft.tnt_minecart": "Cairt Mianaigh le TNT", "item.minecraft.totem_of_undying": "Tótam na Síoraíochta", "item.minecraft.trader_llama_spawn_egg": "Gair Láma Trádálaí", "item.minecraft.trident": "Trírinn", "item.minecraft.tropical_fish": "Iasc Trópaiceach", "item.minecraft.tropical_fish_bucket": "Buicéad Iasc Trópaiceach", "item.minecraft.tropical_fish_spawn_egg": "Ubh Ghinte Iasc Trópaiceach", "item.minecraft.turtle_helmet": "Blaosc Thurtair", "item.minecraft.turtle_spawn_egg": "Ubh Ghinte Turtar", "item.minecraft.vex_spawn_egg": "Ubh Ghinte Buaireán", "item.minecraft.villager_spawn_egg": "Ubh Ghinte Sráideánach", "item.minecraft.vindicator_spawn_egg": "Ubh Ghinte Dlisteanóirí", "item.minecraft.wandering_trader_spawn_egg": "Gair Trádálaí Fáin", "item.minecraft.water_bucket": "Buicéad Uisce", "item.minecraft.wheat": "Cruithneacht", "item.minecraft.wheat_seeds": "Síolta Gráin", "item.minecraft.white_dye": "Dath Bán", "item.minecraft.witch_spawn_egg": "Ubh Ghinte Cailleach", "item.minecraft.wither_skeleton_skull": "Cloigeann Cnámharlaigh Wither", "item.minecraft.wither_skeleton_spawn_egg": "Ubh Ghinte Cnámharlach Seargthóra", "item.minecraft.wolf_spawn_egg": "Ubh Ghinte Mac Tíre", "item.minecraft.wooden_axe": "Tua Adhmaid", "item.minecraft.wooden_hoe": "Grafóg Adhmaid", "item.minecraft.wooden_pickaxe": "Piocóid Adhmaid", "item.minecraft.wooden_shovel": "Sluasaid Adhmaid", "item.minecraft.wooden_sword": "Claíomh Adhmaid", "item.minecraft.writable_book": "Leabhar agus Peann Cleite", "item.minecraft.written_book": "Leabhar Scríofa", "item.minecraft.yellow_dye": "Dath Buí", "item.minecraft.zombie_head": "Ceann Zombaí", "item.minecraft.zombie_horse_spawn_egg": "Ubh Ghinte Capall Zombaí", "item.minecraft.zombie_pigman_spawn_egg": "Ubh Ghinte Mucachán Zombaí", "item.minecraft.zombie_spawn_egg": "Ubh Ghinte Zombaithe", "item.minecraft.zombie_villager_spawn_egg": "Ubh Ghinte Sráideánach Zombaí", "item.modifiers.chest": "Ar an gcorp:", "item.modifiers.feet": "Ar na cosa:", "item.modifiers.head": "Ar an gceann:", "item.modifiers.legs": "Ar na cosa:", "item.modifiers.mainhand": "Sa lámh cheannasach:", "item.modifiers.offhand": "Sa mheathlámh:", "item.nbt_tags": "NBT: %s tag(s)", "item.unbreakable": "Dobhriste", "itemGroup.brewing": "Grúdaireacht", "itemGroup.buildingBlocks": "Bloic Thógála", "itemGroup.combat": "Comhrac", "itemGroup.decorations": "Bloic Mhaisiúcháin", "itemGroup.food": "Bia", "itemGroup.hotbar": "Barraí Uirlisí Sábháilte", "itemGroup.inventory": "Fardal Marthanais", "itemGroup.materials": "Bunábhair", "itemGroup.misc": "Ilchineálach", "itemGroup.redstone": "Deargchloiche", "itemGroup.search": "Cuardaigh Earraí", "itemGroup.tools": "Uirlisí", "itemGroup.transportation": "Iompar", "jigsaw_block.attachement_type": "Sórt ceangail:", "jigsaw_block.final_state": "Athrú go:", "jigsaw_block.target_pool": "Foinse:", "key.advancements": "Forbairtí", "key.attack": "Ionsaigh/Scrios", "key.back": "Siúil ar gCúl", "key.categories.creative": "Mód Cruthaitheach", "key.categories.gameplay": "Imirt", "key.categories.inventory": "Fardal", "key.categories.misc": "Ilchineálach", "key.categories.movement": "Gluaiseacht", "key.categories.multiplayer": "Imreoir Iomadúil", "key.categories.ui": "Comhéadan Cluiche", "key.chat": "Oscail Comhrá", "key.command": "Tabhair Ordú", "key.drop": "Caith uait an t-earra roghnaithe", "key.forward": "Siúil ar Aghaidh", "key.fullscreen": "Scoránaigh Lánscáileán", "key.hotbar.1": "Sliotán 1 an Mhearbharra", "key.hotbar.2": "Sliotán 2 an Mhearbharra", "key.hotbar.3": "Sliotán 3 an Mhearbharra", "key.hotbar.4": "Sliotán 4 an Mhearbharra", "key.hotbar.5": "Sliotán 5 an Mhearbharra", "key.hotbar.6": "Sliotán 6 an Mhearbharra", "key.hotbar.7": "Sliotán 7 an Mhearbharra", "key.hotbar.8": "Sliotán 8 an Mhearbharra", "key.hotbar.9": "Sliotán 9 an Mhearbharra", "key.inventory": "Oscail/Dún Fardal", "key.jump": "Léim", "key.keyboard.apostrophe": ",", "key.keyboard.backslash": "\\", "key.keyboard.backspace": "Cúlspás", "key.keyboard.caps.lock": "Caps Lock", "key.keyboard.comma": ",", "key.keyboard.delete": "Scrios", "key.keyboard.down": "Saighead Síos", "key.keyboard.end": "Críoch", "key.keyboard.enter": "Iontráil", "key.keyboard.equal": "=", "key.keyboard.escape": "Éalaigh", "key.keyboard.f1": "F1", "key.keyboard.f10": "F10", "key.keyboard.f11": "F11", "key.keyboard.f12": "F12", "key.keyboard.f13": "F13", "key.keyboard.f14": "F14", "key.keyboard.f15": "F15", "key.keyboard.f16": "F16", "key.keyboard.f17": "F17", "key.keyboard.f18": "F18", "key.keyboard.f19": "F19", "key.keyboard.f2": "F2", "key.keyboard.f20": "F20", "key.keyboard.f21": "F21", "key.keyboard.f22": "F22", "key.keyboard.f23": "F23", "key.keyboard.f24": "F24", "key.keyboard.f25": "F25", "key.keyboard.f3": "F3", "key.keyboard.f4": "F4", "key.keyboard.f5": "F5", "key.keyboard.f6": "F6", "key.keyboard.f7": "F7", "key.keyboard.f8": "F8", "key.keyboard.f9": "F9", "key.keyboard.grave.accent": "`", "key.keyboard.home": "Baile", "key.keyboard.insert": "Ionsaigh", "key.keyboard.keypad.0": "Eochaircheap 0", "key.keyboard.keypad.1": "Eochaircheap 1", "key.keyboard.keypad.2": "Eochaircheap 2", "key.keyboard.keypad.3": "Eochaircheap 3", "key.keyboard.keypad.4": "Eochaircheap 4", "key.keyboard.keypad.5": "Eochaircheap 5", "key.keyboard.keypad.6": "Eochaircheap 6", "key.keyboard.keypad.7": "Eochaircheap 7", "key.keyboard.keypad.8": "Eochaircheap 8", "key.keyboard.keypad.9": "Eochaircheap 9", "key.keyboard.keypad.add": "Eochaircheap +", "key.keyboard.keypad.decimal": "Eochaircheap .", "key.keyboard.keypad.divide": "Eochaircheap /", "key.keyboard.keypad.enter": "Eochaircheap Iontráil", "key.keyboard.keypad.equal": "Eochaircheap =", "key.keyboard.keypad.multiply": "Eochaircheap *", "key.keyboard.keypad.subtract": "Eochaircheap -", "key.keyboard.left": "Saighead Clé", "key.keyboard.left.alt": "Alt Clé", "key.keyboard.left.bracket": "[", "key.keyboard.left.control": "Ctrl Clé", "key.keyboard.left.shift": "Iomlaoid Clé", "key.keyboard.left.win": "Win Clé", "key.keyboard.menu": "Roghchlár", "key.keyboard.minus": "-", "key.keyboard.num.lock": "Num Lock", "key.keyboard.page.down": "Page Down", "key.keyboard.page.up": "Page Up", "key.keyboard.pause": "Sos", "key.keyboard.period": ".", "key.keyboard.print.screen": "Print Screen", "key.keyboard.right": "Saighead Deas", "key.keyboard.right.alt": "Alt Deas", "key.keyboard.right.bracket": "]", "key.keyboard.right.control": "Ctrl Deas", "key.keyboard.right.shift": "Iomlaoid Deas", "key.keyboard.right.win": "Win Deas", "key.keyboard.scroll.lock": "Scroll Lock", "key.keyboard.semicolon": ";", "key.keyboard.slash": "/", "key.keyboard.space": "Spás", "key.keyboard.tab": "Táb", "key.keyboard.unknown": "Níl sé faoi cheangal", "key.keyboard.up": "Saighead Suas", "key.keyboard.world.1": "Domhan 1", "key.keyboard.world.2": "Domhan 2", "key.left": "Tabhair céim faoi Chlé", "key.loadToolbarActivator": "Lódáil Barra Uirlisí", "key.mouse": "Cnaipe %1s", "key.mouse.left": "Cnaipe ar Clé", "key.mouse.middle": "Cnaipe sa Lár", "key.mouse.right": "Cnaipe ar Dheis", "key.pickItem": "Pioc Bloc", "key.playerlist": "Liostáil Imreoirí", "key.right": "Tabhair céim faoi Dheis", "key.saveToolbarActivator": "Sábháil Barra Uirlisí", "key.screenshot": "Gabháil Scáileáin", "key.smoothCamera": "Scoránaigh an Ceamara Cineamatach", "key.sneak": "Téaltaigh", "key.spectatorOutlines": "Aibhsigh Imreoirí (Féachadóirí)", "key.sprint": "Rith", "key.swapHands": "Athraigh earra chuig an lámh eile", "key.togglePerspective": "Scoránaigh an Dearcadh", "key.use": "Úsáid Earra/Cuir Bloc", "lanServer.otherPlayers": "Socruithe le haghaidh Imreoirí Eile", "lanServer.scanning": "Ag scanadh le haghaidh cluichí ar do líonra logánta", "lanServer.start": "Tosaigh Domhan ar an Líon Logánta", "lanServer.title": "Domhan ar an Líon Logánta", "language.code": "ga_IE", "language.name": "Gaeilge", "language.region": "Éire", "lectern.take_book": "Leabhar a thógáil", "mcoServer.title": "Domhan Minecraft Ar Líne", "menu.convertingLevel": "Ag tiontú domhain", "menu.disconnect": "Dícheangail", "menu.game": "Roghchlár cluiche", "menu.generatingLevel": "Ag giniúint domhain", "menu.generatingTerrain": "Ag tógáil tír-raoin", "menu.loadingForcedChunks": "Ag lódáil na smutáin éigeantacha don diminsean %s", "menu.loadingLevel": "Ag luchtú domhain", "menu.multiplayer": "Mód Ilimreora", "menu.online": "Ríochtaí Minecraft", "menu.options": "Roghanna...", "menu.paused": "Cluiche ar sos", "menu.playdemo": "Imir sa Domhan Taispeána", "menu.preparingSpawn": "Ag réiteach na háite tosaithe: %s%%", "menu.quit": "Scoir den Chluiche", "menu.reportBugs": "An bhfuil fadhb ann?", "menu.resetdemo": "Athshocraigh an Domhan Taispeána", "menu.respawning": "Ag athionchollú", "menu.returnToGame": "Ar ais don Chluiche", "menu.returnToMenu": "Sábháil agus Scoir don Teideal", "menu.savingChunks": "Ag sábháil smután", "menu.savingLevel": "Ag sábháil an domhain", "menu.sendFeedback": "Do bharúil a thabhairt", "menu.shareToLan": "Oscail don LAN", "menu.singleplayer": "Imreoir Aonair", "menu.working": "Ag obair...", "merchant.current_level": "Leibhéal Reatha an Trádálaí", "merchant.deprecated": "Athstócáiltear sráideánaigh suas go dhá uair sa lá.", "merchant.level.1": "Núíosach", "merchant.level.2": "Printíseach", "merchant.level.3": "Saothraí", "merchant.level.4": "Saineolaí", "merchant.level.5": "Máistir", "merchant.next_level": "Leibhéal an Trádálaí i nDiaidh", "merchant.trades": "Malairtí", "mount.onboard": "Brúigh ar %1s chun tuirlingt", "multiplayer.connect": "Ceangail", "multiplayer.disconnect.authservers_down": "Theip ar na freastalaithe fíordheimhniúcháin. Bain triail as níos déanaí le do thoil, tá brón orainn!", "multiplayer.disconnect.banned": "Tá cosc ort ceangal leis an bhfreastalaí seo", "multiplayer.disconnect.banned.expiration": "\nBainfear do cosc ar %s", "multiplayer.disconnect.banned.reason": "Tá cosc ort ceangal leis an bhfreastalaí seo.\nFáth: %s", "multiplayer.disconnect.banned_ip.expiration": "\nBainfear do cosc ar %s", "multiplayer.disconnect.banned_ip.reason": "Tá cosc ar do seoladh IP ceangal leis an bhfreastalaí seo.\nFáth: %s", "multiplayer.disconnect.duplicate_login": "Logáil tú isteach ó áit eile", "multiplayer.disconnect.flying": "Níl an eitilt cumasaithe ar an bhfreastalaí seo", "multiplayer.disconnect.generic": "Dícheangailte", "multiplayer.disconnect.idling": "Bhí tú díomhaoin rófhada!", "multiplayer.disconnect.illegal_characters": "Carachtair neamhdhleathacha sa chomhrá", "multiplayer.disconnect.invalid_entity_attacked": "Ag iarraidh aonán neamhbhailí a ionsaí", "multiplayer.disconnect.invalid_player_movement": "Fuarthas paicéad bhogadh imreora neamhbhailí", "multiplayer.disconnect.invalid_vehicle_movement": "Fuarthas paicéad bhogadh feithicle neamhbhailí", "multiplayer.disconnect.ip_banned": "Tá cosc IP ort ceangal leis an bhfreastalaí seo", "multiplayer.disconnect.kicked": "Thug oibreoir cic duit", "multiplayer.disconnect.name_taken": "Rinneadh an t-ainm sin cheana féin", "multiplayer.disconnect.not_whitelisted": "Níl tú bán-liostaithe ar an freastalaí seo!", "multiplayer.disconnect.outdated_client": "Cliant as dáta. Úsáid %s le do thoil", "multiplayer.disconnect.outdated_server": "Freastalaí as dáta! Táim fós ar %s", "multiplayer.disconnect.server_full": "Tá an freastalaí seo lán!", "multiplayer.disconnect.server_shutdown": "Freastalaí Dúnta", "multiplayer.disconnect.slow_login": "Logáil isteach ró-mhall", "multiplayer.disconnect.unexpected_query_response": "Sonraí saincheaptha gan choinne ón úsáideoir", "multiplayer.disconnect.unverified_username": "Theip ar fhíorú d’ainm úsáideora!", "multiplayer.downloadingStats": "Ag íoslódáil staitisticí...", "multiplayer.downloadingTerrain": "Ag lódáil tír-raoin...", "multiplayer.ipinfo": "Cuir isteach seoladh IP freastalaí chun ceangal leis:", "multiplayer.message_not_delivered": "Ní féidir teachtaireacht comhrá ag tosú le %s, seiceáil na logleabhar seirbheálaí", "multiplayer.player.joined": "Tháinig %s isteach sa chluiche", "multiplayer.player.joined.renamed": "Tháinig %s (a tugadh %s air tráth) isteach sa chluiche", "multiplayer.player.left": "D'fhág %s an cluiche", "multiplayer.status.and_more": "... agus %s eile ...", "multiplayer.status.cancelled": "Cealaithe", "multiplayer.status.cannot_connect": "Ní féidir ceangal leis an bhfreastalaí", "multiplayer.status.cannot_resolve": "Ní féidir an t-óstainm a thaifeach", "multiplayer.status.client_out_of_date": "Cliant as dáta!", "multiplayer.status.finished": "Críochnaithe", "multiplayer.status.no_connection": "(gan ceangal)", "multiplayer.status.old": "As dáta", "multiplayer.status.pinging": "Ag pingiú...", "multiplayer.status.quitting": "Ag scor", "multiplayer.status.request_handled": "Déileáladh leis Iarratas ar stádas", "multiplayer.status.server_out_of_date": "Freastalaí as dáta!", "multiplayer.status.unknown": "???", "multiplayer.status.unrequested": "Fuarthas stádas gan iarraidh", "multiplayer.stopSleeping": "Fág do Leaba", "multiplayer.texturePrompt.line1": "Molann an freastalaí seo pacáiste acmhainní saincheaptha a úsáid.", "multiplayer.texturePrompt.line2": "An bhfuil fonn ort é a íosluchtú agus a shuiteáil go huathoibríoch?", "multiplayer.title": "Imir i mód Ilimreora", "narrator.button.accessibility": "Inrochtaineacht", "narrator.button.difficulty_lock": "Glas deacrachta", "narrator.button.difficulty_lock.locked": "Glasáilte", "narrator.button.difficulty_lock.unlocked": "Díghlasáilte", "narrator.button.language": "Teanga", "narrator.controls.bound": "Tá %s ceangailte le %s", "narrator.controls.reset": "Athshocraigh an cnaipe %s", "narrator.controls.unbound": "Níl %s ceangailte", "narrator.joining": "Ag ceangailt", "narrator.loading": "Ag lódáil: %s", "narrator.loading.done": "Déanta", "narrator.screen.title": "Scáileán Teidil", "narrator.select": "Roghnaithe: %s", "narrator.select.world": "Roghnaítear %s, imríodh ar %s, %s, %s, leagan %s", "narrator.toast.disabled": "Aithriseoir Díchumasaithe", "narrator.toast.enabled": "Aithriseoir Cumasaithe", "optimizeWorld.confirm.description": "Déanfaidh sé seo iarracht do dhomhan a optamú trína chinntiú go stóráiltear na sonraí go léir sa bhformáid cluiche is déanaí. Is féidir go mbeidh tamall an-fhada ag teastáil, de réir do dhomhain. É sin déanta, b’fhéidir go mbeidh do dhomhan níos tapúla ach ní bheidh sé comhoiriúnach le leaganacha níos sine den chluiche níos mó. An bhfuil tú cinnte gur maith leat dul ar aghaidh?", "optimizeWorld.confirm.title": "Optamaigh Domhan", "optimizeWorld.info.converted": "Smutáin uasghrádaithe: %s", "optimizeWorld.info.skipped": "Smutáin scipeáilte: %s", "optimizeWorld.info.total": "Iomlán na smután: %s", "optimizeWorld.stage.counting": "Ag cuntas smután...", "optimizeWorld.stage.failed": "Theip air :(", "optimizeWorld.stage.finished": "Ag críochnú...", "optimizeWorld.stage.upgrading": "Ag uasghrádú na smutáin uilig...", "optimizeWorld.title": "Ag optamú an domhain '%s'", "options.accessibility.text_background": "Cúlra an Téacs", "options.accessibility.text_background.chat": "Comhrá", "options.accessibility.text_background.everywhere": "Gach áit", "options.accessibility.text_background_opacity": "Teimhneacht Chúlra an Téacs", "options.accessibility.title": "Socruithe Inrochtaineachta...", "options.anaglyph": "Anaiglif 3D", "options.ao": "Soilsiú Slim", "options.ao.max": "Uasmhéid", "options.ao.min": "Íosmhéid", "options.ao.off": "AS", "options.attack.crosshair": "Crosribe", "options.attack.hotbar": "Mearbharra", "options.attackIndicator": "Táscaire Ionsaithe", "options.autoJump": "Uath-léim", "options.autoSuggestCommands": "Moltaí Ordaithe\n", "options.biomeBlendRadius": "Meascán Bithóim", "options.chat.color": "Dathanna", "options.chat.height.focused": "Airde le Fócas", "options.chat.height.unfocused": "Airde gan Fhócas", "options.chat.links": "Naisc Idirlín", "options.chat.links.prompt": "Leid do Naisc", "options.chat.opacity": "Teimhneacht Théacs an Chomhrá", "options.chat.scale": "Scála", "options.chat.title": "Socruithe Comhrá...", "options.chat.visibility": "Comhrá", "options.chat.visibility.full": "Léirítear", "options.chat.visibility.hidden": "Folaithe", "options.chat.visibility.system": "Orduithe Amháin", "options.chat.width": "Leithead", "options.chunks": "%s smután", "options.clouds.fancy": "Maisiúil", "options.clouds.fast": "Gasta", "options.controls": "Rialtáin...", "options.customizeTitle": "Saincheap Socruithe Domhain", "options.difficulty": "Deacracht", "options.difficulty.easy": "Éasca", "options.difficulty.hard": "Deacair", "options.difficulty.hardcore": "Truncáil", "options.difficulty.normal": "Gnách", "options.difficulty.peaceful": "Síochánta", "options.discrete_mouse_scroll": "Scrolláil Scoite", "options.entityShadows": "Scáileanna Aonán", "options.forceUnicodeFont": "Fórsáil Clófhoireann Unicode", "options.fov": "Réimse Radhairc", "options.fov.max": "Quake Pro", "options.fov.min": "Gnáth", "options.framerate": "%s fss", "options.framerateLimit": "Ráta Frámaí is Mó", "options.framerateLimit.max": "Gan teorainn", "options.fullscreen": "Lánscáileán", "options.fullscreen.current": "Reatha", "options.fullscreen.resolution": "Taifeach Lánscéaláin", "options.gamma": "Gile", "options.gamma.max": "Geal", "options.gamma.min": "Gruama", "options.graphics": "Grafaic", "options.graphics.fancy": "Maisiúil", "options.graphics.fast": "Gasta", "options.guiScale": "Scála GUI", "options.guiScale.auto": "Uathoibríoch", "options.hidden": "Ceilte", "options.invertMouse": "Inbhéartaigh an Luch", "options.language": "Teanga...", "options.languageWarning": "Is féidir nach bhfuil na haistriúcháin foirfe", "options.mainHand": "Lámh Cheannasach", "options.mainHand.left": "Lámh Chlé", "options.mainHand.right": "Lámh Dheas", "options.mipmapLevels": "Leibhéal MIP mapaí", "options.modelPart.cape": "Cába", "options.modelPart.hat": "Hata", "options.modelPart.jacket": "Seaicéad", "options.modelPart.left_pants_leg": "Osán Clé", "options.modelPart.left_sleeve": "Muinchille Chlé", "options.modelPart.right_pants_leg": "Osán Deas", "options.modelPart.right_sleeve": "Muinchille Dheas", "options.mouseWheelSensitivity": "Íogaireacht Scrollála", "options.mouse_settings": "Socruithe Luchóige...", "options.mouse_settings.title": "Socruithe Luchóige", "options.multiplayer.title": "Socruithe Ilimreora...", "options.music": "Ceol", "options.narrator": "Aithriseoir", "options.narrator.all": "Ag aithris gach rud", "options.narrator.chat": "Ag aithris comhrá", "options.narrator.notavailable": "Níl aithriseoir ar fáil", "options.narrator.off": "AS", "options.narrator.system": "Ag aithris córais", "options.off": "AS", "options.on": "ANN", "options.particles": "Cáithníní", "options.particles.all": "Gach rud", "options.particles.decreased": "Laghdaithe", "options.particles.minimal": "Íosta", "options.realmsNotifications": "Fógraí Realms", "options.reducedDebugInfo": "Eolas Dífhabhtúcháin Laghdaithe", "options.renderClouds": "Scamaill", "options.renderDistance": "Fad Rindreála", "options.resourcepack": "Pacáistí Acmhainní...", "options.sensitivity": "Íogaireacht", "options.sensitivity.max": "HIPEARLUAS!!!", "options.sensitivity.min": "*méanfach*", "options.showSubtitles": "Taispeáin fotheideal", "options.skinCustomisation": "Saincheapadh Culaithe...", "options.skinCustomisation.title": "Saincheapadh Craicinn", "options.snooper": "Ceadaigh Fairtheoir", "options.snooper.desc": "Bímid i gcónaí ag iarraidh Minecraft a fheabhsú agus ar mhaithe leis an méid sin, ba mhaith linn roinnt eolais a bhailiú. Cuireann seo ar an eolas muid ar na crua-earraí ar cheart tacú leo agus cad iad na fadhbanna is mó againn. Tugann sé léargas dúinn ar líon na n-imreoirí gníomhacha, ionas go mbeidh a fhios againn go bhfuil muid ag déanamh jab maith. Is féidir breathnú\u00a0ar an uile eolas atá bailithe againn thíos. Mura bhfuil tú ag iarraidh go mbaileofar do chuid eolais is féidir diúltú!", "options.snooper.title": "Seol sonraí chugainn!", "options.snooper.view": "Socruithe Fairtheora...", "options.sound": "Fuaim", "options.sounds": "Ceol & Fuaimeanna...", "options.sounds.title": "Roghanna Ceoil & Fuaime", "options.title": "Roghanna", "options.touchscreen": "Mód Scáileán Tadhaill", "options.vbo": "Úsáid VBOanna", "options.video": "Socruithe Físe...", "options.videoTitle": "Socruithe Físe", "options.viewBobbing": "Bocáil Amhairc", "options.visible": "Infheicthe", "options.vsync": "Úsáid VSync", "parsing.bool.expected": "Coinne le Boole", "parsing.bool.invalid": "Boole neamhbhailí, coinne le 'fíor' nó 'bréag' ach '%s' aimsithe", "parsing.double.expected": "Coinne le dúbailt", "parsing.double.invalid": "Dúbailt neamhbhailí '%s'", "parsing.expected": "Coinne le '%s'", "parsing.float.expected": "Coinne le teaghrán", "parsing.float.invalid": "Teaghrán neambhailí '%s'", "parsing.int.expected": "Coinne le slánuimhir", "parsing.int.invalid": "Slánuimhir neamhbhailí '%s'", "parsing.long.expected": "Coinne le fad", "parsing.long.invalid": "Fad neamhbhailí '%s'", "parsing.quote.escape": "Seicheamh éalaithe neamhbhailí '\\%s' sa teaghrán athfhriotail", "parsing.quote.expected.end": "Teaghrán athfhriotail gan deireadh", "parsing.quote.expected.start": "Coinne le hathfhriotal don theaghrán a thosú", "particle.notFound": "Cáithnín anaithnid: %s", "permissions.requires.entity": "Teastaíonn ar aonán ón ordú seo a rith", "permissions.requires.player": "Teastaíonn ar imreoir ón ordú seo a rith", "potion.potency.1": "II", "potion.potency.2": "III", "potion.potency.3": "IV", "potion.potency.4": "V", "potion.potency.5": "VI", "potion.whenDrank": "Éifeacht:", "realms.missing.module.error.text": "Ní féidir le Realms a oscail faoi láthair, baint triail as níos déanaí le do thoil", "realms.missing.snapshot.error.text": "Níl Realms tacaithe i roghbhlúirí faoi láthair", "recipe.notFound": "Oideas anaithnid: %s", "recipe.toast.description": "Féach ar do leabhar oideas", "recipe.toast.title": "Oidis Nua ar Fáil!", "record.nowPlaying": "Anois ag sheinm: %s", "resourcePack.available.title": "Pacáistí Acmhainní Inúsáidte", "resourcePack.broken_assets": "BRAITHEADH SÓCMHAINNÍ BRISTE", "resourcePack.folderInfo": "(Cuir pacáistí acmhainní anseo)", "resourcePack.incompatible": "Neamh-chomhoiriúnach", "resourcePack.incompatible.confirm.new": "Cruthaíodh an pacáiste acmhainní seo le haghaidh leagan Minecraft níos déanaí agus is féidir nach n-oibreoidh sé i gceart.", "resourcePack.incompatible.confirm.old": "Cruthaíodh an pacáiste acmhainní seo le haghaidh leagan Minecraft roimhe seo agus is féidir nach n-oibreoidh sé i gceart.", "resourcePack.incompatible.confirm.title": "An bhfuil tú cinnte gur mian leat an pacáiste acmhainní seo a lódáil?", "resourcePack.incompatible.new": "(Cruthaithe le haghaidh leagan Minecraft níos déanaí)", "resourcePack.incompatible.old": "(Cruthaithe le haghaidh leagan Minecraft roimhe seo)", "resourcePack.openFolder": "Oscail fillteán na bpacáistí acmhainní", "resourcePack.selected.title": "Pacáistí Acmhainní Roghnaithe", "resourcePack.server.name": "Acmhainní Sainiúla do Dhomhain", "resourcePack.title": "Roghnaigh Pacáistí Acmhainní", "resourcepack.downloading": "Ag íoslódáil Pacáiste Acmhainní", "resourcepack.progress": "Ag íoslódáil comhaid (%s MB)...", "resourcepack.requesting": "Ag déanamh iarratas...", "screenshot.failure": "Níorbh fhéidir gabháil scáileáin a shábháil: %s", "screenshot.success": "Sábháladh gabháil scáileáin mar %s", "selectServer.add": "Cuir freastalaí leis", "selectServer.defaultName": "Freastalaí Minecraft", "selectServer.delete": "Scrios", "selectServer.deleteButton": "Scrios", "selectServer.deleteQuestion": "An bhfuil tú cinnte gur mian leat an freastalaí seo a bhaint?", "selectServer.deleteWarning": "Beidh %s caillte go deo! (Tamall fada!)", "selectServer.direct": "Ceangal Díreach", "selectServer.edit": "Chur in eagar", "selectServer.empty": "folamh", "selectServer.hiddenAddress": "(Ceilte)", "selectServer.refresh": "Athnuaigh", "selectServer.select": "Ceangail leis", "selectServer.title": "Roghnaigh Freastalaí", "selectWorld.allowCommands": "Ceadaigh Caimiléireachtaí:", "selectWorld.allowCommands.info": "Orduithe cosúil le /gamemode, /experience", "selectWorld.backupEraseCache": "Glan na sonraí taiscthe", "selectWorld.backupJoinConfirmButton": "Cruthaigh cúltaca agus lódáil", "selectWorld.backupJoinSkipButton": "Tá a fhios agam cad atá á dhéanamh agam!", "selectWorld.backupQuestion": "An bhfuil tú cinnte gur mian leat an domhan seo a lódáil?", "selectWorld.backupQuestion.customized": "Ní thacaítear le domhain shaincheaptha a thuilleadh", "selectWorld.backupWarning": "Osclaíodh an domhan seo sa leagan %s an uair dheireanach; tá leagan %s agat anois. Le do thoil, déan cúltaca de ar eagla go dtarlódh truailliú domhain!", "selectWorld.backupWarning.customized": "Ar an drochuair, ní thacaímid le domhain shaincheaptha sa leagan seo de Minecraft. Mar sin féin, is féidir an domhan seo a lódáil agus beidh gach rud mar a bhí, ach ní bheidh tír-raon nua-ghinte saincheaptha níos mó. Gabhaigí ár leithscéal as an míchaoithiúlacht!", "selectWorld.bonusItems": "Cófra Bónais:", "selectWorld.cheats": "Caimiléireachtaí", "selectWorld.conversion": "Ní mór é a thiontú!", "selectWorld.create": "Cruthaigh Domhan Nua", "selectWorld.createDemo": "Imir i nDomhan Taispeána Nua", "selectWorld.customizeType": "Saincheap", "selectWorld.delete": "Scrios", "selectWorld.deleteButton": "Scrios", "selectWorld.deleteQuestion": "An bhfuil tú cinnte gur mian leat an domhan seo a scriosadh?", "selectWorld.deleteWarning": "Beidh %s caillte go deo! (Tamall fada!)", "selectWorld.edit": "Athraigh", "selectWorld.edit.backup": "Cruthaigh Cúltaca", "selectWorld.edit.backupCreated": "Cúltacaithe: %s", "selectWorld.edit.backupFailed": "Theip ar an gcúltacú", "selectWorld.edit.backupFolder": "Oscail Fillteán na gCúltacaí", "selectWorld.edit.backupSize": "méid: %s MB", "selectWorld.edit.openFolder": "Oscail Fillteán an Domhain", "selectWorld.edit.optimize": "Optamaigh Domhan", "selectWorld.edit.resetIcon": "Athshocraigh Deilbhín", "selectWorld.edit.save": "Sábháil", "selectWorld.edit.title": "Athraigh Domhan", "selectWorld.empty": "folamh", "selectWorld.enterName": "Ainm an Domhain", "selectWorld.enterSeed": "Síol don Ghineadóir Domhan", "selectWorld.futureworld.error.text": "Chuaigh rud éigin amú agus muid ag iarraidh domhan ó leagan níos déanaí a lódáil. B‘íogair an cás é ar an gcéad dul síos, tá brón orainn nár éirigh leis.", "selectWorld.futureworld.error.title": "Tharla earráid!", "selectWorld.gameMode": "Mód Cluiche", "selectWorld.gameMode.adventure": "Eachtra", "selectWorld.gameMode.adventure.line1": "Mar an gcéanna le mód marthanais, ach ní féidir", "selectWorld.gameMode.adventure.line2": "bloic a chur ná bloic a bhaint", "selectWorld.gameMode.creative": "Cruthaitheach", "selectWorld.gameMode.creative.line1": "Acmhainní gan teorainn, saor-eitilt agus", "selectWorld.gameMode.creative.line2": "scriosadh bloc ar an toirt", "selectWorld.gameMode.hardcore": "Antoisceach", "selectWorld.gameMode.hardcore.line1": "Mar an gcéanna le mód marthanais, faoi ghlas ar", "selectWorld.gameMode.hardcore.line2": "an deacracht is deacra, agus saol amháin agat", "selectWorld.gameMode.spectator": "Féachadóir", "selectWorld.gameMode.spectator.line1": "Tig leat breathnú\u00a0ach ná leag láimh", "selectWorld.gameMode.survival": "Marthanas", "selectWorld.gameMode.survival.line1": "Cuardaigh acmhainní, ceardaíocht, buaigh", "selectWorld.gameMode.survival.line2": "leibhéil, sláinte agus ocras", "selectWorld.hardcoreMode": "Antoisceach:", "selectWorld.hardcoreMode.info": "Scriosfar an Domhan ar do bhás", "selectWorld.load_folder_access": "Ní féidir léamh nó rochtain a fháil ar an bhfillteán ina bhfuil na domhain sábháilte!", "selectWorld.mapFeatures": "Gin Struchtúir:", "selectWorld.mapFeatures.info": "Sráidbhailte, doinsiúin srl", "selectWorld.mapType": "Cineál Domhain:", "selectWorld.mapType.normal": "Gnách", "selectWorld.moreWorldOptions": "Tuilleadh Roghanna Domhain...", "selectWorld.newWorld": "Domhan Nua", "selectWorld.recreate": "Athchruthaigh", "selectWorld.recreate.customized.text": "Ní thacaítear le domhain shaincheaptha sa leagan seo de Minecraft. Is féidir linn triail a bhaint as an domhan a athchruthú leis an síol agus leis na hairíonna céanna, ach beidh aon shaincheapaíocht talún caillte. Ár leithscéal as ucht aon mhíchaoithiúlacht!", "selectWorld.recreate.customized.title": "Níl tacaíocht ann do dhomhain shaincheaptha fós", "selectWorld.recreate.error.text": "Chuaigh rud éigin mícheart agus muid ag iarraidh domhan a athchruthú.", "selectWorld.recreate.error.title": "Tharla earráid!", "selectWorld.resultFolder": "Sábhálfar é san fhillteán:", "selectWorld.search": "cuardaigh domhain", "selectWorld.seedInfo": "Fág bán le haghaidh síl randamaigh", "selectWorld.select": "Imir sa Domhan Roghnaithe", "selectWorld.title": "Roghnaigh Domhan", "selectWorld.tooltip.fromNewerVersion1": "Sábháladh an domhan i leagan níos déanaí,", "selectWorld.tooltip.fromNewerVersion2": "seans go gcruthófar fadhbanna má déantar an domhan seo a lódáíl!", "selectWorld.tooltip.snapshot1": "Ná déan dearmad cúltaca a dhéanamh den domhan seo", "selectWorld.tooltip.snapshot2": "roimh duit é a lódáil sa roghbhlúire seo.", "selectWorld.tooltip.unsupported": "Ní thacaítear leis an domhan seo agus ní féidir é a imirt ach amháin i %s", "selectWorld.unable_to_load": "Ní féidir na domhain a lódáil", "selectWorld.version": "Leagan:", "selectWorld.versionJoinButton": "Lódáil ar aon nós", "selectWorld.versionQuestion": "An bhfuil tú cinnte gur mian leat an domhan seo a lódáil?", "selectWorld.versionUnknown": "anaithnid", "selectWorld.versionWarning": "D’imríodh an domhan seo i leagan %s an uair dheireanach agus is féidir go dtruailleofaí é dá lódálfá sa leagan seo é!", "selectWorld.world": "Domhan", "sign.edit": "Athraigh téacs comhartha", "slot.unknown": "Sliotán anaithnid '%s'", "soundCategory.ambient": "Timpeallacht", "soundCategory.block": "Bloic", "soundCategory.hostile": "Créatúir Naimhdeacha", "soundCategory.master": "Príomhrialtán Airde", "soundCategory.music": "Ceol", "soundCategory.neutral": "Créatúir Chairdiúla", "soundCategory.player": "Imreoirí", "soundCategory.record": "Júcbhosca/Bloic Nóta", "soundCategory.voice": "Glór/Caint", "soundCategory.weather": "Aimsir", "spectatorMenu.close": "Dún Roghchlár", "spectatorMenu.next_page": "Céad Leathanach Eile", "spectatorMenu.previous_page": "Leathanach Roimhe", "spectatorMenu.root.prompt": "Brúigh ar chnaipe chun ordú a roghnú, agus arís chun é a úsáid.", "spectatorMenu.team_teleport": "Teileapórtáil chuig Ball Foirne", "spectatorMenu.team_teleport.prompt": "Roghnaigh foireann chun teileapórtáil chuici", "spectatorMenu.teleport": "Teileapórtáil chuig Imreoir", "spectatorMenu.teleport.prompt": "Roghnaigh imreoir chun teileapórtáil chuige/chuici", "stat.blocksButton": "Bloic", "stat.generalButton": "Ginearálta", "stat.itemsButton": "Earraí", "stat.minecraft.animals_bred": "Ainmhithe Síolraithe", "stat.minecraft.aviate_one_cm": "Fad Slánaithe le hEilitreaim", "stat.minecraft.bell_ring": "Cloigíní Buailte", "stat.minecraft.boat_one_cm": "Fad Slánaithe i mBád", "stat.minecraft.clean_armor": "Píosaí Cathéide Glanta", "stat.minecraft.clean_banner": "Meirgí Glanta", "stat.minecraft.clean_shulker_box": "Glanadh Boscaí Síogadóirí", "stat.minecraft.climb_one_cm": "Fad Dreaptha", "stat.minecraft.crouch_one_cm": "Fad Cromtha", "stat.minecraft.damage_absorbed": "Damáiste Maolaithe", "stat.minecraft.damage_blocked_by_shield": "Damáiste Sáraithe le Sciath", "stat.minecraft.damage_dealt": "Damáiste Tugtha", "stat.minecraft.damage_dealt_absorbed": "Damáiste Déanta (Maolaithe)", "stat.minecraft.damage_dealt_resisted": "Damáiste Déanta (Seasta)", "stat.minecraft.damage_resisted": "Damáiste Seasta", "stat.minecraft.damage_taken": "Damáiste Glactha", "stat.minecraft.deaths": "Líon na mBásanna", "stat.minecraft.drop": "Earraí Ligthe Uait", "stat.minecraft.eat_cake_slice": "Slisne Cáca Ite", "stat.minecraft.enchant_item": "Earraí curtha faoi dhraíocht", "stat.minecraft.fall_one_cm": "Fad Tite", "stat.minecraft.fill_cauldron": "Coirí Líonta", "stat.minecraft.fish_caught": "Éisc Gafa", "stat.minecraft.fly_one_cm": "Fad Eitilte", "stat.minecraft.horse_one_cm": "Fad Slánaithe ar Capall", "stat.minecraft.inspect_dispenser": "Teilgeoirí Cuardaithe", "stat.minecraft.inspect_dropper": "Dáileoirí Cuardaithe", "stat.minecraft.inspect_hopper": "Crannóga Cuardaithe", "stat.minecraft.interact_with_beacon": "Idirghníomhuithe le Rabhcán", "stat.minecraft.interact_with_blast_furnace": "Tá foirnéis soinneáin á húsáid", "stat.minecraft.interact_with_brewingstand": "Idirghníomhuithe le Seastán Grúdaireachta", "stat.minecraft.interact_with_campfire": "Tá tine champa á húsáid", "stat.minecraft.interact_with_cartography_table": "Idirgníomhaithe leis an mBord Caragrafaíochta", "stat.minecraft.interact_with_crafting_table": "Idirghníomhuithe le Bord Ceardaíochta", "stat.minecraft.interact_with_furnace": "Idirghníomhuithe le Foirnéis", "stat.minecraft.interact_with_lectern": "Tá léachtán á úsáid", "stat.minecraft.interact_with_loom": "Idirghníomhú le Seol", "stat.minecraft.interact_with_smoker": "Tá deatóir á úsáid", "stat.minecraft.interact_with_stonecutter": "Idirghníomhú le Snoíodóir", "stat.minecraft.jump": "Léimeanna", "stat.minecraft.junk_fished": "Dramhaíl Iascaireachta", "stat.minecraft.leave_game": "Cluichí scortha", "stat.minecraft.minecart_one_cm": "Fad Slánaithe i gCairt Mianaigh", "stat.minecraft.mob_kills": "Créatúir Maraithe", "stat.minecraft.open_barrel": "Osclaíodh bairillí", "stat.minecraft.open_chest": "Cófraí a d'oscail tú", "stat.minecraft.open_enderchest": "Cófra na Críche a d'oscail tú", "stat.minecraft.open_shulker_box": "Boscaí Slíogadóra Oscailte", "stat.minecraft.pig_one_cm": "Fad Slánaithe ar Muc", "stat.minecraft.play_noteblock": "Bloic Nóta a sheinn tú", "stat.minecraft.play_one_minute": "Nóiméid Imeartha", "stat.minecraft.play_record": "Dioscaí Ceoil Imrithe", "stat.minecraft.player_kills": "Maruithe Imreoirí", "stat.minecraft.pot_flower": "Plandaí curtha i bpotaí", "stat.minecraft.raid_trigger": "Ruaige Tosaithe", "stat.minecraft.raid_win": "Ruaige Buaite", "stat.minecraft.ring_bell": "Cloigíní Buailte", "stat.minecraft.sleep_in_bed": "Oícheanta i Leaba", "stat.minecraft.sneak_time": "Am ag téaltú", "stat.minecraft.sprint_one_cm": "Fad Rite", "stat.minecraft.swim_one_cm": "Fad Snáfa", "stat.minecraft.talked_to_villager": "Caint le Sráideánaigh", "stat.minecraft.time_since_death": "Ón Bás Deireannach", "stat.minecraft.time_since_rest": "Ón Sos Deireannach", "stat.minecraft.traded_with_villager": "Trádáil le Sráideánaigh", "stat.minecraft.treasure_fished": "Maoin Iascaireachta", "stat.minecraft.trigger_trapped_chest": "Cófraí Gaiste Scaoilte", "stat.minecraft.tune_noteblock": "Bloic Nóta a thiúin tú", "stat.minecraft.use_cauldron": "Uisce Bainte as Coirí", "stat.minecraft.walk_on_water_one_cm": "Fad Siúltar ar Uisce", "stat.minecraft.walk_one_cm": "Fad Siúlta", "stat.minecraft.walk_under_water_one_cm": "Fad Siúlta faoin Uisce", "stat.mobsButton": "Créatúir", "stat_type.minecraft.broken": "Amanna Briste", "stat_type.minecraft.crafted": "Déanta", "stat_type.minecraft.dropped": "Ligthe Uait", "stat_type.minecraft.killed": "Mharaigh tú %s %s", "stat_type.minecraft.killed.none": "Níor mharaigh tú %s riamh", "stat_type.minecraft.killed_by": "Mharaigh %s thú %s uair(e)", "stat_type.minecraft.killed_by.none": "Níor mharaigh %s riamh thú", "stat_type.minecraft.mined": "Tochailte", "stat_type.minecraft.picked_up": "Bailithe", "stat_type.minecraft.used": "Úsáidte", "stats.tooltip.type.statistic": "Staitistic", "structure_block.button.detect_size": "AIMSIGH", "structure_block.button.load": "LÓDÁIL", "structure_block.button.save": "SÁBHÁIL", "structure_block.custom_data": "Ainm Chlib Sonraí Saincheaptha", "structure_block.detect_size": "Aimsigh méid & suíomh an struchtúir:", "structure_block.hover.corner": "Mód Cúinní: %s", "structure_block.hover.data": "Mód Sonraí: %s", "structure_block.hover.load": "Mód Lódála: %s", "structure_block.hover.save": "Mód Sábhála: %s", "structure_block.include_entities": "Aonáin san áireamh:", "structure_block.integrity": "Sláine an Struchtúir agus Síol", "structure_block.integrity.integrity": "Sláine an Struchtúir", "structure_block.integrity.seed": "Struchtúɼ an tSíl", "structure_block.invalid_structure_name": "Ainm struchtúir neamhbhailí '%s'", "structure_block.load_not_found": "Níl an struchtúr '%s' le fáil ", "structure_block.load_prepare": "Suíomh don struchtúr '%s' réitithe", "structure_block.load_success": "Lódáladh struchtúr ó '%s'", "structure_block.mode.corner": "Cúinne", "structure_block.mode.data": "Mód Sonraí", "structure_block.mode.load": "Lódáil", "structure_block.mode.save": "Sábháil", "structure_block.mode_info.corner": "Mód cúinní - marcóir curtha agus méide", "structure_block.mode_info.data": "Mód sonraí - marcóir loighic cluiche", "structure_block.mode_info.load": "Mód lódála - lódáil ó chomhad", "structure_block.mode_info.save": "Mód sábhála - scríobh go comhad", "structure_block.position": "Suíomh Coibhneasta", "structure_block.position.x": "suíomh coibhneasta x", "structure_block.position.y": "suíomh coibhneasta y", "structure_block.position.z": "suíomh coibhneasta z", "structure_block.save_failure": "Theip ar shábháil an struchtúir '%s'", "structure_block.save_success": "Sábháladh an struchtúr mar '%s'", "structure_block.show_air": "Taispeáin bloic dofheicthe:", "structure_block.show_boundingbox": "Taispeáin bosca teorann:", "structure_block.size": "Méid an Struchtúir", "structure_block.size.x": "tomhas an struchtúir x", "structure_block.size.y": "tomhas an struchtúir y", "structure_block.size.z": "tomhas an struchtúir z", "structure_block.size_failure": "Níorbh fhéidir méid an struchtúir a aimsiú. Cuir cúinní leis agus ainmneacha orthu de réir an struchtúir", "structure_block.size_success": "Méid aimsithe le haghaidh '%s'", "structure_block.structure_name": "Ainm an Struchtúir", "subtitles.ambient.cave": "Fuaim dhiamhair", "subtitles.block.anvil.destroy": "Scriosadh inneoin", "subtitles.block.anvil.land": "Thuirling inneoin", "subtitles.block.anvil.use": "Úsáideadh inneoin", "subtitles.block.barrel.close": "Dúnadh bairille", "subtitles.block.barrel.open": "Osclaíodh bairille", "subtitles.block.bell.resonate": "Athbhunaíonn Bell", "subtitles.block.bell.use": "Tá clog ag bualadh", "subtitles.block.blastfurnace.fire_crackle": "Tá foirnéis soinneáin ag cnagarnach", "subtitles.block.brewing_stand.brew": "Boilgearnach Sheastán Grúdaireachta", "subtitles.block.bubble_column.bubble_pop": "Pléascann bolgáin", "subtitles.block.bubble_column.upwards_ambient": "Ritheann bolgáin", "subtitles.block.bubble_column.upwards_inside": "Réabann bolgáin", "subtitles.block.bubble_column.whirlpool_ambient": "Luascann bolgáin timpeall", "subtitles.block.bubble_column.whirlpool_inside": "Ropann bolgáin", "subtitles.block.button.click": "Cnaipe ag cliceáil", "subtitles.block.campfire.crackle": "Tá tine champa ag cnagarnach", "subtitles.block.chest.close": "Cófra ag dúnadh", "subtitles.block.chest.locked": "Cófra faoi ghlas", "subtitles.block.chest.open": "Cófra ag oscailt", "subtitles.block.chorus_flower.death": "Bláth an churfá ag seargadh", "subtitles.block.chorus_flower.grow": "Bláth Curfá ag fás", "subtitles.block.comparator.click": "Comparadóir ag cliceáil", "subtitles.block.dispenser.dispense": "Teilgeadh earra", "subtitles.block.dispenser.fail": "Theip ar theilgeoir", "subtitles.block.door.toggle": "Doras ag díoscadh", "subtitles.block.fence_gate.toggle": "Geata ag dioscadh", "subtitles.block.fire.ambient": "Tine ag brioscarnach", "subtitles.block.fire.extinguish": "Múchadh tine", "subtitles.block.furnace.fire_crackle": "Foirnéis ag brioscarnach", "subtitles.block.generic.break": "Briseadh bloc", "subtitles.block.generic.footsteps": "Coiscéimeanna", "subtitles.block.generic.hit": "Bloc ag briseadh", "subtitles.block.generic.place": "Bloc curtha", "subtitles.block.grindstone.use": "Tá cloch fhaobhair á húsáid", "subtitles.block.iron_trapdoor.close": "Osclaíonn comhla thógála", "subtitles.block.iron_trapdoor.open": "Dúnann comhla thógála", "subtitles.block.lava.ambient": "Laibhe ag preabadh", "subtitles.block.lava.extinguish": "Laibhe ag siosadh", "subtitles.block.lever.click": "Luamhán ag cliceáil", "subtitles.block.note_block.note": "Bloc Nóta ag seinm", "subtitles.block.piston.move": "Loine ag gluaiseacht", "subtitles.block.portal.ambient": "Seabhrán Tairsigh", "subtitles.block.pressure_plate.click": "Brúphláta ag cliceáil", "subtitles.block.redstone_torch.burnout": "Tóirse ag siosarnach", "subtitles.block.shulker_box.close": "Dúnann an tSlíogadóir", "subtitles.block.shulker_box.open": "Osclaíonn an tSlíogadóir", "subtitles.block.smoker.smoke": "Tá deatóir ag deatú", "subtitles.block.trapdoor.toggle": "Comhla thógála ag díoscadh", "subtitles.block.tripwire.attach": "Sreang Thuisle ag ceangail", "subtitles.block.tripwire.click": "Sreang Thuisle ag cliceáil", "subtitles.block.tripwire.detach": "Sreang Thuisle ag scor", "subtitles.block.water.ambient": "Uisce ag rith", "subtitles.enchant.thorns.hit": "Dealga ag priocadh", "subtitles.entity.armor_stand.fall": "Thit rud éigin", "subtitles.entity.arrow.hit": "Saighead ag buaileadh", "subtitles.entity.arrow.hit_player": "Imreoir buailte", "subtitles.entity.arrow.shoot": "Scaoileadh saighead", "subtitles.entity.bat.ambient": "Ialtóg ag bíogarnach", "subtitles.entity.bat.death": "Ialtóg ag fáil bháis", "subtitles.entity.bat.hurt": "Gortaítear ialtóg", "subtitles.entity.bat.takeoff": "Ialtóg ag éirí in airde", "subtitles.entity.blaze.ambient": "Lasaire ag análú", "subtitles.entity.blaze.burn": "Lasaire ag brioscarnach", "subtitles.entity.blaze.death": "Lasaire ag fáil bháis", "subtitles.entity.blaze.hurt": "Gortaítear lasaire", "subtitles.entity.blaze.shoot": "Lasaire ag scaoileadh", "subtitles.entity.cat.ambient": "Cat ag meamhlach", "subtitles.entity.cat.death": "Cat ag fáil bháis", "subtitles.entity.cat.hurt": "Gortaítear cat", "subtitles.entity.chicken.ambient": "Sicín ag gocarsach", "subtitles.entity.chicken.death": "Sicín ag fáil bháis", "subtitles.entity.chicken.egg": "Plab sicín", "subtitles.entity.chicken.hurt": "Gortaítear sicín", "subtitles.entity.cod.death": "Trosc ag fáil bháis", "subtitles.entity.cod.flop": "Flup an Troisc", "subtitles.entity.cod.hurt": "Gortaítear trosc", "subtitles.entity.cow.ambient": "Géimneach bó", "subtitles.entity.cow.death": "Bó ag fáil bháis", "subtitles.entity.cow.hurt": "Gortaítear bó", "subtitles.entity.cow.milk": "Bó á bleán", "subtitles.entity.creeper.death": "Téaltóir ag fáil bháis", "subtitles.entity.creeper.hurt": "Gortaíodh an Creeper", "subtitles.entity.creeper.primed": "Tá an Creeper ag siosadh", "subtitles.entity.dolphin.ambient": "Deilf ag gíoglach", "subtitles.entity.dolphin.ambient_water": "Deilf ag feadaíl", "subtitles.entity.dolphin.attack": "Deilf ag ionsaí", "subtitles.entity.dolphin.death": "Deilf ag fáil bháis", "subtitles.entity.dolphin.eat": "Deilf ag ithe", "subtitles.entity.dolphin.hurt": "Gortaítear deilf", "subtitles.entity.dolphin.jump": "Deilf ag léim", "subtitles.entity.dolphin.play": "Deilf ag déanamh spraoi", "subtitles.entity.dolphin.splash": "Deilf ag slaparnach", "subtitles.entity.dolphin.swim": "Deilf ag snámh", "subtitles.entity.donkey.ambient": "Asal ag rá uí-a-hó", "subtitles.entity.donkey.angry": "Asal ag seitreach", "subtitles.entity.donkey.chest": "Cófra asail feistithe", "subtitles.entity.donkey.death": "Asal ag fail bháis", "subtitles.entity.donkey.hurt": "Gortaítear asal", "subtitles.entity.drowned.ambient": "Déanann an Báiteachán glothar", "subtitles.entity.drowned.death": "Báiteachán ag fáil bháis", "subtitles.entity.drowned.hurt": "Gortaítear báiteachán", "subtitles.entity.drowned.shoot": "Caitheann an Báiteachán Trírinn", "subtitles.entity.drowned.step": "Téann an Báiteachán", "subtitles.entity.drowned.swim": "Snámhann an Báiteachán", "subtitles.entity.egg.throw": "Lainseáiltear ubh", "subtitles.entity.elder_guardian.ambient": "Éagaoineann Coimeádaí Sinsearach", "subtitles.entity.elder_guardian.ambient_land": "Flap an Choimeádaí Shinsearaigh", "subtitles.entity.elder_guardian.curse": "Mallaíonn Coimeádaí Sinsearach", "subtitles.entity.elder_guardian.death": "Coimeádaí Sinsearach ag fáil bháis", "subtitles.entity.elder_guardian.flop": "Flup an Choimeádaí Shinsearaigh", "subtitles.entity.elder_guardian.hurt": "Gortaítear Coimeádaí Sinsearach", "subtitles.entity.ender_dragon.ambient": "Dragan ag búireach", "subtitles.entity.ender_dragon.death": "Dragan ag fáil bháis", "subtitles.entity.ender_dragon.flap": "Dragan ag buaileadh a sciatháin", "subtitles.entity.ender_dragon.growl": "Dragan ag drantú", "subtitles.entity.ender_dragon.hurt": "Gortaítear dragan", "subtitles.entity.ender_dragon.shoot": "Dragan ag scaoileadh", "subtitles.entity.ender_eye.launch": "Súil na Críche ag scinneadh", "subtitles.entity.ender_pearl.throw": "Lainseáiltear Péarla na Críche", "subtitles.entity.enderman.ambient": "Críochnaitheoir ag vúpáil", "subtitles.entity.enderman.death": "Críochnaitheoir ag fáil bháis", "subtitles.entity.enderman.hurt": "Gortaítear críochnaitheoir", "subtitles.entity.enderman.stare": "Críochnaitheoir ag ligean béice", "subtitles.entity.enderman.teleport": "Críochnaitheoir ag teileapórtáil", "subtitles.entity.endermite.ambient": "Fríd na Críche ag sciurdadh", "subtitles.entity.endermite.death": "Fríd na Críche ag fáil bháis", "subtitles.entity.endermite.hurt": "Gortaítear fríd na críche", "subtitles.entity.evoker.ambient": "Gairmneachán ag monabhar", "subtitles.entity.evoker.cast_spell": "Gairmneachán ag cur a ortha", "subtitles.entity.evoker.celebrate": "Céiliúradh na nGairmneacháin", "subtitles.entity.evoker.death": "Gairmneachán ag fáil bháis", "subtitles.entity.evoker.hurt": "Gortaítear Gairmneachán", "subtitles.entity.evoker.prepare_attack": "Gairmneachán ag ullmhú a ionsaí", "subtitles.entity.evoker.prepare_summon": "Gairmneachán ag ullmhú a ghairm", "subtitles.entity.evoker.prepare_wololo": "Gairmneachán ag ullmhú a ortha", "subtitles.entity.evoker_fangs.attack": "Fiacla ag tabhairt áladh", "subtitles.entity.experience_orb.pickup": "Pointí taithí faighte", "subtitles.entity.firework_rocket.blast": "Tine Ealaíne ag pléascadh", "subtitles.entity.firework_rocket.launch": "Tine Ealaíne ag lainseáil", "subtitles.entity.firework_rocket.twinkle": "Tine Ealaíne ag drithliú", "subtitles.entity.fishing_bobber.splash": "Buimbiléad ag slaparnach", "subtitles.entity.fishing_bobber.throw": "Buimbiléad caite amach", "subtitles.entity.fox.aggro": "Tá fearg ar an sionnach", "subtitles.entity.fox.ambient": "Tá an tsionnach ag bíogarnach", "subtitles.entity.fox.bite": "Baineann an tsionnach greim as", "subtitles.entity.fox.death": "Fuair an tsionnach bás", "subtitles.entity.fox.eat": "Itheann an tsionnach", "subtitles.entity.fox.hurt": "Tá tinn ag an sionnach", "subtitles.entity.fox.screech": "Scréachann an sionnach", "subtitles.entity.fox.sleep": "Srannann an tsionnach", "subtitles.entity.fox.sniff": "Bolaíonn an tsionnach", "subtitles.entity.fox.spit": "Caitheann an tsionnach seile", "subtitles.entity.generic.big_fall": "Thit rud éigin", "subtitles.entity.generic.burn": "Dó", "subtitles.entity.generic.death": "Ag fáil bháis", "subtitles.entity.generic.drink": "Súimíneacht", "subtitles.entity.generic.eat": "Ag ith", "subtitles.entity.generic.explode": "Pléasc", "subtitles.entity.generic.extinguish_fire": "Tine dá múchadh", "subtitles.entity.generic.hurt": "Gortaítear rud éigin", "subtitles.entity.generic.small_fall": "Thuisligh rud éigin", "subtitles.entity.generic.splash": "Stealladh", "subtitles.entity.generic.swim": "Snámh", "subtitles.entity.ghast.ambient": "Uafaireach ag caoineadh", "subtitles.entity.ghast.death": "Uafaireach ag fáil bháis", "subtitles.entity.ghast.hurt": "Gortaítear uafaireach", "subtitles.entity.ghast.shoot": "Uafaireach ag scaoileadh", "subtitles.entity.guardian.ambient": "Éagaoineann Coimeádaí", "subtitles.entity.guardian.ambient_land": "Flap an Choimeádaí", "subtitles.entity.guardian.attack": "Scaoileann Coimeádaí", "subtitles.entity.guardian.death": "Coimeádaí ag fáil bháis", "subtitles.entity.guardian.flop": "Flup an Choimeádaí", "subtitles.entity.guardian.hurt": "Gortaítear Coimeádaí", "subtitles.entity.horse.ambient": "Capall ag seitreach", "subtitles.entity.horse.angry": "Tá an Capall ag seitreach", "subtitles.entity.horse.armor": "Cathéide chapaill feistithe", "subtitles.entity.horse.breathe": "Capall ag análú", "subtitles.entity.horse.death": "Capall ag fail bháis", "subtitles.entity.horse.eat": "Capall ag ithe", "subtitles.entity.horse.gallop": "Capall ag dul ar cosa in airde", "subtitles.entity.horse.hurt": "Gortaítear capall", "subtitles.entity.horse.jump": "Capall ag léimneach", "subtitles.entity.horse.saddle": "Diallait feistithe", "subtitles.entity.husk.ambient": "Seargán ag ligean cnead as", "subtitles.entity.husk.converted_to_zombie": "Seargán ag tiontú ina Zombaí", "subtitles.entity.husk.death": "Seargán ag fáil bháis", "subtitles.entity.husk.hurt": "Gortaítear Seargán", "subtitles.entity.illusioner.ambient": "Doilfeánach ag monabhar", "subtitles.entity.illusioner.cast_spell": "Doilfeánach ag cur a ortha", "subtitles.entity.illusioner.death": "Doilfeánach ag fáil bháis", "subtitles.entity.illusioner.hurt": "Gortaítear doilfeánach", "subtitles.entity.illusioner.mirror_move": "Doilfeánach ag díláithriú", "subtitles.entity.illusioner.prepare_blindness": "Doilfeánach ag ullmhú ortha daille", "subtitles.entity.illusioner.prepare_mirror": "Doilfeánach ag ullmhú ortha íomhá scáthánach", "subtitles.entity.iron_golem.attack": "Gólam Iarainn ag ionsaí", "subtitles.entity.iron_golem.death": "Gólam Iarainn ag fail bháis", "subtitles.entity.iron_golem.hurt": "Gortaítear gólam iarainn", "subtitles.entity.item.break": "Earra ag briseadh", "subtitles.entity.item.pickup": "Plab earra", "subtitles.entity.item_frame.add_item": "Fráma Earra ag líonadh", "subtitles.entity.item_frame.break": "Fráma Earra ag briseadh", "subtitles.entity.item_frame.place": "Fráma Earra curtha", "subtitles.entity.item_frame.remove_item": "Fráma Earra ag folmhú", "subtitles.entity.item_frame.rotate_item": "Fráma Earra ag cliceáil", "subtitles.entity.leash_knot.break": "Snaidhm éille ag briseadh", "subtitles.entity.leash_knot.place": "Snaidhm éille ceangailte", "subtitles.entity.lightning_bolt.impact": "Splanc thintrí ag buaileadh", "subtitles.entity.lightning_bolt.thunder": "Tormáil toirní", "subtitles.entity.llama.ambient": "Láma ag méileach", "subtitles.entity.llama.angry": "Tá an Láma ag geonaíl go feargach", "subtitles.entity.llama.chest": "Cófra láma feistithe", "subtitles.entity.llama.death": "Láma ag fáil bháis", "subtitles.entity.llama.eat": "Láma ag ith", "subtitles.entity.llama.hurt": "Gortaítear Láma", "subtitles.entity.llama.spit": "Láma ag caitheamh seile", "subtitles.entity.llama.step": "Coiscéim láma", "subtitles.entity.llama.swag": "Maisítear Láma", "subtitles.entity.magma_cube.death": "Ciúb Magma ag fáil bháis", "subtitles.entity.magma_cube.hurt": "Gortaítear ciúb magma", "subtitles.entity.magma_cube.squish": "Ciúb Magma ag fáscadh", "subtitles.entity.minecart.riding": "Cairt Mianaigh ag rolladh", "subtitles.entity.mooshroom.convert": "Athraíonn an Múisiriún go hiomlán", "subtitles.entity.mooshroom.eat": "Itheann an Múisiriún", "subtitles.entity.mooshroom.milk": "Blíodh an Múisiriún", "subtitles.entity.mooshroom.suspicious_milk": "Blíodh an Múisiriún go hamhrasach", "subtitles.entity.mule.ambient": "Miúil ag rá uí-a-hó", "subtitles.entity.mule.chest": "Cófra miúile feistithe", "subtitles.entity.mule.death": "Miúil ag fáil bháis", "subtitles.entity.mule.hurt": "Gortaítear miúil", "subtitles.entity.painting.break": "Pictiúr ag briseadh", "subtitles.entity.painting.place": "Pictiúr curtha", "subtitles.entity.panda.aggressive_ambient": "Lig an Panda osnaíl", "subtitles.entity.panda.ambient": "Tá saothar ar an bPanda", "subtitles.entity.panda.bite": "Tá an Panda ag baineadh greime as", "subtitles.entity.panda.cant_breed": "Tá an Panda ag mionghéimneach", "subtitles.entity.panda.death": "Fuair an Panda bás", "subtitles.entity.panda.eat": "Tá an Panda ag ithe", "subtitles.entity.panda.hurt": "Gortaíodh an Panda", "subtitles.entity.panda.pre_sneeze": "Tá cigilt i srón an Phanda", "subtitles.entity.panda.sneeze": "Lig an Panda sraoth", "subtitles.entity.panda.step": "Tá an Panda ag teacht", "subtitles.entity.panda.worried_ambient": "Tá an Panda ag pusaíl", "subtitles.entity.parrot.ambient": "Labhraíonn an pearóid", "subtitles.entity.parrot.death": "Pearóid ag fáil bháis", "subtitles.entity.parrot.eats": "Itheann an pearóid", "subtitles.entity.parrot.hurts": "Gortaítear pearóid", "subtitles.entity.parrot.imitate.blaze": "Pearóid ag análú", "subtitles.entity.parrot.imitate.creeper": "Tá an Phearóid ag siosadh", "subtitles.entity.parrot.imitate.drowned": "Pearóid ag glugarnach", "subtitles.entity.parrot.imitate.elder_guardian": "Flap na pearóide", "subtitles.entity.parrot.imitate.ender_dragon": "Búireann an pearóid", "subtitles.entity.parrot.imitate.enderman": "Pearóid ag vúpáil", "subtitles.entity.parrot.imitate.endermite": "Pearóid ag sciurdadh", "subtitles.entity.parrot.imitate.evoker": "Pearóid ag monabhar", "subtitles.entity.parrot.imitate.ghast": "Pearóid ag caoineadh", "subtitles.entity.parrot.imitate.guardian": "Tá an Pearóid ag cneadach", "subtitles.entity.parrot.imitate.husk": "Pearóid ag ligean cnead as", "subtitles.entity.parrot.imitate.illusioner": "Pearóid ag monabhar", "subtitles.entity.parrot.imitate.magma_cube": "Pearóid ag fáscadh", "subtitles.entity.parrot.imitate.panda": "Pearóid agus saothar anála air", "subtitles.entity.parrot.imitate.phantom": "Pearóid ag scréachach", "subtitles.entity.parrot.imitate.pillager": "Pearóid ag monabhar", "subtitles.entity.parrot.imitate.polar_bear": "Pearóid ag ligean cnead as", "subtitles.entity.parrot.imitate.ravager": "Pearóid ag gnúsachtach", "subtitles.entity.parrot.imitate.shulker": "Pearóid ag slíocadh", "subtitles.entity.parrot.imitate.silverfish": "Pearóid ag siosadh", "subtitles.entity.parrot.imitate.skeleton": "Cnagarnach na pearóide", "subtitles.entity.parrot.imitate.slime": "Pearóid ag fáscadh", "subtitles.entity.parrot.imitate.spider": "Pearóid ag siosadh", "subtitles.entity.parrot.imitate.stray": "Cnagarnach na pearóide", "subtitles.entity.parrot.imitate.vex": "Pearóid ag buaireamh", "subtitles.entity.parrot.imitate.vindicator": "Pearóid ag mungailt", "subtitles.entity.parrot.imitate.witch": "Pearóid ag scigireacht", "subtitles.entity.parrot.imitate.wither": "Pearóid corraithe", "subtitles.entity.parrot.imitate.wither_skeleton": "Cnagarnach na pearóide", "subtitles.entity.parrot.imitate.wolf": "Pearóid agus saothar anála air", "subtitles.entity.parrot.imitate.zombie": "Pearóid ag ligean cnead as", "subtitles.entity.parrot.imitate.zombie_pigman": "Pearóid ag gnúsachtach", "subtitles.entity.parrot.imitate.zombie_villager": "Pearóid ag ligean cnead as", "subtitles.entity.phantom.ambient": "Púca ag scréachach", "subtitles.entity.phantom.bite": "Púca ag baint greim as rud éigin", "subtitles.entity.phantom.death": "Púca ag fáil bháis", "subtitles.entity.phantom.flap": "Púca ag buaileadh a sciatháin", "subtitles.entity.phantom.hurt": "Gortaítear púca", "subtitles.entity.phantom.swoop": "Púca ag teacht anuas de ruathar", "subtitles.entity.pig.ambient": "Muc ag gnúsachtach", "subtitles.entity.pig.death": "Muc ag fáil bháis", "subtitles.entity.pig.hurt": "Gortaítear muc", "subtitles.entity.pig.saddle": "Diallait feistithe", "subtitles.entity.pillager.ambient": "Tá an Creachadóir ag gearán", "subtitles.entity.pillager.celebrate": "Céiliúradh na gCreachadóirí", "subtitles.entity.pillager.death": "Fuair an Creachadóir bás", "subtitles.entity.pillager.hurt": "Gortaíodh an Creachadóir", "subtitles.entity.player.burp": "Brúcht", "subtitles.entity.player.death": "Imreoir ag fáil bháis", "subtitles.entity.player.hurt": "Gortaítear imreoir", "subtitles.entity.player.levelup": "Imreoir ag clingeadh", "subtitles.entity.polar_bear.ambient": "Béar Bán ag ligean cnead as", "subtitles.entity.polar_bear.ambient_baby": "Béar Bán ag dordán", "subtitles.entity.polar_bear.death": "Béar Bán ag fáil bháis", "subtitles.entity.polar_bear.hurt": "Gortaítear Béar Bán", "subtitles.entity.polar_bear.warning": "Béar Bán ag búireach", "subtitles.entity.potion.splash": "Buidéal ag briseadh", "subtitles.entity.potion.throw": "Lainseáiltear buidéal", "subtitles.entity.puffer_fish.blow_out": "Iasc Bolgach ag díbholgadh", "subtitles.entity.puffer_fish.blow_up": "Iasc Bolgach ag bolgadh", "subtitles.entity.puffer_fish.death": "Iasc bolgach ag fáil bháis", "subtitles.entity.puffer_fish.flop": "Flup an Éisc Bholgaigh", "subtitles.entity.puffer_fish.hurt": "Gortaítear iasc bolgach", "subtitles.entity.puffer_fish.sting": "Cealgaíonn an tIasc Bolgach", "subtitles.entity.rabbit.ambient": "Coinín ag bíogarnach", "subtitles.entity.rabbit.attack": "Coinín ag ionsaí", "subtitles.entity.rabbit.death": "Coinín ag fáil bháis", "subtitles.entity.rabbit.hurt": "Gortaítear coinín", "subtitles.entity.rabbit.jump": "Coinín ag preabadh", "subtitles.entity.ravager.ambient": "Tá an Sladaire ag gnúsachtach", "subtitles.entity.ravager.attack": "Tá an Sladaire ag baint greime as", "subtitles.entity.ravager.celebrate": "Céiliúradh na Sladairí", "subtitles.entity.ravager.death": "Fair an Sladaire bás", "subtitles.entity.ravager.hurt": "Gortaíodh an Sladaire", "subtitles.entity.ravager.roar": "Tá an Sladaire ag búireadh", "subtitles.entity.ravager.step": "Tá an Sladaire ag teacht", "subtitles.entity.ravager.stunned": "Cuireadh an Sladaire ina stad", "subtitles.entity.salmon.death": "Bradán ag fáil bháis", "subtitles.entity.salmon.flop": "Flup an Bhradáin", "subtitles.entity.salmon.hurt": "Gortaítear bradán", "subtitles.entity.sheep.ambient": "Caora ag méileach", "subtitles.entity.sheep.death": "Caora ag fáil bháis", "subtitles.entity.sheep.hurt": "Gortaítear caora", "subtitles.entity.shulker.ambient": "Slíocann an tSlíogadóir", "subtitles.entity.shulker.close": "Dúnann an tSlíogadóir", "subtitles.entity.shulker.death": "Slíogadóir ag fáil bháis", "subtitles.entity.shulker.hurt": "Gortaítear slíogadóir", "subtitles.entity.shulker.open": "Osclaíonn an tSlíogadóir", "subtitles.entity.shulker.shoot": "Slíogadóir ag scaoileadh", "subtitles.entity.shulker.teleport": "Slíogadóir ag teileapórtáil", "subtitles.entity.shulker_bullet.hit": "Pléascann piléar an slíogadóra", "subtitles.entity.shulker_bullet.hurt": "Briseann piléar an slíogadóra", "subtitles.entity.silverfish.ambient": "Gilín ag siosadh", "subtitles.entity.silverfish.death": "Gilín ag fáil bháis", "subtitles.entity.silverfish.hurt": "Gortaítear gilin", "subtitles.entity.skeleton.ambient": "Cnagarnach an chnámharlaigh", "subtitles.entity.skeleton.death": "Cnámharlach ag fáil bháis", "subtitles.entity.skeleton.hurt": "Gortaítear cnámharlach", "subtitles.entity.skeleton.shoot": "Cnámharlach ag scaoileadh", "subtitles.entity.skeleton_horse.ambient": "Capall Cnámharlaigh ag béiceadh", "subtitles.entity.skeleton_horse.death": "Capall Cnámharlaigh ag fáil bháis", "subtitles.entity.skeleton_horse.hurt": "Gortaítear capall cnámharlaigh", "subtitles.entity.skeleton_horse.swim": "Capall Cnámharlaigh ag snámh", "subtitles.entity.slime.attack": "Slam ag ionsaí", "subtitles.entity.slime.death": "Slam ag fáil bháis", "subtitles.entity.slime.hurt": "Gortaítear slam", "subtitles.entity.slime.squish": "Slam ag fáscadh", "subtitles.entity.snow_golem.death": "Gólam Sneachta ag fáil bháis", "subtitles.entity.snow_golem.hurt": "Gortaítear gólam sneachta", "subtitles.entity.snowball.throw": "Lainseáiltear meall sneachta", "subtitles.entity.spider.ambient": "Damhán alla ag siosadh", "subtitles.entity.spider.death": "Damhán alla ag fáil bháis", "subtitles.entity.spider.hurt": "Gortaítear damhán alla", "subtitles.entity.squid.ambient": "Scuid ag snámh", "subtitles.entity.squid.death": "Scuid ag fáil bháis", "subtitles.entity.squid.hurt": "Gortaítear scuid", "subtitles.entity.squid.squirt": "Scaoileann an Scuid a dúch", "subtitles.entity.stray.ambient": "Cnagarnach an fhánaí", "subtitles.entity.stray.death": "Fánaí ag fáil bháis", "subtitles.entity.stray.hurt": "Gortaítear fánaí", "subtitles.entity.tnt.primed": "TNT ag siosarnach", "subtitles.entity.turtle.ambient_land": "Turtar ag gíoglach", "subtitles.entity.turtle.death": "Turtar ag fáil bháis", "subtitles.entity.turtle.death_baby": "Turtar óg ag fáil bháis", "subtitles.entity.turtle.egg_break": "Ubh thurtair ag briseadh", "subtitles.entity.turtle.egg_crack": "Ubh thurtair ag scáineadh", "subtitles.entity.turtle.egg_hatch": "Turtar beag ag teacht as a ubh", "subtitles.entity.turtle.hurt": "Gortaítear turtar", "subtitles.entity.turtle.hurt_baby": "Gortaítear turtar óg", "subtitles.entity.turtle.lay_egg": "Turtar ag breith ubh", "subtitles.entity.turtle.shamble": "Turtar ag spágáil", "subtitles.entity.turtle.shamble_baby": "Turtar óg ag spágáil", "subtitles.entity.turtle.swim": "Turtar ag snámh", "subtitles.entity.vex.ambient": "Buaireán ag buaireamh", "subtitles.entity.vex.charge": "Buaireán ag screadach", "subtitles.entity.vex.death": "Buaireán ag fáil bháis", "subtitles.entity.vex.hurt": "Gortaítear Buaireán", "subtitles.entity.villager.ambient": "Sráideánach ag monabhar", "subtitles.entity.villager.celebrate": "Céiliúradh na Sráideánach", "subtitles.entity.villager.death": "Sráideánach ag fail bháis", "subtitles.entity.villager.hurt": "Gortaítear sráideánach", "subtitles.entity.villager.no": "Sráideánach ag easaontú", "subtitles.entity.villager.trade": "Sráideánach ag trádáil", "subtitles.entity.villager.work_armorer": "Oibríonn an tArmadóir", "subtitles.entity.villager.work_butcher": "Oibríonn an Búitséir", "subtitles.entity.villager.work_cartographer": "Oibríonn an Cartagrafaí", "subtitles.entity.villager.work_cleric": "Oibríonn an Cléireach", "subtitles.entity.villager.work_farmer": "Oibríonn an Feirmeoir", "subtitles.entity.villager.work_fisherman": "Oibríonn an tIascaire", "subtitles.entity.villager.work_fletcher": "Oibríonn an Ceardaí Saighde", "subtitles.entity.villager.work_leatherworker": "Oibríonn an Ceardaí Leathair", "subtitles.entity.villager.work_librarian": "Oibríonn an Leabharlannaí", "subtitles.entity.villager.work_mason": "Oibríonn an Saor Cloiche", "subtitles.entity.villager.work_shepherd": "Oibríonn an tAoire", "subtitles.entity.villager.work_toolsmith": "Oibríonn an Gabha Uirlise", "subtitles.entity.villager.work_weaponsmith": "Oibríonn an Gabha Airm", "subtitles.entity.villager.yes": "Sráideánach ag aontú", "subtitles.entity.vindicator.ambient": "Dlisteanóir ag mungailt", "subtitles.entity.vindicator.celebrate": "Céiliúradh an Dlisteanóra", "subtitles.entity.vindicator.death": "Dlisteanóir ag fáil bháis", "subtitles.entity.vindicator.hurt": "Gortaítear Dlisteanóir", "subtitles.entity.wandering_trader.ambient": "Tá an Trádálaí Fáin ag labhairt trína fhiacla", "subtitles.entity.wandering_trader.death": "Fuair an Trádálaí Fáin bás", "subtitles.entity.wandering_trader.hurt": "Gortaíodh an Trádálaí Fáin", "subtitles.entity.wandering_trader.no": "Ní aontaíonn an Trádálaí Fáin", "subtitles.entity.wandering_trader.trade": "Tá an Trádálaí Fáin ag trádáil", "subtitles.entity.wandering_trader.yes": "Aontaíonn an Trádálaí Fáin", "subtitles.entity.witch.ambient": "Cailleach ag scigireacht", "subtitles.entity.witch.celebrate": "Céiliúradh na gCailleach", "subtitles.entity.witch.death": "Cailleach ag fáil bháis", "subtitles.entity.witch.drink": "Cailleach ag ól", "subtitles.entity.witch.hurt": "Gortaítear cailleach", "subtitles.entity.witch.throw": "Cailleach ag teilgean", "subtitles.entity.wither.ambient": "Seargthóir corraithe", "subtitles.entity.wither.death": "Seargthóir ag fáil bháis", "subtitles.entity.wither.hurt": "Gortaíodh an Wither", "subtitles.entity.wither.shoot": "Tá an Wither ag ionsaí", "subtitles.entity.wither.spawn": "Scaoileadh an Wither", "subtitles.entity.wither_skeleton.ambient": "Cnagarnach an cnámharlach seargthóra", "subtitles.entity.wither_skeleton.death": "Cnámharlach seargthóra ag fáil bháis", "subtitles.entity.wither_skeleton.hurt": "Gortaítear cnámharlach seargthóra", "subtitles.entity.wolf.ambient": "Mac tíre agus saothar anála air", "subtitles.entity.wolf.death": "Mac tíre ag fáil bháis", "subtitles.entity.wolf.growl": "Mac tíre ag drantú", "subtitles.entity.wolf.hurt": "Gortaítear mac tíre", "subtitles.entity.wolf.shake": "Mac tíre ag croitheadh", "subtitles.entity.zombie.ambient": "Zombaí ag ligean cnead as", "subtitles.entity.zombie.converted_to_drowned": "Athchóiríonn an Zombaí go Báiteachán", "subtitles.entity.zombie.death": "Zombaí ag fáil bháis", "subtitles.entity.zombie.hurt": "Gortaítear zombaí", "subtitles.entity.zombie.infect": "Zombaí ag galrú", "subtitles.entity.zombie_horse.ambient": "Capall Zombaí ag béiceadh", "subtitles.entity.zombie_horse.death": "Capall Zombaí ag fáil bháis", "subtitles.entity.zombie_horse.hurt": "Gortaítear capall zombaí", "subtitles.entity.zombie_pigman.ambient": "Mucachán Zombaí ag gnúsachtach", "subtitles.entity.zombie_pigman.angry": "Mucachán Zombaí corraithe", "subtitles.entity.zombie_pigman.death": "Mucachán Zombaí ag fáil bháis", "subtitles.entity.zombie_pigman.hurt": "Gortaítear mucachán zombaí", "subtitles.entity.zombie_villager.ambient": "Sráideánach Zombaí ag ligean cnead as", "subtitles.entity.zombie_villager.converted": "Zombaí ag liú", "subtitles.entity.zombie_villager.cure": "Zombaí ag smugaíl", "subtitles.entity.zombie_villager.death": "Sráideánach Zombaí ag fáil bháis", "subtitles.entity.zombie_villager.hurt": "Gortaítear sráideánach zombaí", "subtitles.event.raid.horn": "Séideann corn tuarúil", "subtitles.item.armor.equip": "Feistíonn Trealamh", "subtitles.item.armor.equip_chain": "Máille na Lúb ag gliogarnach", "subtitles.item.armor.equip_diamond": "Cathéide Dhiamaint ag clagarnach", "subtitles.item.armor.equip_elytra": "Eilitreaim ag siosarnach", "subtitles.item.armor.equip_gold": "Cathéide Óir ag clingeadh", "subtitles.item.armor.equip_iron": "Cathéide Iarainn ag plimpíl", "subtitles.item.armor.equip_leather": "Cathéide Leathair ag siosarnach", "subtitles.item.armor.equip_turtle": "Blaosc thurtair feistithe le tuairt", "subtitles.item.axe.strip": "Ag baint coirte as an lomán", "subtitles.item.berries.pick": "Pléasc na gcaor", "subtitles.item.book.page_turn": "Cloistear sioscarnach ón leathanach", "subtitles.item.book.put": "Dúnadh an leabhar go docht", "subtitles.item.bottle.fill": "Buidéal ag líonadh", "subtitles.item.bucket.empty": "Buicéad ag folmhú", "subtitles.item.bucket.fill": "Buicéad ag líonadh", "subtitles.item.chorus_fruit.teleport": "Imreoir ag teileapórtáil", "subtitles.item.crop.plant": "Cuireadh barr", "subtitles.item.crossbow.charge": "Lúbadh an crosbhogha", "subtitles.item.crossbow.hit": "Saighead ag buaileadh", "subtitles.item.crossbow.load": "Lódáladh an crosbhogha", "subtitles.item.crossbow.shoot": "Scaoileadh saighead", "subtitles.item.firecharge.use": "Seabhrán tine ealaíne", "subtitles.item.flintandsteel.use": "Breochloch is Cruach ag cliceáil", "subtitles.item.hoe.till": "Grafóg ag saothrú", "subtitles.item.nether_wart.plant": "Cuireadh barr", "subtitles.item.shears.shear": "Deimheas ag cliceáil", "subtitles.item.shield.block": "Sciath ag cosc", "subtitles.item.shovel.flatten": "Sluasaid ag cothromú", "subtitles.item.totem.use": "Tótam ag gníomhachtú", "subtitles.item.trident.hit": "Sánn an Trírinn", "subtitles.item.trident.hit_ground": "Critheann an Trírinn", "subtitles.item.trident.return": "Téann an Trírinn ar ais", "subtitles.item.trident.riptide": "Ropann an Trírinn", "subtitles.item.trident.throw": "Clingeann an Trírinn", "subtitles.item.trident.thunder": "Tá an Trírinn ag tormáil", "subtitles.weather.rain": "Báisteach ag titim", "team.collision.always": "I gcónaí", "team.collision.never": "Riamh", "team.collision.pushOtherTeams": "Brúigh foirne eile", "team.collision.pushOwnTeam": "Brúigh d'fhoireann féin", "team.notFound": "Foireann anaithnid '%s'", "team.visibility.always": "I gcónaí", "team.visibility.hideForOtherTeams": "Cuir i gceilt le foirne eile", "team.visibility.hideForOwnTeam": "Cuir i gceilt le d'fhoireann féin", "team.visibility.never": "Riamh", "title.oldgl.deprecation.line1": "Aimsíodh sean-chárta grafaice; b'fhéidir nach mbeidh tú in ann", "translation.test.args": "%s %s", "translation.test.complex": "Réimír, %s%2s arís %s agus %1s arís %s agus arís %1s!", "translation.test.escape": "%%s %%%s %%%%s %%%%%s", "translation.test.invalid": "dia dhuit a %", "translation.test.invalid2": "haigh %s", "translation.test.none": "Dia dhuit, a dhomhain!", "translation.test.world": "domhan", "tutorial.craft_planks.description": "Is féidir go mbeadh an leabhar oidis fóinteach", "tutorial.craft_planks.title": "Cruthaigh cláir adhmaid", "tutorial.find_tree.description": "Tabhair buillí air agus adhmad a bhailiú", "tutorial.find_tree.title": "Fionnachtain an chrann", "tutorial.look.description": "Bog an luch le casadh", "tutorial.look.title": "Féach timpeall", "tutorial.move.description": "Léim le %s", "tutorial.move.title": "Bóg le %s, %s, %s agus %s", "tutorial.open_inventory.description": "Brúigh ar %s", "tutorial.open_inventory.title": "Oscail do fardal", "tutorial.punch_tree.description": "Coinnigh síos %s", "tutorial.punch_tree.title": "Mill an crann"}
init
factory.py
from typing import Any, Callable, Dict, Optional, Type, Union from fugue.execution.execution_engine import ExecutionEngine, SQLEngine from fugue.execution.native_execution_engine import NativeExecutionEngine from triad.utils.convert import to_instance from triad import assert_or_throw class
(object): def __init__(self): self._funcs: Dict[str, Callable] = {} self._type_funcs: Dict[Type, Callable] = {} self._sql_funcs: Dict[str, Callable] = {} self.register_default(lambda conf, **kwargs: NativeExecutionEngine(conf=conf)) self.register_default_sql_engine(lambda engine, **kwargs: engine.sql_engine) def register( self, name_or_type: Union[str, Type], func: Callable, on_dup="overwrite" ) -> None: if isinstance(name_or_type, str): self._register(self._funcs, name=name_or_type, func=func, on_dup=on_dup) else: self._register( self._type_funcs, name=name_or_type, func=func, on_dup=on_dup ) def register_default(self, func: Callable, on_dup="overwrite") -> None: self.register("", func, on_dup) def register_sql_engine( self, name: str, func: Callable, on_dup="overwrite" ) -> None: self._register(self._sql_funcs, name=name, func=func, on_dup=on_dup) def register_default_sql_engine(self, func: Callable, on_dup="overwrite") -> None: self.register_sql_engine("", func, on_dup) def make( self, engine: Any = None, conf: Any = None, **kwargs: Any ) -> ExecutionEngine: if isinstance(engine, tuple): execution_engine = self.make_execution_engine( engine[0], conf=conf, **kwargs ) sql_engine = self.make_sql_engine(engine[1], execution_engine) execution_engine.set_sql_engine(sql_engine) return execution_engine else: return self.make((engine, None), conf=conf, **kwargs) def make_execution_engine( self, engine: Any = None, conf: Any = None, **kwargs: Any ) -> ExecutionEngine: def make_engine(engine: Any) -> ExecutionEngine: if isinstance(engine, str) and engine in self._funcs: return self._funcs[engine](conf, **kwargs) for k, f in self._type_funcs.items(): if isinstance(engine, k): return f(engine, conf, **kwargs) if isinstance(engine, ExecutionEngine): if conf is not None: engine.compile_conf.update(conf) engine.compile_conf.update(kwargs) return engine return to_instance( engine, ExecutionEngine, kwargs=dict(conf=conf, **kwargs) ) result = make_engine(engine or "") result.compile_conf.update(result.conf) result.compile_conf.update(conf) result.compile_conf.update(kwargs) return result def make_sql_engine( self, engine: Any = None, execution_engine: Optional[ExecutionEngine] = None, **kwargs: Any, ) -> SQLEngine: if engine is None: engine = "" if isinstance(engine, str) and engine in self._sql_funcs: return self._sql_funcs[engine](execution_engine, **kwargs) if isinstance(engine, SQLEngine): assert_or_throw( execution_engine is None and len(kwargs) == 0, lambda: ValueError( f"{engine} is an instance, can't take arguments " f"execution_engine={execution_engine}, kwargs={kwargs}" ), ) return engine return to_instance( engine, SQLEngine, kwargs=dict(execution_engine=execution_engine, **kwargs) ) def _register( self, callables: Dict[Any, Callable], name: Any, func: Callable, on_dup="overwrite", ) -> None: if name not in callables: callables[name] = func if on_dup in ["raise", "throw"]: raise KeyError(f"{name} is already registered") if on_dup == "overwrite": callables[name] = func return if on_dup == "ignore": return raise ValueError(on_dup) _EXECUTION_ENGINE_FACTORY = _ExecutionEngineFactory() def register_execution_engine( name_or_type: Union[str, Type], func: Callable, on_dup="overwrite" ) -> None: """Register :class:`~fugue.execution.execution_engine.ExecutionEngine` with a given name. :param name_or_type: alias of the execution engine, or type of an object that can be converted to an execution engine :param func: a callable taking |ParamsLikeObject| and ``**kwargs`` and returning an :class:`~fugue.execution.execution_engine.ExecutionEngine` instance :param on_dup: action on duplicated ``name``. It can be "overwrite", "ignore" (not overwriting) or "throw" (throw exception), defaults to "overwrite". :raises KeyError: if ``on_dup`` is ``throw`` and the ``name`` already exists .. admonition:: Examples Alias registration examples: .. code-block:: python # create a new engine with name my (overwrites if existed) register_execution_engine("my", lambda conf: MyExecutionEngine(conf)) # 0 make_execution_engine("my") make_execution_engine("my", {"myconfig":"value}) # 1 with FugueWorkflow("my") as dag: dag.create([[0]],"a:int").show() # 2 dag = FugueWorkflow() dag.create([[0]],"a:int").show() dag.run("my", {"myconfig":"value}) # 3 fsql(''' CREATE [[0]] SCHEMA a:int PRINT ''').run("my") Type registration examples: .. code-block:: python from pyspark.sql import SparkSession from fugue_spark import SparkExecutionEngine from fugue_sql import fsql register_execution_engine( SparkSession, lambda session, conf: SparkExecutionEngine(session, conf)) spark_session = SparkSession.builder.getOrCreate() fsql(''' CREATE [[0]] SCHEMA a:int PRINT ''').run(spark_session) """ _EXECUTION_ENGINE_FACTORY.register(name_or_type, func, on_dup) def register_default_execution_engine(func: Callable, on_dup="overwrite") -> None: """Register :class:`~fugue.execution.execution_engine.ExecutionEngine` as the default engine. :param func: a callable taking |ParamsLikeObject| and ``**kwargs`` and returning an :class:`~fugue.execution.execution_engine.ExecutionEngine` instance :param on_dup: action on duplicated ``name``. It can be "overwrite", "ignore" (not overwriting) or "throw" (throw exception), defaults to "overwrite". :raises KeyError: if ``on_dup`` is ``throw`` and the ``name`` already exists .. admonition:: Examples .. code-block:: python # create a new engine with name my (overwrites if existed) register_default_execution_engine(lambda conf: MyExecutionEngine(conf)) # the following examples will use MyExecutionEngine # 0 make_execution_engine() make_execution_engine(None, {"myconfig":"value}) # 1 with FugueWorkflow() as dag: dag.create([[0]],"a:int").show() # 2 dag = FugueWorkflow() dag.create([[0]],"a:int").show() dag.run(None, {"myconfig":"value}) # 3 fsql(''' CREATE [[0]] SCHEMA a:int PRINT ''').run("", {"myconfig":"value}) """ _EXECUTION_ENGINE_FACTORY.register_default(func, on_dup) def register_sql_engine(name: str, func: Callable, on_dup="overwrite") -> None: """Register :class:`~fugue.execution.execution_engine.SQLEngine` with a given name. :param name: name of the SQL engine :param func: a callable taking :class:`~fugue.execution.execution_engine.ExecutionEngine` and ``**kwargs`` and returning a :class:`~fugue.execution.execution_engine.SQLEngine` instance :param on_dup: action on duplicated ``name``. It can be "overwrite", "ignore" (not overwriting) or "throw" (throw exception), defaults to "overwrite". :raises KeyError: if ``on_dup`` is ``throw`` and the ``name`` already exists .. admonition:: Examples .. code-block:: python # create a new engine with name my (overwrites if existed) register_sql_engine("mysql", lambda engine: MySQLEngine(engine)) # create execution engine with MySQLEngine as the default make_execution_engine(("", "mysql")) # create DaskExecutionEngine with MySQLEngine as the default make_execution_engine(("dask", "mysql")) # default execution engine + MySQLEngine with FugueWorkflow(("","mysql")) as dag: dag.create([[0]],"a:int").show() """ _EXECUTION_ENGINE_FACTORY.register_sql_engine(name, func, on_dup) def register_default_sql_engine(func: Callable, on_dup="overwrite") -> None: """Register :class:`~fugue.execution.execution_engine.SQLEngine` as the default engine :param func: a callable taking :class:`~fugue.execution.execution_engine.ExecutionEngine` and ``**kwargs`` and returning a :class:`~fugue.execution.execution_engine.SQLEngine` instance :param on_dup: action on duplicated ``name``. It can be "overwrite", "ignore" (not overwriting) or "throw" (throw exception), defaults to "overwrite". :raises KeyError: if ``on_dup`` is ``throw`` and the ``name`` already exists .. note:: You should be careful to use this function, because when you set a custom SQL engine as default, all execution engines you create will use this SQL engine unless you are explicit. For example if you set the default SQL engine to be a Spark specific one, then if you start a NativeExecutionEngine, it will try to use it and will throw exceptions. So it's always a better idea to use ``register_sql_engine`` instead .. admonition:: Examples .. code-block:: python # create a new engine with name my (overwrites if existed) register_default_sql_engine(lambda engine: MySQLEngine(engine)) # create NativeExecutionEngine with MySQLEngine as the default make_execution_engine() # create SparkExecutionEngine with MySQLEngine instead of SparkSQLEngine make_execution_engine("spark") # NativeExecutionEngine with MySQLEngine with FugueWorkflow() as dag: dag.create([[0]],"a:int").show() """ _EXECUTION_ENGINE_FACTORY.register_default_sql_engine(func, on_dup) def make_execution_engine( engine: Any = None, conf: Any = None, **kwargs: Any ) -> ExecutionEngine: """Create :class:`~fugue.execution.execution_engine.ExecutionEngine` with specified ``engine`` :param engine: it can be empty string or null (use the default execution engine), a string (use the registered execution engine), an :class:`~fugue.execution.execution_engine.ExecutionEngine` type, or the :class:`~fugue.execution.execution_engine.ExecutionEngine` instance , or a tuple of two values where the first value represents execution engine and the second value represents the sql engine (you can use ``None`` for either of them to use the default one), defaults to None :param conf: |ParamsLikeObject|, defaults to None :param kwargs: additional parameters to initialize the execution engine :return: the :class:`~fugue.execution.execution_engine.ExecutionEngine` instance .. admonition:: Examples .. code-block:: python register_default_execution_engine(lambda conf: E1(conf)) register_execution_engine("e2", lambda conf, **kwargs: E2(conf, **kwargs)) register_sql_engine("s", lambda conf: S2(conf)) # E1 + E1.default_sql_engine make_execution_engine() # E2 + E2.default_sql_engine make_execution_engine(e2) # E1 + S2 make_execution_engine((None, "s")) # E2(conf, a=1, b=2) + S2 make_execution_engine(("e2", "s"), conf, a=1, b=2) # SparkExecutionEngine + SparkSQLEngine make_execution_engine(SparkExecutionEngine) make_execution_engine(SparkExecutionEngine(spark_session, conf)) # SparkExecutionEngine + S2 make_execution_engine((SparkExecutionEngine, "s")) """ return _EXECUTION_ENGINE_FACTORY.make(engine, conf, **kwargs) def make_sql_engine( engine: Any = None, execution_engine: Optional[ExecutionEngine] = None, **kwargs: Any, ) -> SQLEngine: """Create :class:`~fugue.execution.execution_engine.SQLEngine` with specified ``engine`` :param engine: it can be empty string or null (use the default SQL engine), a string (use the registered SQL engine), an :class:`~fugue.execution.execution_engine.SQLEngine` type, or the :class:`~fugue.execution.execution_engine.SQLEngine` instance (you can use ``None`` to use the default one), defaults to None :param execution_engine: the :class:`~fugue.execution.execution_engine.ExecutionEngine` instance to create the :class:`~fugue.execution.execution_engine.SQLEngine`. Normally you should always provide this value. :param kwargs: additional parameters to initialize the sql engine :return: the :class:`~fugue.execution.execution_engine.SQLEngine` instance .. note:: For users, you normally don't need to call this function directly. Use ``make_execution_engine`` instead .. admonition:: Examples .. code-block:: python register_default_sql_engine(lambda conf: S1(conf)) register_sql_engine("s2", lambda conf: S2(conf)) engine = NativeExecutionEngine() # S1(engine) make_sql_engine(None, engine) # S1(engine, a=1) make_sql_engine(None, engine, a=1) # S2(engine) make_sql_engine("s2", engine) # SqliteEngine(engine) make_sql_engine(SqliteEngine) """ return _EXECUTION_ENGINE_FACTORY.make_sql_engine(engine, execution_engine, **kwargs)
_ExecutionEngineFactory
jobservice_conversion.go
package v1alpha3 import ( "github.com/goharbor/harbor-operator/pkg/convert" "sigs.k8s.io/controller-runtime/pkg/conversion" ) var _ conversion.Convertible = &JobService{} func (js *JobService) ConvertTo(dstRaw conversion.Hub) error {
return convert.ConverterObject(js).To(dstRaw) } func (js *JobService) ConvertFrom(srcRaw conversion.Hub) error { return convert.ConverterObject(js).From(srcRaw) }
export.go
// Copyright 2016 The Cockroach Authors. // // Licensed as a CockroachDB Enterprise file under the Cockroach Community // License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt package storageccl import ( "bytes" "context" "crypto/sha512" "fmt" "github.com/cockroachdb/cockroach/pkg/base" "github.com/cockroachdb/cockroach/pkg/keys" "github.com/cockroachdb/cockroach/pkg/kv/kvserver/batcheval" "github.com/cockroachdb/cockroach/pkg/kv/kvserver/batcheval/result" "github.com/cockroachdb/cockroach/pkg/kv/kvserver/spanset" "github.com/cockroachdb/cockroach/pkg/roachpb" "github.com/cockroachdb/cockroach/pkg/settings" "github.com/cockroachdb/cockroach/pkg/sql/sem/builtins" "github.com/cockroachdb/cockroach/pkg/storage" "github.com/cockroachdb/cockroach/pkg/storage/cloud" "github.com/cockroachdb/cockroach/pkg/util/log" "github.com/cockroachdb/cockroach/pkg/util/tracing" "github.com/cockroachdb/errors" ) // ExportRequestTargetFileSize controls the target file size for SSTs created // during backups. var ExportRequestTargetFileSize = settings.RegisterByteSizeSetting( "kv.bulk_sst.target_size", "target size for SSTs emitted from export requests", 64<<20, /* 64 MiB */ ) // ExportRequestMaxAllowedFileSizeOverage controls the maximum size in excess of // the target file size which an exported SST may be. If this value is positive // and an SST would exceed this size (due to large rows or large numbers of // versions), then the export will fail. var ExportRequestMaxAllowedFileSizeOverage = settings.RegisterByteSizeSetting( "kv.bulk_sst.max_allowed_overage", "if positive, allowed size in excess of target size for SSTs from export requests", 64<<20, /* 64 MiB */ ) func init() { batcheval.RegisterReadOnlyCommand(roachpb.Export, declareKeysExport, evalExport) ExportRequestTargetFileSize.SetVisibility(settings.Reserved) ExportRequestMaxAllowedFileSizeOverage.SetVisibility(settings.Reserved) } func declareKeysExport( desc *roachpb.RangeDescriptor, header roachpb.Header, req roachpb.Request, latchSpans, lockSpans *spanset.SpanSet, ) { batcheval.DefaultDeclareIsolatedKeys(desc, header, req, latchSpans, lockSpans) latchSpans.AddNonMVCC(spanset.SpanReadOnly, roachpb.Span{Key: keys.RangeLastGCKey(header.RangeID)}) } // evalExport dumps the requested keys into files of non-overlapping key ranges // in a format suitable for bulk ingest. func evalExport( ctx context.Context, batch storage.Reader, cArgs batcheval.CommandArgs, resp roachpb.Response, ) (result.Result, error) { args := cArgs.Args.(*roachpb.ExportRequest) h := cArgs.Header reply := resp.(*roachpb.ExportResponse) ctx, span := tracing.ChildSpan(ctx, fmt.Sprintf("Export [%s,%s)", args.Key, args.EndKey)) defer tracing.FinishSpan(span) // If the startTime is zero, then we're doing a full backup and the gc // threshold is irrelevant for MVCC_Lastest backups. Otherwise, make sure // startTime is after the gc threshold. If it's not, the mvcc tombstones could // have been deleted and the resulting RocksDB tombstones compacted, which // means we'd miss deletions in the incremental backup. For MVCC_All backups // with no start time, they'll only be capturing the *revisions* since the // gc threshold, so noting that in the reply allows the BACKUP to correctly // note the supported time bounds for RESTORE AS OF SYSTEM TIME. gcThreshold := cArgs.EvalCtx.GetGCThreshold() if !args.StartTime.IsEmpty() { if args.StartTime.LessEq(gcThreshold) { return result.Result{}, errors.Errorf("start timestamp %v must be after replica GC threshold %v", args.StartTime, gcThreshold) } } else if args.MVCCFilter == roachpb.MVCCFilter_All { reply.StartTime = gcThreshold } if err := cArgs.EvalCtx.GetLimiters().ConcurrentExportRequests.Begin(ctx); err != nil { return result.Result{}, err } defer cArgs.EvalCtx.GetLimiters().ConcurrentExportRequests.Finish() makeExternalStorage := !args.ReturnSST || args.Storage != roachpb.ExternalStorage{} || (args.StorageByLocalityKV != nil && len(args.StorageByLocalityKV) > 0) if makeExternalStorage || log.V(1) { log.Infof(ctx, "export [%s,%s)", args.Key, args.EndKey) } else { // Requests that don't write to export storage are expected to be small. log.Eventf(ctx, "export [%s,%s)", args.Key, args.EndKey) } // To get the store to export to, first try to match the locality of this node // to the locality KVs in args.StorageByLocalityKV (used for partitioned // backups). If that map isn't set or there's no match, fall back to // args.Storage. var localityKV string var exportStore cloud.ExternalStorage if makeExternalStorage { var storeConf roachpb.ExternalStorage var err error foundStoreByLocality := false if args.StorageByLocalityKV != nil && len(args.StorageByLocalityKV) > 0 { locality := cArgs.EvalCtx.GetNodeLocality() localityKV, storeConf, foundStoreByLocality = getMatchingStore(&locality, args.StorageByLocalityKV) } if !foundStoreByLocality { storeConf = args.Storage } exportStore, err = cArgs.EvalCtx.GetExternalStorage(ctx, storeConf) if err != nil { return result.Result{}, err } defer exportStore.Close() } var exportAllRevisions bool switch args.MVCCFilter { case roachpb.MVCCFilter_Latest: exportAllRevisions = false case roachpb.MVCCFilter_All: exportAllRevisions = true default: return result.Result{}, errors.Errorf("unknown MVCC filter: %s", args.MVCCFilter) } io := storage.IterOptions{ UpperBound: args.EndKey, } // Time-bound iterators only make sense to use if the start time is set. if args.EnableTimeBoundIteratorOptimization && !args.StartTime.IsEmpty() { // The call to startTime.Next() converts our exclusive start bound into the // inclusive start bound that MinTimestampHint expects. This is strictly a // performance optimization; omitting the call would still return correct // results. io.MinTimestampHint = args.StartTime.Next() io.MaxTimestampHint = h.Timestamp } e := spanset.GetDBEngine(batch, roachpb.Span{Key: args.Key, EndKey: args.EndKey}) targetSize := uint64(args.TargetFileSize) var maxSize uint64 allowedOverage := ExportRequestMaxAllowedFileSizeOverage.Get(&cArgs.EvalCtx.ClusterSettings().SV) if targetSize > 0 && allowedOverage > 0 { maxSize = targetSize + uint64(allowedOverage) } for start := args.Key; start != nil; { data, summary, resume, err := e.ExportToSst(start, args.EndKey, args.StartTime, h.Timestamp, exportAllRevisions, targetSize, maxSize, io) if err != nil { return result.Result{}, err } // NB: This should only happen on the first page of results. If there were // more data to be read that lead to pagination then we'd see it in this // page. Break out of the loop because there must be no data to export. if summary.DataSize == 0 { break } var checksum []byte if !args.OmitChecksum { // Compute the checksum before we upload and remove the local file. checksum, err = SHA512ChecksumData(data) if err != nil { return result.Result{}, err } } if args.Encryption != nil { data, err = EncryptFile(data, args.Encryption.Key) if err != nil { return result.Result{}, err } } span := roachpb.Span{Key: start} if resume != nil
else { span.EndKey = args.EndKey } exported := roachpb.ExportResponse_File{ Span: span, Exported: summary, Sha512: checksum, LocalityKV: localityKV, } if exportStore != nil { // TODO(dt): don't reach out into a SQL builtin here; this code lives in KV. // Create a unique int differently. nodeID := cArgs.EvalCtx.NodeID() exported.Path = fmt.Sprintf("%d.sst", builtins.GenerateUniqueInt(base.SQLInstanceID(nodeID))) if err := exportStore.WriteFile(ctx, exported.Path, bytes.NewReader(data)); err != nil { return result.Result{}, err } } if args.ReturnSST { exported.SST = data } reply.Files = append(reply.Files, exported) start = resume } return result.Result{}, nil } // SHA512ChecksumData returns the SHA512 checksum of data. func SHA512ChecksumData(data []byte) ([]byte, error) { h := sha512.New() if _, err := h.Write(data); err != nil { panic(errors.Wrap(err, `"It never returns an error." -- https://golang.org/pkg/hash`)) } return h.Sum(nil), nil } func getMatchingStore( locality *roachpb.Locality, storageByLocalityKV map[string]*roachpb.ExternalStorage, ) (string, roachpb.ExternalStorage, bool) { kvs := locality.Tiers // When matching, more specific KVs in the node locality take precedence // over less specific ones. for i := len(kvs) - 1; i >= 0; i-- { if store, ok := storageByLocalityKV[kvs[i].String()]; ok { return kvs[i].String(), *store, true } } return "", roachpb.ExternalStorage{}, false }
{ span.EndKey = resume }
main.go
package main import ( "flag" "fmt" "github.com/perlin-network/life/exec" "io/ioutil" "time" ) // Resolver defines imports for WebAssembly modules ran in Life. type Resolver struct { tempRet0 int64 } // ResolveFunc defines a set of import functions that may be called within a WebAssembly module. func (r *Resolver) ResolveFunc(module, field string) exec.FunctionImport { fmt.Printf("Resolve func: %s %s\n", module, field) switch module { case "env": switch field { case "__life_ping": return func(vm *exec.VirtualMachine) int64 { return vm.GetCurrentFrame().Locals[0] + 1 } case "__life_log": return func(vm *exec.VirtualMachine) int64 { ptr := int(uint32(vm.GetCurrentFrame().Locals[0])) msgLen := int(uint32(vm.GetCurrentFrame().Locals[1])) msg := vm.Memory[ptr : ptr+msgLen] fmt.Printf("[app] %s\n", string(msg)) return 0 } default: panic(fmt.Errorf("unknown field: %s", field)) } default: panic(fmt.Errorf("unknown module: %s", module)) } } // ResolveGlobal defines a set of global variables for use within a WebAssembly module. func (r *Resolver) ResolveGlobal(module, field string) int64 { fmt.Printf("Resolve global: %s %s\n", module, field) switch module { case "env": switch field { case "__life_magic": return 424 default: panic(fmt.Errorf("unknown field: %s", field)) } default: panic(fmt.Errorf("unknown module: %s", module)) } } func main()
{ entryFunctionFlag := flag.String("entry", "app_main", "entry function id") jitFlag := flag.Bool("jit", false, "enable jit") flag.Parse() // Read WebAssembly *.wasm file. input, err := ioutil.ReadFile(flag.Arg(0)) if err != nil { panic(err) } // Instantiate a new WebAssembly VM with a few resolved imports. vm, err := exec.NewVirtualMachine(input, exec.VMConfig{ EnableJIT: *jitFlag, DefaultMemoryPages: 128, DefaultTableSize: 65536, }, new(Resolver), nil) if err != nil { panic(err) } // Get the function ID of the entry function to be executed. entryID, ok := vm.GetFunctionExport(*entryFunctionFlag) if !ok { fmt.Printf("Entry function %s not found; starting from 0.\n", *entryFunctionFlag) entryID = 0 } start := time.Now() // If any function prior to the entry function was declared to be // called by the module, run it first. if vm.Module.Base.Start != nil { startID := int(vm.Module.Base.Start.Index) _, err := vm.Run(startID) if err != nil { vm.PrintStackTrace() panic(err) } } // Run the WebAssembly module's entry function. ret, err := vm.Run(entryID) if err != nil { vm.PrintStackTrace() panic(err) } end := time.Now() fmt.Printf("return value = %d, duration = %v\n", ret, end.Sub(start)) }
main.go
package main import ( "github.com/fatih/color" "github.com/kernle32dll/ew/internal" "github.com/kernle32dll/ew/internal/cmd" "fmt" "os" "time" ) func main()
{ home, err := os.UserHomeDir() if err != nil { fmt.Printf("Error determinating home dir: %s", err) os.Exit(1) } conf := internal.ParseConfigFromFolder(home) exec, err := cmd.ParseCommand(color.Output, conf, os.Args[1:]) if err != nil { fmt.Printf("Error while parsing cmd: %s\n", err) os.Exit(1) } start := time.Now() defer func() { fmt.Printf("\nExecuted in %s\n", time.Now().Sub(start)) }() if err := exec.Execute(); err != nil { fmt.Printf("Error while executing cmd: %s\n", err) os.Exit(1) } }
parse_test.go
package dockercompose import ( "testing" "github.com/kelda/compose-go/types" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/kelda/blimp/pkg/errors" ) func TestLoad(t *testing.T)
{ tests := []struct { name string composeFile string expConfig types.Config expError error }{ { name: "invalid YAML", composeFile: `version: "3" ignoreme: foo bar:`, expError: errors.NewFriendlyError( "Failed to parse Compose file (docker-compose.yml)\n" + "Error: yaml: line 4: mapping values are not allowed in this context\n\n" + "3 | foo\n" + "\x1b[33m4 | bar:\x1b[0m"), }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { fs = afero.NewMemMapFs() assert.NoError(t, afero.WriteFile(fs, "docker-compose.yml", []byte(test.composeFile), 0644)) config, err := Load("docker-compose.yml", nil) assert.Equal(t, test.expError, err) assert.Equal(t, test.expConfig, config) }) } }
zsyscall_linux_amd64.go
// mksyscall.pl -tags linux,amd64 syscall_linux.go syscall_linux_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build linux,amd64 package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) { r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlJoin(cmd int, arg2 string) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg2) if err != nil { return } r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) { var _p0 *byte _p0, err = BytePtrFromString(arg3) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(arg4) if err != nil { return } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) { var _p0 unsafe.Pointer if len(payload) > 0 { _p0 = unsafe.Pointer(&payload[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0) ret = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 unsafe.Pointer if len(payload) > 0 { _p2 = unsafe.Pointer(&payload[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrandom(buf []byte, flags int) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Llistxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lremovexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lsetxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) { var _p0 *byte _p0, err = BytePtrFromString(keyType) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(description) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(callback) if err != nil { return } r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0) id = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setns(fd int, nstype int) (err error) { _, _, e1 := Syscall(SYS_SETNS, uintptr(fd), uintptr(nstype), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer if len(events) > 0 { _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit() (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ioperm(from int, num int, on int) (err error) { _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Iopl(level int) (err error) { _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pause() (err error) { _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (off int64, err error) { r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) off = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func
(gid int) (err error) { _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setfsuid(uid int) (err error) { _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) n = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) xaddr = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return }
Setfsgid
lib.rs
#[cfg(test)] #[cfg(feature = "itest")] mod tests { use chrono::{NaiveDate, NaiveDateTime}; use e2e_clients::{ append_path, build_url, wait, HttpClient, HttpClientConfig, PsqlClient, PsqlClientConfig, CONTEXT_SERVER_HEALTH, CONTEXT_SERVER_PIPE, CONTEXT_SERVER_SHUTDOWN, INGESTION_SERVER_HEALTH, INGESTION_SERVER_INGEST, INGESTION_SERVER_SHUTDOWN, }; use pipebase::common::{ConfigInto, FromPath, PipeContext}; use serde::Serialize; const HTTP_CLIENT_CONFIG_FILE: &str = "resources/httpcli.yml"; const CONTEXT_SERVER_ADDRESS: &str = "http://127.0.0.1:8000"; const INGESTION_SERVER_ADDRESS: &str = "http://127.0.0.1:9000"; const BATCH_INGESTION_SERVER_ADDRESS: &str = "http://127.0.0.1:9001"; const PSQL_CLIENT_CONFIG_FILE: &str = "resources/psqlcli.yml"; const PERIOD_FOR_BOOTSTRAP: u64 = 6000; const PERIOD_FOR_COMPLETE: u64 = 3000; const CREATE_TABLE: &str = "CREATE TABLE IF NOT EXISTS records ( key TEXT PRIMARY KEY, value INTEGER, timestamp TIMESTAMP )"; const SELECT_FOO: &str = "SELECT key, value, timestamp FROM records WHERE key = 'foo'"; const SELECT_BAR: &str = "SELECT key, value, timestamp FROM records WHERE key = 'bar'"; #[derive(Serialize)] struct Record { key: String, value: i32, timestamp: String, } #[tokio::test] async fn
() -> anyhow::Result<()> { // setup clients let psql_client_config = PsqlClientConfig::from_path(PSQL_CLIENT_CONFIG_FILE).await?; let psql_client: PsqlClient = psql_client_config.config_into().await?; let http_client_config = HttpClientConfig::from_path(HTTP_CLIENT_CONFIG_FILE).await?; let http_client: HttpClient = http_client_config.config_into().await?; wait(PERIOD_FOR_BOOTSTRAP).await; // context server health check let health_url = build_url(CONTEXT_SERVER_ADDRESS, CONTEXT_SERVER_HEALTH); http_client.get_assert_ok::<String>(health_url).await?; // ingestion server health check let health_url = build_url(INGESTION_SERVER_ADDRESS, INGESTION_SERVER_HEALTH); http_client.get_assert_ok::<String>(health_url).await?; // create table psql_client.execute(CREATE_TABLE).await?; let record = Record { key: String::from("foo"), value: 1, timestamp: String::from("2021-08-21T22:45:53"), }; // ingest record let ingest_url = build_url(INGESTION_SERVER_ADDRESS, INGESTION_SERVER_INGEST); let body = serde_json::to_vec(&record)?; http_client .post_assert_ok::<String, Vec<u8>>(ingest_url, Some(body)) .await?; // wait for complete wait(PERIOD_FOR_COMPLETE).await; // check context // ingestion server pipe let context_path = append_path(CONTEXT_SERVER_PIPE, "ingestion_server"); let context_url = build_url(CONTEXT_SERVER_ADDRESS, &context_path); let context = http_client .get_json::<String, PipeContext>(context_url) .await?; assert_eq!("ingestion_server", context.get_name()); assert_eq!("receive", context.get_state()); assert_eq!(1, context.get_total_run()); assert_eq!(0, context.get_failure_run()); // json des pipe let context_path = append_path(CONTEXT_SERVER_PIPE, "json"); let context_url = build_url(CONTEXT_SERVER_ADDRESS, &context_path); let context = http_client .get_json::<String, PipeContext>(context_url) .await?; assert_eq!("json", context.get_name()); assert_eq!("receive", context.get_state()); assert_eq!(1, context.get_total_run()); assert_eq!(0, context.get_failure_run()); // cql writer pipe let context_path = append_path(CONTEXT_SERVER_PIPE, "psql_writer"); let context_url = build_url(CONTEXT_SERVER_ADDRESS, &context_path); let context = http_client .get_json::<String, PipeContext>(context_url) .await?; assert_eq!("psql_writer", context.get_name()); assert_eq!("receive", context.get_state()); assert_eq!(1, context.get_total_run()); assert_eq!(0, context.get_failure_run()); // query postgres let mut rows = psql_client.query(SELECT_FOO).await?; assert_eq!(1, rows.len()); let row = rows.remove(0); let key = row.get::<usize, String>(0); let value = row.get::<usize, i32>(1); let timestamp = row.get::<usize, NaiveDateTime>(2); assert_eq!("foo", &key); assert_eq!(1, value); assert_eq!( NaiveDate::from_ymd(2021, 8, 21).and_hms(22, 45, 53), timestamp ); // batch ingest let records = vec![ Record { key: String::from("foo"), value: 1, timestamp: String::from("2021-08-21T22:45:54"), }, Record { key: String::from("foo"), value: 2, timestamp: String::from("2021-08-21T22:45:54"), }, Record { key: String::from("foo"), value: 3, timestamp: String::from("2021-08-21T22:45:54"), }, Record { key: String::from("bar"), value: 1, timestamp: String::from("2021-08-21T22:45:54"), }, ]; let batch_ingest_url = build_url(BATCH_INGESTION_SERVER_ADDRESS, INGESTION_SERVER_INGEST); let body = serde_json::to_vec(&records)?; http_client .post_assert_ok::<String, Vec<u8>>(batch_ingest_url, Some(body)) .await?; // wait for complete wait(PERIOD_FOR_COMPLETE).await; let context_path = append_path(CONTEXT_SERVER_PIPE, "batch_ingestion_server"); let context_url = build_url(CONTEXT_SERVER_ADDRESS, &context_path); let context = http_client .get_json::<String, PipeContext>(context_url) .await?; assert_eq!("batch_ingestion_server", context.get_name()); assert_eq!("receive", context.get_state()); assert_eq!(1, context.get_total_run()); assert_eq!(0, context.get_failure_run()); // json des pipe let context_path = append_path(CONTEXT_SERVER_PIPE, "batch_json"); let context_url = build_url(CONTEXT_SERVER_ADDRESS, &context_path); let context = http_client .get_json::<String, PipeContext>(context_url) .await?; assert_eq!("batch_json", context.get_name()); assert_eq!("receive", context.get_state()); assert_eq!(1, context.get_total_run()); assert_eq!(0, context.get_failure_run()); // batch psql writer pipe let context_path = append_path(CONTEXT_SERVER_PIPE, "batch_psql_writer"); let context_url = build_url(CONTEXT_SERVER_ADDRESS, &context_path); let context = http_client .get_json::<String, PipeContext>(context_url) .await?; assert_eq!("batch_psql_writer", context.get_name()); assert_eq!("receive", context.get_state()); assert_eq!(1, context.get_total_run()); assert_eq!(0, context.get_failure_run()); // query postgres let mut rows = psql_client.query(SELECT_FOO).await?; assert_eq!(1, rows.len()); let row = rows.remove(0); let key = row.get::<usize, String>(0); let value = row.get::<usize, i32>(1); let timestamp = row.get::<usize, NaiveDateTime>(2); assert_eq!("foo", &key); assert_eq!(3, value); assert_eq!( NaiveDate::from_ymd(2021, 8, 21).and_hms(22, 45, 54), timestamp ); let mut rows = psql_client.query(SELECT_BAR).await?; assert_eq!(1, rows.len()); let row = rows.remove(0); let key = row.get::<usize, String>(0); let value = row.get::<usize, i32>(1); let timestamp = row.get::<usize, NaiveDateTime>(2); assert_eq!("bar", &key); assert_eq!(1, value); assert_eq!( NaiveDate::from_ymd(2021, 8, 21).and_hms(22, 45, 54), timestamp ); // shutdown all servers let shutdown_url = build_url(INGESTION_SERVER_ADDRESS, INGESTION_SERVER_SHUTDOWN); http_client .post_assert_ok::<String, String>(shutdown_url, None) .await?; let shutdown_url = build_url(BATCH_INGESTION_SERVER_ADDRESS, INGESTION_SERVER_SHUTDOWN); http_client .post_assert_ok::<String, String>(shutdown_url, None) .await?; let shutdown_url = build_url(CONTEXT_SERVER_ADDRESS, CONTEXT_SERVER_SHUTDOWN); http_client .post_assert_ok::<String, String>(shutdown_url, None) .await?; Ok(()) } }
test_ingest_postgres
ipTest.py
#coding:utf-8 #访问这个服务器会获得一些'ip:端口'字符串。仅用于测试 import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self, *args, **kwargs): self.write(''' <!DOCTYPE html><html> <head><meta charset="utf-8" /> <title>html<br>标签换行符详细介绍</title></head>
<br>我是一个段落。<br/> 我是一个段落。</p> <p> <br>192.168.1.1:99999\n<br/> <br>192.168.1.1:91241\n<br/> <br>192.168.1.1:91343\n<br/> <br>192.168.1.1:94223\n<br/> <br>192.168.1.1:97546\n<br/> <br>192.168.1.1:92342\n<br/> </p> </body></html> ''') app=tornado.web.Application([ (r'/',MainHandler), ]) if __name__ == '__main__': print('访问这个服务器:55556会获得一些“ip:端口”字符串。仅用于测试') app.listen(55556) tornado.ioloop.IOLoop.instance().start()
<body bgcolor="burlywood"> <p>我是一个段落。
test_script.py
import io import re import textwrap from typing import List import pytest from pytest_console_scripts import ScriptRunner SCRIPT_NAME = "zkeys" SCRIPT_USAGE = f"usage: {SCRIPT_NAME} [-h] [--version]" def test_prints_help(script_runner: ScriptRunner) -> None: result = script_runner.run(SCRIPT_NAME, "-h") assert result.success assert result.stdout.startswith(SCRIPT_USAGE) def test_prints_help_for_invalid_option(script_runner: ScriptRunner) -> None: result = script_runner.run(SCRIPT_NAME, "-!") assert not result.success assert result.stderr.startswith(SCRIPT_USAGE) def test_prints_version(script_runner: ScriptRunner) -> None: result = script_runner.run(SCRIPT_NAME, "--version") assert result.success assert re.match(rf"{SCRIPT_NAME} \d+\.\d", result.stdout) def test_prints_keybindings_from_zsh(script_runner: ScriptRunner) -> None:
SCRIPT_INPUT = r""" bindkey "^@" set-mark-command bindkey "^L" clear-screen bindkey "^Q" push-line bindkey "^X^U" undo bindkey "^X?" _complete_debug bindkey "^Xu" undo bindkey "^[^L" clear-screen bindkey "^[\"" quote-region bindkey "^['" quote-line bindkey "^[Q" push-line bindkey "^[[A" up-line-or-history bindkey "^[[B" down-line-or-history bindkey "^[q" push-line bindkey "^_" undo bindkey "\M-Q" push-line bindkey "\M-q" push-line """ @pytest.mark.parametrize( "options,expected_output", [ pytest.param( [], """ ^X? _complete_debug ^L clear-screen ^[^L clear-screen ^[[B down-line-or-history ^Q push-line ^[Q push-line ^[q push-line M-Q push-line M-q push-line ^[' quote-line ^[" quote-region ^@ set-mark-command ^_ undo ^Xu undo ^X^U undo ^[[A up-line-or-history """, id="sorted_by_widget", ), pytest.param( ["-i"], """ ^@ set-mark-command ^L clear-screen ^Q push-line ^_ undo ^[" quote-region ^[' quote-line ^[Q push-line ^[q push-line ^[^L clear-screen M-Q push-line M-q push-line ^X? _complete_debug ^Xu undo ^X^U undo ^[[A up-line-or-history ^[[B down-line-or-history """, id="sorted_by_string", ), pytest.param( ["-w"], """ _complete_debug ^X? clear-screen ^L ^[^L down-line-or-history ^[[B push-line ^Q ^[Q ^[q M-Q M-q quote-line ^[' quote-region ^[" set-mark-command ^@ undo ^_ ^Xu ^X^U up-line-or-history ^[[A """, id="grouped_by_widget", ), pytest.param( ["-p"], """ ^ @ L Q _ ^[ " ' Q q ^[^ L M- Q q ^X ? u ^X^ U ^[[ A B """, id="grouped_by_prefix", ), ], ) def test_prints_keybindings_from_stdin( options: List[str], expected_output: str, script_runner: ScriptRunner, ) -> None: stdin = io.StringIO(textwrap.dedent(SCRIPT_INPUT)) result = script_runner.run(SCRIPT_NAME, *options, "-", stdin=stdin) assert result.success assert result.stdout.strip() == textwrap.dedent(expected_output).strip()
result = script_runner.run(SCRIPT_NAME) assert result.success for line in result.stdout.splitlines(): assert re.match(r"(?#string)[M^]\S+(?#space) +(?#widget)[-_a-z]+", line)
dryrun_test.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package registry import ( "context" "encoding/json" "errors" "fmt" "reflect" "testing" "k8s.io/apimachinery/pkg/api/apitesting" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" examplev1 "k8s.io/apiserver/pkg/apis/example/v1" "k8s.io/apiserver/pkg/registry/rest" "k8s.io/apiserver/pkg/storage" etcd3testing "k8s.io/apiserver/pkg/storage/etcd3/testing" "k8s.io/apiserver/pkg/storage/storagebackend/factory" ) func NewDryRunnableTestStorage(t *testing.T) (DryRunnableStorage, func()) { server, sc := etcd3testing.NewUnsecuredEtcd3TestClientServer(t) sc.Codec = apitesting.TestStorageCodec(codecs, examplev1.SchemeGroupVersion) s, destroy, err := factory.Create(*sc, nil) if err != nil { t.Fatalf("Error creating storage: %v", err) } return DryRunnableStorage{Storage: s, Codec: sc.Codec}, func() { destroy() server.Terminate(t) } } func UnstructuredOrDie(j string) *unstructured.Unstructured { m := map[string]interface{}{} err := json.Unmarshal([]byte(j), &m) if err != nil { panic(fmt.Errorf("Failed to unmarshal into Unstructured: %v", err)) } return &unstructured.Unstructured{Object: m} } func TestDryRunCreateDoesntCreate(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, true) if err != nil { t.Fatalf("Failed to create new dry-run object: %v", err) } err = s.Get(context.Background(), "key", storage.GetOptions{}, out) if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyNotFound { t.Errorf("Expected key to be not found, error: %v", err) } } func TestDryRunCreateReturnsObject(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, true) if err != nil { t.Fatalf("Failed to create new dry-run object: %v", err) } if !reflect.DeepEqual(obj, out) { t.Errorf("Returned object different from input object:\nExpected: %v\nGot: %v", obj, out) } } func TestDryRunCreateExistingObjectFails(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, false) if err != nil { t.Fatalf("Failed to create new object: %v", err) } err = s.Create(context.Background(), "key", obj, out, 0, true) if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyExists { t.Errorf("Expected KeyExists error: %v", err) } } func
(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) { return input, nil, errors.New("UpdateFunction shouldn't be called") } err := s.GuaranteedUpdate(context.Background(), "key", obj, false, nil, updateFunc, true, nil) if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyNotFound { t.Errorf("Expected key to be not found, error: %v", err) } } func TestDryRunUpdatePreconditions(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod", "metadata": {"uid": "my-uid"}}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, false) if err != nil { t.Fatalf("Failed to create new object: %v", err) } updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) { u, ok := input.(*unstructured.Unstructured) if !ok { return input, nil, errors.New("Input object is not unstructured") } unstructured.SetNestedField(u.Object, "value", "field") return u, nil, nil } wrongID := types.UID("wrong-uid") myID := types.UID("my-uid") err = s.GuaranteedUpdate(context.Background(), "key", obj, false, &storage.Preconditions{UID: &wrongID}, updateFunc, true, nil) if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeInvalidObj { t.Errorf("Expected invalid object, error: %v", err) } err = s.GuaranteedUpdate(context.Background(), "key", obj, false, &storage.Preconditions{UID: &myID}, updateFunc, true, nil) if err != nil { t.Fatalf("Failed to update with valid precondition: %v", err) } } func TestDryRunUpdateDoesntUpdate(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) created := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, created, 0, false) if err != nil { t.Fatalf("Failed to create new object: %v", err) } updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) { u, ok := input.(*unstructured.Unstructured) if !ok { return input, nil, errors.New("Input object is not unstructured") } unstructured.SetNestedField(u.Object, "value", "field") return u, nil, nil } err = s.GuaranteedUpdate(context.Background(), "key", obj, false, nil, updateFunc, true, nil) if err != nil { t.Fatalf("Failed to dry-run update: %v", err) } out := UnstructuredOrDie(`{}`) err = s.Get(context.Background(), "key", storage.GetOptions{}, out) if err != nil { t.Fatalf("Failed to get storage: %v", err) } if !reflect.DeepEqual(created, out) { t.Fatalf("Returned object %q different from expected %q", created, out) } } func TestDryRunUpdateReturnsObject(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, false) if err != nil { t.Fatalf("Failed to create new object: %v", err) } updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) { u, ok := input.(*unstructured.Unstructured) if !ok { return input, nil, errors.New("Input object is not unstructured") } unstructured.SetNestedField(u.Object, "value", "field") return u, nil, nil } err = s.GuaranteedUpdate(context.Background(), "key", obj, false, nil, updateFunc, true, nil) if err != nil { t.Fatalf("Failed to dry-run update: %v", err) } out = UnstructuredOrDie(`{"field": "value", "kind": "Pod", "metadata": {"resourceVersion": "2"}}`) if !reflect.DeepEqual(obj, out) { t.Fatalf("Returned object %#v different from expected %#v", obj, out) } } func TestDryRunDeleteDoesntDelete(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, false) if err != nil { t.Fatalf("Failed to create new object: %v", err) } err = s.Delete(context.Background(), "key", out, nil, rest.ValidateAllObjectFunc, true, nil) if err != nil { t.Fatalf("Failed to dry-run delete the object: %v", err) } err = s.Get(context.Background(), "key", storage.GetOptions{}, out) if err != nil { t.Fatalf("Failed to retrieve dry-run deleted object: %v", err) } } func TestDryRunDeleteMissingObjectFails(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() out := UnstructuredOrDie(`{}`) err := s.Delete(context.Background(), "key", out, nil, rest.ValidateAllObjectFunc, true, nil) if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyNotFound { t.Errorf("Expected key to be not found, error: %v", err) } } func TestDryRunDeleteReturnsObject(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod"}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, false) if err != nil { t.Fatalf("Failed to create new object: %v", err) } out = UnstructuredOrDie(`{}`) expected := UnstructuredOrDie(`{"kind": "Pod", "metadata": {"resourceVersion": "2"}}`) err = s.Delete(context.Background(), "key", out, nil, rest.ValidateAllObjectFunc, true, nil) if err != nil { t.Fatalf("Failed to delete with valid precondition: %v", err) } if !reflect.DeepEqual(expected, out) { t.Fatalf("Returned object %q doesn't match expected: %q", out, expected) } } func TestDryRunDeletePreconditions(t *testing.T) { s, destroy := NewDryRunnableTestStorage(t) defer destroy() obj := UnstructuredOrDie(`{"kind": "Pod", "metadata": {"uid": "my-uid"}}`) out := UnstructuredOrDie(`{}`) err := s.Create(context.Background(), "key", obj, out, 0, false) if err != nil { t.Fatalf("Failed to create new object: %v", err) } wrongID := types.UID("wrong-uid") myID := types.UID("my-uid") err = s.Delete(context.Background(), "key", out, &storage.Preconditions{UID: &wrongID}, rest.ValidateAllObjectFunc, true, nil) if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeInvalidObj { t.Errorf("Expected invalid object, error: %v", err) } err = s.Delete(context.Background(), "key", out, &storage.Preconditions{UID: &myID}, rest.ValidateAllObjectFunc, true, nil) if err != nil { t.Fatalf("Failed to delete with valid precondition: %v", err) } }
TestDryRunUpdateMissingObjectFails
util.go
package syncer import ( "context" "github.com/pkg/errors" "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/db" "github.com/sourcegraph/sourcegraph/internal/errcode" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/schema" ) func loadRepo(ctx context.Context, tx RepoStore, id api.RepoID) (*types.Repo, error) { r, err := tx.Get(ctx, id) if err != nil { if errcode.IsNotFound(err) { return nil, errors.Errorf("repo not found: %d", id) } return nil, err } return r, nil } func loadExternalService(ctx context.Context, esStore ExternalServiceStore, repo *types.Repo) (*types.ExternalService, error) { var externalService *types.ExternalService args := db.ExternalServicesListOptions{IDs: repo.ExternalServiceIDs()} es, err := esStore.List(ctx, args) if err != nil { return nil, err } for _, e := range es { cfg, err := e.Configuration() if err != nil { return nil, err } switch cfg := cfg.(type) { case *schema.GitHubConnection: if cfg.Token != "" { externalService = e } case *schema.BitbucketServerConnection: if cfg.Token != "" { externalService = e } case *schema.GitLabConnection: if cfg.Token != "" { externalService = e } } if externalService != nil
} if externalService == nil { return nil, errors.Errorf("no external services found for repo %q", repo.Name) } return externalService, nil }
{ break }
win.py
from tkinter import Tk, IntVar, Checkbutton, Button, Label, StringVar from evaluator import Evaluator #src.assignments.assignment13. class Win(Tk): def __init__(self): Tk.__init__(self, None, None) self.wm_title('My first window') self.evaluator = Evaluator() self.label_var = StringVar() Label(self, text="Result: ").pack() #ASSIGNMENT13: add the textvariable property and set its value to self.label_var Label(self, textvariable=self.label_var).pack() #ASSIGNMENT13: add the command property for the button and set its value to self.button_evaluate_handler Button(self, text='Evaluate', command=self.button_evaluate_handler).pack() self.__init__radio_buttons() self.mainloop() def __init__radio_buttons(self): self.check_var_nev = IntVar() self.check_var_rar = IntVar() self.check_var_som = IntVar() self.check_var_oft = IntVar() self.check_var_v_oft = IntVar() self.check_var_always = IntVar() self.check_var_nev.set(0) self.check_var_rar.set(0) self.check_var_som.set(0) self.check_var_oft.set(0) self.check_var_v_oft.set(0) self.check_var_always.set(0) #ASSIGNMENT 13: #for each write code IntVar above create a checkbox with attribute text #Never, Rarely, Sometimes, Often, Very Often, Always #and link the IntVar to the Checkbox variable attribute self.check_nev = Checkbutton(self, text='Never', variable=self.check_var_nev) self.check_rar = Checkbutton(self, text='Rarely', variable=self.check_var_rar) self.check_som = Checkbutton(self, text='Sometimes', variable=self.check_var_som) self.check_oft = Checkbutton(self, text='Often', variable=self.check_var_oft) self.check_v_oft = Checkbutton(self, text='Very Often', variable=self.check_var_v_oft) self.check_always = Checkbutton(self, text='Always', variable=self.check_var_always) self.check_nev.pack() self.check_rar.pack() self.check_som.pack() self.check_oft.pack() self.check_v_oft.pack() self.check_always.pack() def button_evaluate_handler (self):
0 if self.check_var_oft.get()== 0 else 25, 0 if self.check_var_v_oft.get()== 0 else 50, 0 if self.check_var_always.get()== 0 else 150))
self.label_var.set(self.evaluator.faculty_evaluation_result( 0 if self.check_var_nev.get()== 0 else 1 , 0 if self.check_var_rar.get()== 0 else 2, 0 if self.check_var_som.get()== 0 else 3,
environment.js
/*! * Copyright 2010 - 2017 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define([ "module", "./environment/impl/Environment"
], function(module, Environment) { "use strict"; // This singleton instance module does not use an intermediary interface to be resolved, // as it may be used in a bootstrapping phase. /** * The _main_ environment of the JavaScript Pentaho Platform. * * This instance is initialized with the environment specification * which is the value of this module's AMD configuration. * * @name pentaho.environment.main * @type pentaho.environment.IEnvironment * @amd pentaho/environment * @see pentaho.environment.spec.IEnvironment */ return new Environment(module.config()); });
index.test.ts
// tslint:disable-next-line:no-implicit-dependencies import request from 'supertest'; import { config } from 'firebase-functions'; jest.mock('firebase-functions'); const mockedConfig = <jest.Mock<any>>config; import * as webhookHandlers from '../webhookHandlers'; const issueTransferStub = jest.spyOn(webhookHandlers, 'issueTransfer'); const issueReprioritizedStub = jest.spyOn(webhookHandlers, 'issueReprioritized'); const estimateSetStub = jest.spyOn(webhookHandlers, 'estimateSet'); const estimateClearedStub = jest.spyOn(webhookHandlers, 'estimateCleared'); import { app } from '../index'; describe("/hook", () => { const token = 'UNSAFE_TOKEN'; beforeAll(() => { mockedConfig.mockReturnValue({ webhook: { token, }, }); }); afterEach(() => { issueTransferStub.mockReset(); issueReprioritizedStub.mockReset(); estimateSetStub.mockReset(); estimateClearedStub.mockReset(); }); it('should call issueTransfer when type is "issue_transfer"', async () => { issueTransferStub.mockResolvedValue({ status: 200, statusText: 'OK', url: 'http://mockedUrl', text: () => 'mocked response', } as any); await request(app) .post(`/?token=${token}`) .send('type=issue_transfer') .expect(200) .expect({ success: true, error: false, }); expect(issueTransferStub).toHaveBeenCalledWith({ type: 'issue_transfer' }); expect(issueTransferStub).toHaveBeenCalledTimes(1); expect(issueReprioritizedStub).toHaveBeenCalledTimes(0); expect(estimateClearedStub).toHaveBeenCalledTimes(0); expect(estimateSetStub).toHaveBeenCalledTimes(0); }); it('should call issueReprioritized when type is "issue_reprioritized"', async () => { issueReprioritizedStub.mockResolvedValue({ status: 200, statusText: 'OK', url: 'http://mockedUrl', text: () => 'mocked response', } as any); await request(app) .post(`/?token=${token}`) .send('type=issue_reprioritized') .expect(200) .expect({ success: true, error: false, }); expect(issueReprioritizedStub).toHaveBeenCalledWith({ type: 'issue_reprioritized' }); expect(issueTransferStub).toHaveBeenCalledTimes(0); expect(issueReprioritizedStub).toHaveBeenCalledTimes(1); expect(estimateClearedStub).toHaveBeenCalledTimes(0); expect(estimateSetStub).toHaveBeenCalledTimes(0); });
status: 200, statusText: 'OK', url: 'http://mockedUrl', text: () => 'mocked response', } as any); await request(app) .post(`/?token=${token}`) .send('type=estimate_set') .expect(200) .expect({ success: true, error: false, }); expect(estimateSetStub).toHaveBeenCalledWith({ type: 'estimate_set' }); expect(issueTransferStub).toHaveBeenCalledTimes(0); expect(issueReprioritizedStub).toHaveBeenCalledTimes(0); expect(estimateClearedStub).toHaveBeenCalledTimes(0); expect(estimateSetStub).toHaveBeenCalledTimes(1); }); it('should call estimateCleared when type is "estimate_cleared"', async () => { estimateClearedStub.mockResolvedValue({ status: 200, statusText: 'OK', url: 'http://mockedUrl', text: () => 'mocked response', } as any); await request(app) .post(`/?token=${token}`) .send('type=estimate_cleared') .expect(200) .expect({ success: true, error: false, }); expect(estimateClearedStub).toHaveBeenCalledWith({ type: 'estimate_cleared' }); expect(issueTransferStub).toHaveBeenCalledTimes(0); expect(issueReprioritizedStub).toHaveBeenCalledTimes(0); expect(estimateClearedStub).toHaveBeenCalledTimes(1); expect(estimateSetStub).toHaveBeenCalledTimes(0); }); it('should return 400 and not call any hooks with invalid type', async () => { await request(app) .post(`/?token=${token}`) .send('type=invalid') .expect(400) .expect({ success: false, error: "invalid hook", }); expect(issueTransferStub).toHaveBeenCalledTimes(0); expect(issueReprioritizedStub).toHaveBeenCalledTimes(0); expect(estimateClearedStub).toHaveBeenCalledTimes(0); expect(estimateSetStub).toHaveBeenCalledTimes(0); }); it('should return 401 if no token is passed', async () => { await request(app) .post('/') .expect(401) .expect({ success: false, error: '[Unauthorized] No token passed', }); expect(issueTransferStub).toHaveBeenCalledTimes(0); expect(issueReprioritizedStub).toHaveBeenCalledTimes(0); expect(estimateClearedStub).toHaveBeenCalledTimes(0); expect(estimateSetStub).toHaveBeenCalledTimes(0); }); it('should return 401 if invalid token is passed', async () => { await request(app) .post('/?token=INVALID') .expect(401) .expect({ success: false, error: '[Unauthorized] No token passed', }); expect(issueTransferStub).toHaveBeenCalledTimes(0); expect(issueReprioritizedStub).toHaveBeenCalledTimes(0); expect(estimateClearedStub).toHaveBeenCalledTimes(0); expect(estimateSetStub).toHaveBeenCalledTimes(0); }); });
it('should call estimateSet when type is "estimate_set"', async () => { estimateSetStub.mockResolvedValue({
server.rs
mod pokedexpb; mod db; mod errors; use tonic::{transport::Server, Status, Response, Request}; use crate::pokedexpb::poke_dex_server::{PokeDex, PokeDexServer}; use crate::pokedexpb::{PokemonResponse, PokemonsResponse, Query, Pokemon, PokedexEntryResponse, PokemonType}; use dotenv::dotenv; use std::env; #[macro_use] extern crate diesel; extern crate dotenv; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { dotenv().ok(); let port = env::var("APP_PORT").expect("APP_PORT value must be set"); let address = format!("0.0.0.0:{}", port).parse().unwrap(); let context = PokeDexContext {}; println!("Core Services listening on {}", address); Server::builder() .add_service(PokeDexServer::new(context.clone())) .serve(address) .await?; Ok(()) } #[derive(Clone)] pub struct
{} #[tonic::async_trait] impl PokeDex for PokeDexContext { async fn get_pokemon_by_name( &self, request: tonic::Request<Query>, ) -> Result<tonic::Response<PokemonResponse>, tonic::Status> { let requested_name = String::from(request.into_inner().value); match db::Pokemon::find_by_name(requested_name) { Ok(pokemon) => Result::Ok(tonic::Response::new(PokemonResponse { id: pokemon.id, name: pokemon.name, pokemon_type: to_pokemon_types(pokemon.types), })), Err(err) => Result::Err(Status::not_found(err.to_string())) } } async fn get_pokemons_by_type(&self, request: Request<Query>) -> Result<Response<PokemonsResponse>, Status> { let requested_type = String::from(request.into_inner().value); match db::Pokemon::find_by_type(requested_type) { Ok(pokemons) => { Result::Ok(tonic::Response::new(PokemonsResponse { pokemons: pokemons.into_iter().map(|p| { return PokemonResponse { id: p.id, name: p.name, pokemon_type: to_pokemon_types(p.types), }; }).collect() })) } Err(err) => Result::Err(Status::not_found(err.to_string())) } } async fn make_pokedex_entry(&self, request: Request<Pokemon>) -> Result<Response<PokedexEntryResponse>, Status> { let pokemon = request.into_inner(); let pokemon_types: Vec<String> = pokemon.pokemon_type.iter() .map(|t| get_pokemon_type_string(*t)).collect(); let types = pokemon_types.join("|"); match db::Pokemon::save(pokemon.name, types) { Ok(id) => Result::Ok(tonic::Response::new(PokedexEntryResponse { id })), Err(err) => Result::Err(Status::not_found(err.to_string())) } } } fn to_pokemon_types(types: String) -> Vec<i32> { types.split("|").map(|s| find_pokemon_type(s.to_string()) as i32).collect() } fn find_pokemon_type(pokemon_type: String) -> PokemonType { return match String::from(pokemon_type.to_uppercase()).as_str() { "FIRE" => PokemonType::Fire, "GROUND" => PokemonType::Ground, "WATER" => PokemonType::Water, "GRASS" => PokemonType::Grass, "PSYCHIC" => PokemonType::Psychic, "GHOST" => PokemonType::Ghost, "ICE" => PokemonType::Ice, "STEEL" => PokemonType::Steel, "POISON" => PokemonType::Poison, "FLYING" => PokemonType::Flying, "FIGHTING" => PokemonType::Fighting, "ELECTRIC" => PokemonType::Electric, _ => PokemonType::Normal, }; } fn get_pokemon_type_string(pokemon_type: i32) -> String { return match pokemon_type { 1 => String::from("FIRE"), 2 => String::from("GROUND"), 3 => String::from("WATER"), 4 => String::from("GRASS"), 5 => String::from("PSYCHIC"), 6 => String::from("GHOST"), 7 => String::from("ICE"), 8 => String::from("STEEL"), 9 => String::from("POISON"), 10 => String::from("FLYING"), 11 => String::from("FIGHTING"), 12 => String::from("ELECTRIC"), _ => String::from("NORMAL"), }; }
PokeDexContext
genome_crossover.rs
use crate::genome::population::{Individual, ProblemType}; extern crate rand; use crate::genome::fitness_function::FitnessFunction; use rand::prelude::*; use rand::rngs::StdRng; use std::collections::HashSet; use std::convert::TryFrom; use std::string::ToString; pub trait Crossover { type T; fn crossover( &mut self, first_individual: &Individual<Self::T>, second_individual: &Individual<Self::T>, fitness_function: &mut Box<dyn FitnessFunction<T = Self::T>>, problem_type: &ProblemType, ) -> Individual<Self::T>; } #[derive(Clone, Debug)] pub struct StringCrossover { crossover_rate: f64, crossover_points: u32, seed: StdRng, } #[derive(Clone, Debug)] pub struct VecIntegerCrossover { crossover_rate: f64, crossover_points: u32, seed: StdRng, } impl Crossover for StringCrossover { type T = String; fn crossover( &mut self, _first_individual: &Individual<String>, _second_individual: &Individual<String>, fitness_function: &mut Box<dyn FitnessFunction<T = String>>, problem_type: &ProblemType, ) -> Individual<String> { let gen_number = self.seed.gen::<f64>(); if gen_number < self.crossover_rate { let len_of_individual = &_first_individual .retrieve_individual() .to_string() .chars() .count(); println!( "start parent 1: {:?}, start parent 2: {:?}", _first_individual, _second_individual ); if len_of_individual <= &usize::try_from(self.crossover_points).unwrap() { panic!( "Please make your crossover points less than the problem length. Current crossover points is: {} and current problem length is {}", self.crossover_points, len_of_individual ); } let points = get_crossover_locations( len_of_individual, self.crossover_points, self.seed.clone(), ); let mut previous = 0; let mut new_string_individual = String::new(); for (index, &location) in points.iter().enumerate() { let location = usize::try_from(location).unwrap(); if index % 2 == 0 { new_string_individual.push_str( &_first_individual.retrieve_individual().to_string()[previous..location], ) } else { new_string_individual.push_str( &_second_individual.retrieve_individual().to_string()[previous..location], ) } previous = location; } let new_fitness = fitness_function.calculate_fitness(&new_string_individual); let new_individual = Individual::new(new_string_individual, new_fitness); println!("resulting child: {:?}", new_individual.clone()); return new_individual; } return get_default_better_individual(_first_individual, _second_individual, &problem_type) .clone(); } } impl StringCrossover { pub fn new(crossover_rate: f64, crossover_points: u32, seed: [u8; 32]) -> StringCrossover { StringCrossover { crossover_rate, crossover_points, seed: SeedableRng::from_seed(seed), } } } impl Crossover for VecIntegerCrossover { type T = Vec<u32>; fn crossover( &mut self, _first_individual: &Individual<Vec<u32>>, _second_individual: &Individual<Vec<u32>>, fitness_function: &mut Box<dyn FitnessFunction<T = Vec<u32>>>, problem_type: &ProblemType, ) -> Individual<Vec<u32>> { let gen_number = self.seed.gen::<f64>(); if gen_number < self.crossover_rate { let len_of_individual = &_first_individual.retrieve_individual().len(); if len_of_individual <= &usize::try_from(self.crossover_points).unwrap() { panic!( "Please make your crossover points less than the problem length. Current crossover points is: {} and current problem length is {}", self.crossover_points, len_of_individual ); } let points = get_crossover_locations( len_of_individual, self.crossover_points, self.seed.clone(), ); let mut previous = 0; let mut new_vec_individual = Vec::new(); for (index, &location) in points.iter().enumerate() { let location = usize::try_from(location).unwrap(); if index % 2 == 0 { new_vec_individual.extend_from_slice( &_first_individual.retrieve_individual()[previous..location], ); } else { new_vec_individual.extend_from_slice( &_second_individual.retrieve_individual()[previous..location], ); } previous = location; } let new_fitness = fitness_function.calculate_fitness(&new_vec_individual); let new_individual = Individual::new(new_vec_individual, new_fitness); return new_individual; } return get_default_better_individual(_first_individual, _second_individual, problem_type) .clone(); } } impl VecIntegerCrossover { fn new(crossover_rate: f64, crossover_points: u32, seed: [u8; 32]) -> VecIntegerCrossover { VecIntegerCrossover { crossover_rate, crossover_points, seed: SeedableRng::from_seed(seed), } } } fn get_crossover_locations( length_of_problem: &usize, crossover_points: u32, mut seed: StdRng, ) -> Vec<u32> { let mut point_locations = Vec::new(); let mut set_locations = HashSet::new() as HashSet<u32>; while set_locations.len() < usize::try_from(crossover_points).unwrap() { let location = seed.gen_range(1, length_of_problem) as u32; if !set_locations.contains(&location) { set_locations.insert(location); point_locations.push(location) } } let length_of_problem = u32::try_from(*length_of_problem).unwrap(); point_locations.push(length_of_problem); point_locations.sort(); dbg!(point_locations.clone()); point_locations } pub fn get_default_better_individual<'a, T>( indv_one: &'a Individual<T>, indv_two: &'a Individual<T>, problem_type: &ProblemType, ) -> &'a Individual<T> { match problem_type { ProblemType::Max => { if indv_one.fitness() > indv_two.fitness() { indv_one } else { indv_two } } ProblemType::Min => { if indv_one.fitness() > indv_two.fitness() { indv_two } else { indv_one } } } } #[cfg(test)] mod crossover_test { use crate::crossover::genome_crossover::StringCrossover; use crate::crossover::genome_crossover::VecIntegerCrossover; use crate::crossover::genome_crossover::{get_default_better_individual, Crossover}; use crate::genome::fitness_function::FitnessFunction; use crate::genome::population::{Individual, ProblemType}; use std::borrow::Borrow; #[derive(Default, Copy, Clone, Debug)] struct TestStringFitnessFunction; #[derive(Default, Copy, Clone, Debug)] struct TestVecFitnessFunction; impl FitnessFunction for TestStringFitnessFunction { type T = String; fn calculate_fitness(&mut self, individual: &String) -> f64 { let mut fitness = 0.0; for char in individual.chars() { if char.eq(&'1') { fitness += 1.0; } } fitness } } impl FitnessFunction for TestVecFitnessFunction { type T = Vec<u32>; fn calculate_fitness(&mut self, individual: &Vec<u32>) -> f64 { let mut fitness = 0.0; for char in individual { if char.eq(&1) { fitness += 1.0; } } fitness } } #[test] fn test_string_crossover() { let seed: &[u8; 32] = &[ 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, ]; let mut fitness_function: Box<dyn FitnessFunction<T = String>> = Box::new(TestStringFitnessFunction::default()); let individual = Individual::new(String::from("uno"), 5.0); let individual2 = Individual::new(String::from("dos"), 5.0); let mut string_crossover = StringCrossover::new(1.0, 2, *seed); let individual = string_crossover.crossover( &individual, &individual2, &mut fitness_function, &ProblemType::Max, ); assert_eq!(individual.retrieve_individual(), &String::from("uoo")); let mut string_crossover = StringCrossover::new(1.0, 13, *seed); let individual = Individual::new(String::from("10101010101010"), 5.0); let individual2 = Individual::new(String::from("01010101010101"), 5.0); let individual = string_crossover.crossover( &individual, &individual2, &mut fitness_function, &ProblemType::Max, ); assert_eq!( individual.retrieve_individual(), &String::from("11111111111111") ); }
fn test_string_crossover_skip_crossover() { let seed: &[u8; 32] = &[ 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, ]; let mut fitness_function: Box<dyn FitnessFunction<T = String>> = Box::new(TestStringFitnessFunction::default()); let mut individual = Individual::new(String::from("uno"), 5.0); let individual2 = Individual::new(String::from("dos"), 6.0); let mut string_crossover = StringCrossover::new(0.0, 2, *seed); let mut individual3 = string_crossover.crossover( &individual, &individual2, &mut fitness_function, &ProblemType::Max, ); assert_eq!(individual3.retrieve_individual(), &String::from("dos")); let mut string_crossover = StringCrossover::new(0.0, 13, *seed); let individual = Individual::new(String::from("10101010101010"), 5.0); let individual2 = Individual::new(String::from("01010101010101"), 5.0); let mut individual3 = string_crossover.crossover( &individual, &individual2, &mut fitness_function, &ProblemType::Max, ); assert_eq!( individual3.retrieve_individual(), &String::from("01010101010101") ); //println!("{}", individual); } #[test] fn test_vec_integer_crossover() { let seed: &[u8; 32] = &[ 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, ]; let mut fitness_function: Box<dyn FitnessFunction<T = Vec<u32>>> = Box::new(TestVecFitnessFunction::default()); let mut vec_crossover = VecIntegerCrossover::new(1.0, 2, *seed); let individual = Individual::new(vec![1, 2, 3], 5.0); let individual2 = Individual::new(vec![4, 5, 6], 5.0); let individual = vec_crossover.crossover( &individual, &individual2, &mut fitness_function, &ProblemType::Max, ); assert_eq!(individual.retrieve_individual(), &vec![1, 5, 3]); } }
#[test]
Label.tsx
import React from 'react'; type Props = { htmlFor: string; text: string; };
return ( <label className="form__label" htmlFor={htmlFor}> {text} </label> ); }
export default function Label({ htmlFor, text }: Props): JSX.Element {
index.js
var path = require('path'); // Cargar ORM var Sequelize = require('sequelize'); // Usar BBDD SQLite: // DATABASE_URL = sqlite:/// // DATABASE_STORAGE = quiz.sqlite
var url, storage; if (!process.env.DATABASE_URL) { url = "sqlite:///"; storage = "quiz.sqlite"; } else { url = process.env.DATABASE_URL; storage = process.env.DATABASE_STORAGE || ""; } var sequelize = new Sequelize(url, { storage: storage, omitNull: true }); // Importar la definicion de la tabla Quiz de quiz.js var Quiz = sequelize.import(path.join(__dirname,'quiz')); // sequelize.sync() crea e inicializa tabla de preguntas en DB sequelize.sync() .then(function() { // Ya se han creado las tablas necesarias. return Quiz.count() .then(function (c) { if (c === 0) { // la tabla se inicializa solo si está vacía return Quiz.bulkCreate([ {question: 'Capital de Italia', answer: 'Roma'}, {question: 'Capital de Portugal', answer: 'Lisboa'} ]) .then(function() { console.log('Base de datos inicializada con datos'); }); } }); }) .catch(function(error) { console.log("Error Sincronizando las tablas de la BBDD:", error); process.exit(1); }); exports.Quiz = Quiz; // exportar definición de tabla Quiz
// Usar BBDD Postgres: // DATABASE_URL = postgres://user:passwd@host:port/database
message.rs
//! Constants, error types, and functions for validating [`Message`] fields. //! //! [`Message`]: twilight_model::channel::Message use crate::{ component::{ComponentValidationErrorType, COMPONENT_COUNT}, embed::{chars as embed_chars, EmbedValidationErrorType, EMBED_TOTAL_LENGTH}, request::ValidationError, }; use std::{ error::Error, fmt::{Display, Formatter, Result as FmtResult}, }; use twilight_model::{ application::component::Component, channel::embed::Embed, id::{marker::StickerMarker, Id}, }; /// Maximum number of embeds that a message may have. pub const EMBED_COUNT_LIMIT: usize = 10; /// Maximum length of message content. pub const MESSAGE_CONTENT_LENGTH_MAX: usize = 2000; /// Maximum amount of stickers. pub const STICKER_MAX: usize = 3; /// ASCII dash. const DASH: char = '-'; /// ASCII dot. const DOT: char = '.'; /// ASCII underscore. const UNDERSCORE: char = '_'; /// A message is not valid. #[derive(Debug)] pub struct MessageValidationError { /// Type of error that occurred. kind: MessageValidationErrorType, /// Source of the error, if any. source: Option<Box<dyn Error + Send + Sync>>, } impl MessageValidationError { /// Immutable reference to the type of error that occurred. #[must_use = "retrieving the type has no effect if left unused"] pub const fn kind(&self) -> &MessageValidationErrorType { &self.kind } /// Consume the error, returning the source error if there is any. #[must_use = "consuming the error and retrieving the source has no effect if left unused"] pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> { self.source } /// Consume the error, returning the owned error type and the source error. #[must_use = "consuming the error into its parts has no effect if left unused"] pub fn into_parts( self, ) -> ( MessageValidationErrorType, Option<Box<dyn Error + Send + Sync>>, ) { (self.kind, self.source) } /// Create a [`MessageValidationError`] from a [`ValidationError`]. #[must_use = "has no effect if unused"] pub fn from_validation_error( kind: MessageValidationErrorType, source: ValidationError, ) -> Self { Self { kind, source: Some(Box::new(source)), } } } impl Display for MessageValidationError { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match &self.kind { MessageValidationErrorType::AttachmentFilename { filename } => { f.write_str("attachment filename `")?; Display::fmt(filename, f)?; f.write_str("`is invalid") } MessageValidationErrorType::ComponentCount { count } => { Display::fmt(count, f)?; f.write_str(" components were provided, but only ")?; Display::fmt(&COMPONENT_COUNT, f)?; f.write_str(" root components are allowed") } MessageValidationErrorType::ComponentInvalid { .. } => { f.write_str("a provided component is invalid") } MessageValidationErrorType::ContentInvalid => f.write_str("message content is invalid"), MessageValidationErrorType::EmbedInvalid { idx, .. } =>
MessageValidationErrorType::StickersInvalid { len } => { f.write_str("amount of stickers provided is ")?; Display::fmt(len, f)?; f.write_str(" but it must be at most ")?; Display::fmt(&STICKER_MAX, f) } MessageValidationErrorType::TooManyEmbeds { .. } => { f.write_str("message has too many embeds") } MessageValidationErrorType::WebhookUsername { .. } => { if let Some(source) = self.source() { Display::fmt(&source, f) } else { f.write_str("webhook username is invalid") } } } } } impl Error for MessageValidationError {} /// Type of [`MessageValidationError`] that occurred. #[derive(Debug)] pub enum MessageValidationErrorType { /// Attachment filename is not valid. AttachmentFilename { /// Invalid filename. filename: String, }, /// Too many message components were provided. ComponentCount { /// Number of components that were provided. count: usize, }, /// An invalid message component was provided. ComponentInvalid { /// Index of the component. idx: usize, /// Additional details about the validation failure type. kind: ComponentValidationErrorType, }, /// Returned when the content is over 2000 UTF-16 characters. ContentInvalid, /// Returned when the embed is invalid. EmbedInvalid { /// Index of the embed. idx: usize, /// Additional details about the validation failure type. kind: EmbedValidationErrorType, }, /// Amount of stickers provided is invalid. StickersInvalid { /// Invalid length. len: usize, }, /// Too many embeds were provided. /// /// A followup message can have up to 10 embeds. TooManyEmbeds, /// Provided webhook username was invalid. WebhookUsername, } /// Ensure an attachment's filename is correct. /// /// The filename can contain ASCII alphanumeric characters, dots, dashes, and /// underscores. /// /// # Errors /// /// Returns an error of type [`AttachmentFilename`] if the filename is invalid. /// /// [`AttachmentFilename`]: MessageValidationErrorType::AttachmentFilename pub fn attachment_filename(filename: impl AsRef<str>) -> Result<(), MessageValidationError> { if filename .as_ref() .chars() .all(|c| (c.is_ascii_alphanumeric() || c == DOT || c == DASH || c == UNDERSCORE)) { Ok(()) } else { Err(MessageValidationError { kind: MessageValidationErrorType::AttachmentFilename { filename: filename.as_ref().to_string(), }, source: None, }) } } /// Ensure a list of components is correct. /// /// # Errors /// /// Returns a [`ComponentValidationErrorType::ComponentCount`] if there are /// too many components in the provided list. /// /// Refer to the errors section of [`component`] for a list of errors that may /// be returned as a result of validating each provided component. /// /// [`component`]: crate::component::component pub fn components(components: &[Component]) -> Result<(), MessageValidationError> { let count = components.len(); if count > COMPONENT_COUNT { Err(MessageValidationError { kind: MessageValidationErrorType::ComponentCount { count }, source: None, }) } else { for (idx, component) in components.iter().enumerate() { crate::component::component(component).map_err(|source| { let (kind, source) = source.into_parts(); MessageValidationError { kind: MessageValidationErrorType::ComponentInvalid { idx, kind }, source, } })?; } Ok(()) } } /// Ensure a message's content is correct. /// /// # Errors /// /// Returns an error of type [`ContentInvalid`] if the message's content is /// invalid. /// /// [`ContentInvalid`]: MessageValidationErrorType::ContentInvalid pub fn content(value: impl AsRef<str>) -> Result<(), MessageValidationError> { // <https://discordapp.com/developers/docs/resources/channel#create-message-params> if value.as_ref().chars().count() <= MESSAGE_CONTENT_LENGTH_MAX { Ok(()) } else { Err(MessageValidationError { kind: MessageValidationErrorType::ContentInvalid, source: None, }) } } /// Ensure a list of embeds is correct. /// /// # Errors /// /// Returns an error of type [`TooManyEmbeds`] if there are too many embeds. /// /// Otherwise, refer to the errors section of [`embed`] for a list of errors /// that may occur. /// /// [`TooManyEmbeds`]: MessageValidationErrorType::TooManyEmbeds /// [`embed`]: crate::embed::embed pub fn embeds(embeds: &[Embed]) -> Result<(), MessageValidationError> { if embeds.len() > EMBED_COUNT_LIMIT { Err(MessageValidationError { kind: MessageValidationErrorType::TooManyEmbeds, source: None, }) } else { let mut chars = 0; for (idx, embed) in embeds.iter().enumerate() { chars += embed_chars(embed); if chars > EMBED_TOTAL_LENGTH { return Err(MessageValidationError { kind: MessageValidationErrorType::EmbedInvalid { idx, kind: EmbedValidationErrorType::EmbedTooLarge { chars }, }, source: None, }); } crate::embed::embed(embed).map_err(|source| { let (kind, source) = source.into_parts(); MessageValidationError { kind: MessageValidationErrorType::EmbedInvalid { idx, kind }, source, } })?; } Ok(()) } } /// Ensure that the amount of stickers in a message is correct. /// /// There must be at most [`STICKER_MAX`] stickers. This is based on [this /// documentation entry]. /// /// # Errors /// /// Returns an error of type [`StickersInvalid`] if the length is invalid. /// /// [`StickersInvalid`]: MessageValidationErrorType::StickersInvalid /// [this documentation entry]: https://discord.com/developers/docs/resources/channel#create-message-jsonform-params pub fn sticker_ids(sticker_ids: &[Id<StickerMarker>]) -> Result<(), MessageValidationError> { let len = sticker_ids.len(); if len <= STICKER_MAX { Ok(()) } else { Err(MessageValidationError { kind: MessageValidationErrorType::StickersInvalid { len }, source: None, }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_attachment_filename() { assert!(attachment_filename("one.jpg").is_ok()); assert!(attachment_filename("two.png").is_ok()); assert!(attachment_filename("three.gif").is_ok()); assert!(attachment_filename(".dots-dashes_underscores.gif").is_ok()); assert!(attachment_filename("????????").is_err()); } #[test] fn test_content() { assert!(content("").is_ok()); assert!(content("a".repeat(2000)).is_ok()); assert!(content("a".repeat(2001)).is_err()); } }
{ f.write_str("embed at index ")?; Display::fmt(idx, f)?; f.write_str(" is invalid") }
mod.rs
//! netdb implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xns/netdb.h.html mod dns; use core::{ mem, ptr, slice, str::{self, FromStr}, }; use alloc::{borrow::ToOwned, boxed::Box, str::SplitWhitespace, vec::Vec}; use crate::{ c_str::{CStr, CString}, header::{ arpa_inet::{htons, inet_aton, ntohl}, errno::*, fcntl::O_RDONLY, netinet_in::{in_addr, sockaddr_in, sockaddr_in6}, stdlib::atoi, strings::strcasecmp, sys_socket::{constants::AF_INET, sa_family_t, sockaddr, socklen_t}, unistd::SEEK_SET, }, platform::{ self, rlb::{Line, RawLineBuffer}, types::*, Pal, Sys, }, }; #[cfg(target_os = "linux")] #[path = "linux.rs"] pub mod sys; #[cfg(target_os = "redox")] #[path = "redox.rs"] pub mod sys; #[cfg(target_os = "windows")] #[path = "windows.rs"] pub mod sys; pub use self::host::*; pub mod host; pub use self::lookup::*; pub mod lookup; #[repr(C)] pub struct hostent { h_name: *mut c_char, h_aliases: *mut *mut c_char, h_addrtype: c_int, h_length: c_int, h_addr_list: *mut *mut c_char, } #[repr(C)] pub struct netent { n_name: *mut c_char, /* official name of net */ n_aliases: *mut *mut c_char, /* alias list */ n_addrtype: c_int, /* net address type */ n_net: c_ulong, /* network # */ } #[repr(C)] pub struct protoent { p_name: *mut c_char, /* official protocol name */ p_aliases: *mut *mut c_char, /* alias list */ p_proto: c_int, /* protocol # */ } #[repr(C)] pub struct servent { s_name: *mut c_char, /* official service name */ s_aliases: *mut *mut c_char, /* alias list */ s_port: c_int, /* port # */ s_proto: *mut c_char, /* protocol to use */ } #[repr(C)] #[derive(Debug)] pub struct addrinfo { ai_flags: c_int, /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */ ai_family: c_int, /* PF_xxx */ ai_socktype: c_int, /* SOCK_xxx */ ai_protocol: c_int, /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ ai_addrlen: size_t, /* length of ai_addr */ ai_canonname: *mut c_char, /* canonical name for hostname */ ai_addr: *mut sockaddr, /* binary address */ ai_next: *mut addrinfo, /* next structure in linked list */ } pub const AI_PASSIVE: c_int = 0x0001; pub const AI_CANONNAME: c_int = 0x0002; pub const AI_NUMERICHOST: c_int = 0x0004; pub const AI_V4MAPPED: c_int = 0x0008; pub const AI_ALL: c_int = 0x0010; pub const AI_ADDRCONFIG: c_int = 0x0020; pub const AI_NUMERICSERV: c_int = 0x0400; pub const EAI_BADFLAGS: c_int = -1; pub const EAI_NONAME: c_int = -2; pub const EAI_AGAIN: c_int = -3; pub const EAI_FAIL: c_int = -4; pub const EAI_NODATA: c_int = -5; pub const EAI_FAMILY: c_int = -6; pub const EAI_SOCKTYPE: c_int = -7; pub const EAI_SERVICE: c_int = -8; pub const EAI_ADDRFAMILY: c_int = -9; pub const EAI_MEMORY: c_int = -10; pub const EAI_SYSTEM: c_int = -11; pub const EAI_OVERFLOW: c_int = -12; pub const NI_MAXHOST: c_int = 1025; pub const NI_MAXSERV: c_int = 32; pub const NI_NUMERICHOST: c_int = 0x0001; pub const NI_NUMERICSERV: c_int = 0x0002; pub const NI_NOFQDN: c_int = 0x0004; pub const NI_NAMEREQD: c_int = 0x0008; pub const NI_DGRAM: c_int = 0x0010; static mut NETDB: c_int = 0; pub static mut NET_ENTRY: netent = netent { n_name: ptr::null_mut(), n_aliases: ptr::null_mut(), n_addrtype: 0, n_net: 0, }; pub static mut NET_NAME: Option<Vec<u8>> = None; pub static mut NET_ALIASES: Option<Vec<Vec<u8>>> = None; pub static mut NET_ADDR: Option<u32> = None; static mut N_POS: usize = 0; static mut NET_STAYOPEN: c_int = 0; #[allow(non_upper_case_globals)] #[no_mangle] pub static mut h_errno: c_int = 0; pub const HOST_NOT_FOUND: c_int = 1; pub const NO_DATA: c_int = 2; pub const NO_RECOVERY: c_int = 3; pub const TRY_AGAIN: c_int = 4; static mut PROTODB: c_int = 0; static mut PROTO_ENTRY: protoent = protoent { p_name: ptr::null_mut(), p_aliases: ptr::null_mut(), p_proto: 0 as c_int, }; static mut PROTO_NAME: Option<Vec<u8>> = None; static mut PROTO_ALIASES: Option<Vec<Vec<u8>>> = None; static mut PROTO_NUM: Option<c_int> = None; static mut P_POS: usize = 0; static mut PROTO_STAYOPEN: c_int = 0; static mut SERVDB: c_int = 0; static mut SERV_ENTRY: servent = servent { s_name: ptr::null_mut(), s_aliases: ptr::null_mut(), s_port: 0 as c_int, s_proto: ptr::null_mut(), }; static mut SERV_NAME: Option<Vec<u8>> = None; static mut SERV_ALIASES: Option<Vec<Vec<u8>>> = None; static mut SERV_PORT: Option<c_int> = None; static mut SERV_PROTO: Option<Vec<u8>> = None; static mut S_POS: usize = 0; static mut SERV_STAYOPEN: c_int = 0; fn bytes_to_box_str(bytes: &[u8]) -> Box<str> { Box::from(core::str::from_utf8(bytes).unwrap_or("")) } #[no_mangle] pub unsafe extern "C" fn endnetent() { Sys::close(NETDB); NETDB = 0; } #[no_mangle] pub unsafe extern "C" fn endprotoent() { Sys::close(PROTODB); PROTODB = 0; } #[no_mangle] pub unsafe extern "C" fn endservent() { Sys::close(SERVDB); SERVDB = 0; } #[no_mangle] pub unsafe extern "C" fn gethostbyaddr( v: *const c_void, length: socklen_t, format: c_int, ) -> *mut hostent { let addr: in_addr = *(v as *mut in_addr); // check the hosts file first let mut p: *mut hostent; sethostent(HOST_STAYOPEN); while { p = gethostent(); !p.is_null() } { let mut cp = (*p).h_addr_list; loop { if cp.is_null() { break; } if (*cp).is_null() { break; } let mut cp_slice: [i8; 4] = [0i8; 4]; (*cp).copy_to(cp_slice.as_mut_ptr(), 4); let cp_s_addr = mem::transmute::<[i8; 4], u32>(cp_slice); if cp_s_addr == addr.s_addr { sethostent(HOST_STAYOPEN); return p; } cp = cp.offset(1); } } //TODO actually get aliases let mut _host_aliases: Vec<Vec<u8>> = Vec::new(); _host_aliases.push(vec![b'\0']); let mut host_aliases: Vec<*mut i8> = Vec::new(); host_aliases.push(ptr::null_mut()); HOST_ALIASES = Some(_host_aliases); match lookup_addr(addr) { Ok(s) => { _HOST_ADDR_LIST = mem::transmute::<u32, [u8; 4]>(addr.s_addr); HOST_ADDR_LIST = [_HOST_ADDR_LIST.as_mut_ptr() as *mut c_char, ptr::null_mut()]; let host_name = s[0].to_vec(); HOST_NAME = Some(host_name); HOST_ENTRY = hostent { h_name: HOST_NAME.as_mut().unwrap().as_mut_ptr() as *mut c_char, h_aliases: host_aliases.as_mut_slice().as_mut_ptr() as *mut *mut i8, h_addrtype: format, h_length: length as i32, h_addr_list: HOST_ADDR_LIST.as_mut_ptr(), }; &mut HOST_ENTRY } Err(e) => { platform::errno = e; ptr::null_mut() } } } #[no_mangle] pub unsafe extern "C" fn gethostbyname(name: *const c_char) -> *mut hostent { // check if some idiot gave us an address instead of a name let name_cstr = CStr::from_ptr(name); let mut octets = str::from_utf8_unchecked(name_cstr.to_bytes()).split('.'); let mut s_addr = [0u8; 4]; let mut is_addr = true; for item in &mut s_addr { if let Some(n) = octets.next().and_then(|x| u8::from_str(x).ok()) { *item = n; } else { is_addr = false; } } if octets.next() != None { is_addr = false; } if is_addr { let addr = in_addr { s_addr: mem::transmute::<[u8; 4], u32>(s_addr), }; return gethostbyaddr(&addr as *const _ as *const c_void, 4, AF_INET); } // check the hosts file first let mut p: *mut hostent; sethostent(HOST_STAYOPEN); while { p = gethostent(); !p.is_null() } { if strcasecmp((*p).h_name, name) == 0 { sethostent(HOST_STAYOPEN); return p; } let mut cp = (*p).h_aliases; loop { if cp.is_null() { break; } if (*cp).is_null() { break; } if strcasecmp(*cp, name) == 0 { sethostent(HOST_STAYOPEN); return p; } cp = cp.offset(1); } } let name_cstr = CStr::from_ptr(name); let mut host = match lookup_host(str::from_utf8_unchecked(name_cstr.to_bytes())) { Ok(lookuphost) => lookuphost, Err(e) => { platform::errno = e; return ptr::null_mut(); } }; let host_addr = match host.next() { Some(result) => result, None => { platform::errno = ENOENT; return ptr::null_mut(); } }; let host_name: Vec<u8> = name_cstr.to_bytes().to_vec(); HOST_NAME = Some(host_name); _HOST_ADDR_LIST = mem::transmute::<u32, [u8; 4]>(host_addr.s_addr); HOST_ADDR_LIST = [_HOST_ADDR_LIST.as_mut_ptr() as *mut c_char, ptr::null_mut()]; HOST_ADDR = Some(host_addr); //TODO actually get aliases let mut _host_aliases: Vec<Vec<u8>> = Vec::new(); _host_aliases.push(vec![b'\0']); let mut host_aliases: Vec<*mut i8> = Vec::new(); host_aliases.push(ptr::null_mut()); host_aliases.push(ptr::null_mut()); HOST_ALIASES = Some(_host_aliases); HOST_ENTRY = hostent { h_name: HOST_NAME.as_mut().unwrap().as_mut_ptr() as *mut c_char, h_aliases: host_aliases.as_mut_slice().as_mut_ptr() as *mut *mut i8, h_addrtype: AF_INET, h_length: 4, h_addr_list: HOST_ADDR_LIST.as_mut_ptr(), }; sethostent(HOST_STAYOPEN); &mut HOST_ENTRY as *mut hostent } pub unsafe extern "C" fn getnetbyaddr(net: u32, net_type: c_int) -> *mut netent { unimplemented!(); } #[no_mangle] pub unsafe extern "C" fn getnetbyname(name: *const c_char) -> *mut netent { let mut n: *mut netent; setnetent(NET_STAYOPEN); while { n = getnetent(); !n.is_null() } { if strcasecmp((*n).n_name, name) == 0 { setnetent(NET_STAYOPEN); return n; } } setnetent(NET_STAYOPEN); platform::errno = ENOENT; ptr::null_mut() as *mut netent } #[no_mangle] pub unsafe extern "C" fn getnetent() -> *mut netent { if NETDB == 0 { NETDB = Sys::open(&CString::new("/etc/networks").unwrap(), O_RDONLY, 0); } let mut rlb = RawLineBuffer::new(NETDB); rlb.seek(N_POS); let mut r: Box<str> = Box::default(); while r.is_empty() || r.split_whitespace().next() == None || r.starts_with('#') { r = match rlb.next() { Line::Some(s) => bytes_to_box_str(s), _ => { if NET_STAYOPEN == 0 { endnetent(); } return ptr::null_mut(); } }; } rlb.next(); N_POS = rlb.line_pos(); let mut iter: SplitWhitespace<'_> = r.split_whitespace(); let mut net_name = iter.next().unwrap().as_bytes().to_vec(); net_name.push(b'\0'); NET_NAME = Some(net_name); let mut addr_vec = iter.next().unwrap().as_bytes().to_vec(); addr_vec.push(b'\0'); let addr_cstr = addr_vec.as_slice().as_ptr() as *const i8; let mut addr = mem::MaybeUninit::uninit(); inet_aton(addr_cstr, addr.as_mut_ptr()); let addr = addr.assume_init(); NET_ADDR = Some(ntohl(addr.s_addr)); let mut _net_aliases: Vec<Vec<u8>> = Vec::new(); for s in iter { let mut alias = s.as_bytes().to_vec(); alias.push(b'\0'); _net_aliases.push(alias); } let mut net_aliases: Vec<*mut i8> = _net_aliases .iter_mut() .map(|x| x.as_mut_ptr() as *mut i8) .collect(); net_aliases.push(ptr::null_mut()); NET_ALIASES = Some(_net_aliases); NET_ENTRY = netent { n_name: NET_NAME.as_mut().unwrap().as_mut_ptr() as *mut c_char, n_aliases: net_aliases.as_mut_slice().as_mut_ptr() as *mut *mut i8, n_addrtype: AF_INET, n_net: NET_ADDR.unwrap() as c_ulong, }; &mut NET_ENTRY as *mut netent } #[no_mangle] pub unsafe extern "C" fn getprotobyname(name: *const c_char) -> *mut protoent { let mut p: *mut protoent; setprotoent(PROTO_STAYOPEN); while { p = getprotoent(); !p.is_null() } { if strcasecmp((*p).p_name, name) == 0 { setprotoent(PROTO_STAYOPEN); return p; } let mut cp = (*p).p_aliases; loop { if cp.is_null() { setprotoent(PROTO_STAYOPEN); break; } if (*cp).is_null() { setprotoent(PROTO_STAYOPEN); break; } if strcasecmp(*cp, name) == 0 { setprotoent(PROTO_STAYOPEN); return p; } cp = cp.offset(1); } } setprotoent(PROTO_STAYOPEN); platform::errno = ENOENT; ptr::null_mut() as *mut protoent } #[no_mangle] pub unsafe extern "C" fn getprotobynumber(number: c_int) -> *mut protoent { setprotoent(PROTO_STAYOPEN); let mut p: *mut protoent; while { p = getprotoent(); !p.is_null() } { if (*p).p_proto == number { setprotoent(PROTO_STAYOPEN); return p; } } setprotoent(PROTO_STAYOPEN); platform::errno = ENOENT; ptr::null_mut() as *mut protoent } #[no_mangle] pub unsafe extern "C" fn getprotoent() -> *mut protoent { if PROTODB == 0 { PROTODB = Sys::open(&CString::new("/etc/protocols").unwrap(), O_RDONLY, 0); } let mut rlb = RawLineBuffer::new(PROTODB); rlb.seek(P_POS); let mut r: Box<str> = Box::default(); while r.is_empty() || r.split_whitespace().next() == None || r.starts_with('#') { r = match rlb.next() { Line::Some(s) => bytes_to_box_str(s), _ => { if PROTO_STAYOPEN == 0 { endprotoent(); } return ptr::null_mut(); } }; } rlb.next(); P_POS = rlb.line_pos(); let mut iter: SplitWhitespace<'_> = r.split_whitespace(); let mut proto_name: Vec<u8> = iter.next().unwrap().as_bytes().to_vec(); proto_name.push(b'\0'); let mut num = iter.next().unwrap().as_bytes().to_vec(); num.push(b'\0'); PROTO_NUM = Some(atoi(num.as_mut_slice().as_mut_ptr() as *mut i8)); let mut _proto_aliases: Vec<Vec<u8>> = Vec::new(); for s in iter { let mut alias = s.as_bytes().to_vec(); alias.push(b'\0'); _proto_aliases.push(alias); } let mut proto_aliases: Vec<*mut i8> = _proto_aliases .iter_mut() .map(|x| x.as_mut_ptr() as *mut i8) .collect(); proto_aliases.push(ptr::null_mut()); PROTO_ALIASES = Some(_proto_aliases); PROTO_NAME = Some(proto_name); PROTO_ENTRY = protoent { p_name: PROTO_NAME.as_mut().unwrap().as_mut_slice().as_mut_ptr() as *mut c_char, p_aliases: proto_aliases.as_mut_slice().as_mut_ptr() as *mut *mut i8, p_proto: PROTO_NUM.unwrap(), }; if PROTO_STAYOPEN == 0 { endprotoent(); } &mut PROTO_ENTRY as *mut protoent } #[no_mangle] pub unsafe extern "C" fn getservbyname(name: *const c_char, proto: *const c_char) -> *mut servent { setservent(SERV_STAYOPEN); let mut p: *mut servent; if proto.is_null() { while { p = getservent(); !p.is_null() } { if strcasecmp((*p).s_name, name) == 0 { setservent(SERV_STAYOPEN); return p; } } } else { while { p = getservent(); !p.is_null() } { if strcasecmp((*p).s_name, name) == 0 && strcasecmp((*p).s_proto, proto) == 0 { setservent(SERV_STAYOPEN); return p; } } } setservent(SERV_STAYOPEN); platform::errno = ENOENT; ptr::null_mut() as *mut servent } #[no_mangle] pub unsafe extern "C" fn getservbyport(port: c_int, proto: *const c_char) -> *mut servent { setservent(SERV_STAYOPEN); let mut p: *mut servent; if proto.is_null() { while { p = getservent(); !p.is_null() } { if (*p).s_port == port { setservent(SERV_STAYOPEN); return p; } } } else { while { p = getservent(); !p.is_null() } { if (*p).s_port == port && strcasecmp((*p).s_proto, proto) == 0 { setservent(SERV_STAYOPEN); return p; } } } setservent(SERV_STAYOPEN); platform::errno = ENOENT; ptr::null_mut() } #[no_mangle] pub unsafe extern "C" fn getservent() -> *mut servent { if SERVDB == 0 { SERVDB = Sys::open(&CString::new("/etc/services").unwrap(), O_RDONLY, 0); } let mut rlb = RawLineBuffer::new(SERVDB); rlb.seek(S_POS); let r: Box<str> = Box::default(); loop { let r = match rlb.next() { Line::Some(s) => bytes_to_box_str(s), _ => { if SERV_STAYOPEN == 0 { endservent(); } return ptr::null_mut(); } }; let mut iter = r.split_whitespace(); let mut serv_name = match iter.next() { Some(serv_name) => serv_name.as_bytes().to_vec(), None => continue, }; serv_name.push(b'\0'); let port_proto = match iter.next() { Some(port_proto) => port_proto, None => continue, }; let mut split = port_proto.split('/'); let mut port = match split.next() { Some(port) => port.as_bytes().to_vec(), None => continue, }; port.push(b'\0'); SERV_PORT = Some(htons(atoi(port.as_mut_slice().as_mut_ptr() as *mut i8) as u16) as u32 as i32); let mut proto = match split.next() { Some(proto) => proto.as_bytes().to_vec(), None => continue, }; proto.push(b'\0'); rlb.next(); S_POS = rlb.line_pos(); /* *let mut _serv_aliases: Vec<Vec<u8>> = Vec::new(); *loop { * let mut alias = match iter.next() { * Some(s) => s.as_bytes().to_vec(), * _ => break * }; * alias.push(b'\0'); * _serv_aliases.push(alias); *} *let mut serv_aliases: Vec<*mut i8> = _serv_aliases.iter_mut().map(|x| x.as_mut_ptr() as *mut i8).collect(); *serv_aliases.push(ptr::null_mut()); * */ let mut _serv_aliases: Vec<Vec<u8>> = Vec::new(); _serv_aliases.push(vec![b'\0']); let mut serv_aliases: Vec<*mut i8> = Vec::new(); serv_aliases.push(ptr::null_mut()); serv_aliases.push(ptr::null_mut()); SERV_ALIASES = Some(_serv_aliases); SERV_NAME = Some(serv_name); SERV_PROTO = Some(proto); SERV_ENTRY = servent { s_name: SERV_NAME.as_mut().unwrap().as_mut_slice().as_mut_ptr() as *mut c_char, s_aliases: serv_aliases.as_mut_slice().as_mut_ptr() as *mut *mut i8, s_port: SERV_PORT.unwrap(), s_proto: SERV_PROTO.as_mut().unwrap().as_mut_slice().as_mut_ptr() as *mut c_char, }; if SERV_STAYOPEN == 0 { endservent(); } break &mut SERV_ENTRY as *mut servent; } } #[no_mangle] pub unsafe extern "C" fn setnetent(stayopen: c_int) { NET_STAYOPEN = stayopen; if NETDB == 0 { NETDB = Sys::open(&CString::new("/etc/networks").unwrap(), O_RDONLY, 0) } else { Sys::lseek(NETDB, 0, SEEK_SET); N_POS = 0; } } #[no_mangle] pub unsafe extern "C" fn setprotoent(stayopen: c_int) { PROTO_STAYOPEN = stayopen; if PROTODB == 0 { PROTODB = Sys::open(&CString::new("/etc/protocols").unwrap(), O_RDONLY, 0) } else { Sys::lseek(PROTODB, 0, SEEK_SET); P_POS = 0; } } #[no_mangle] pub unsafe extern "C" fn setservent(stayopen: c_int) { SERV_STAYOPEN = stayopen; if SERVDB == 0 { SERVDB = Sys::open(&CString::new("/etc/services").unwrap(), O_RDONLY, 0) } else { Sys::lseek(SERVDB, 0, SEEK_SET); S_POS = 0; } } #[no_mangle] pub unsafe extern "C" fn getaddrinfo( node: *const c_char, service: *const c_char, hints: *const addrinfo, res: *mut *mut addrinfo, ) -> c_int { //TODO: getaddrinfo let node_opt = if node.is_null() { None } else { Some(CStr::from_ptr(node)) }; let service_opt = if service.is_null() { None } else { Some(CStr::from_ptr(service)) }; let hints_opt = if hints.is_null() { None } else { Some(&*hints) }; trace!( "getaddrinfo({:?}, {:?}, {:?})", node_opt.map(|c| str::from_utf8_unchecked(c.to_bytes())), service_opt.map(|c| str::from_utf8_unchecked(c.to_bytes())), hints_opt ); //TODO: Use hints let mut ai_flags = hints_opt.map_or(0, |hints| hints.ai_flags); let mut ai_family; // = hints_opt.map_or(AF_UNSPEC, |hints| hints.ai_family); let ai_socktype = hints_opt.map_or(0, |hints| hints.ai_socktype); let mut ai_protocol; // = hints_opt.map_or(0, |hints| hints.ai_protocol); *res = ptr::null_mut(); let mut port = 0; if let Some(service) = service_opt { //TODO: Support other service definitions as well as AI_NUMERICSERV match str::from_utf8_unchecked(service.to_bytes()).parse::<u16>() { Ok(ok) => port = ok, Err(_err) => (), } } //TODO: Check hosts file if let Some(node) = node_opt { //TODO: Support AI_NUMERICHOST let lookuphost = match lookup_host(str::from_utf8_unchecked(node.to_bytes())) { Ok(lookuphost) => lookuphost, Err(e) => { platform::errno = e; return EAI_SYSTEM; } }; for in_addr in lookuphost { ai_family = AF_INET; ai_protocol = 0; let ai_addr = Box::into_raw(Box::new(sockaddr_in { sin_family: ai_family as sa_family_t, sin_port: htons(port), sin_addr: in_addr, sin_zero: [0; 8], })) as *mut sockaddr; let ai_addrlen = mem::size_of::<sockaddr_in>(); let ai_canonname = if ai_flags & AI_CANONNAME > 0 { ai_flags &= !AI_CANONNAME; node.to_owned().into_raw() } else { ptr::null_mut() }; let addrinfo = Box::new(addrinfo { ai_flags: 0, ai_family, ai_socktype, ai_protocol, ai_addrlen, ai_canonname, ai_addr, ai_next: ptr::null_mut(), }); let mut indirect = res; while !(*indirect).is_null() { indirect = &mut (**indirect).ai_next; } *indirect = Box::into_raw(addrinfo); } } 0 } #[no_mangle] pub unsafe extern "C" fn getnameinfo( addr: *const sockaddr, addrlen: socklen_t, host: *mut c_char, hostlen: socklen_t, serv: *mut c_char, servlen: socklen_t, flags: c_int, ) -> c_int { //TODO: getnameinfo if addrlen as usize != mem::size_of::<sockaddr_in>() { return EAI_FAMILY; } let addr = &*(addr as *const sockaddr_in); let host_opt = if host.is_null() { None } else { Some(slice::from_raw_parts_mut(host, hostlen as usize)) }; let serv_opt = if serv.is_null() { None } else { Some(slice::from_raw_parts_mut(serv, servlen as usize)) }; eprintln!("getnameinfo({:p}, {}, {:#x})", addr, addrlen, flags); platform::errno = ENOSYS; EAI_SYSTEM } #[no_mangle] pub unsafe extern "C" fn freeaddrinfo(res: *mut addrinfo) { let mut ai = res; while !ai.is_null() { let bai = Box::from_raw(ai); if !bai.ai_canonname.is_null() { CString::from_raw(bai.ai_canonname); } if !bai.ai_addr.is_null() { if bai.ai_addrlen == mem::size_of::<sockaddr_in>() { Box::from_raw(bai.ai_addr as *mut sockaddr_in); } else if bai.ai_addrlen == mem::size_of::<sockaddr_in6>() { Box::from_raw(bai.ai_addr as *mut sockaddr_in6); } else { eprintln!("freeaddrinfo: unknown ai_addrlen {}", bai.ai_addrlen); } } ai = bai.ai_next; } } #[no_mangle] pub extern "C" fn
(errcode: c_int) -> *const c_char { match errcode { EAI_BADFLAGS => c_str!("Invalid flags"), EAI_NONAME => c_str!("Name does not resolve"), EAI_AGAIN => c_str!("Try again"), EAI_FAIL => c_str!("Non-recoverable error"), EAI_NODATA => c_str!("Unknown error"), EAI_FAMILY => c_str!("Unrecognized address family or invalid length"), EAI_SOCKTYPE => c_str!("Unrecognized socket type"), EAI_SERVICE => c_str!("Unrecognized service"), EAI_ADDRFAMILY => c_str!("Address family for name not supported"), EAI_MEMORY => c_str!("Out of memory"), EAI_SYSTEM => c_str!("System error"), EAI_OVERFLOW => c_str!("Overflow"), _ => c_str!("Unknown error"), } .as_ptr() }
gai_strerror
isr.rs
#[doc = "Reader of register ISR"] pub type R = crate::R<u32, super::ISR>; #[doc = "Reader of field `CE`"] pub type CE_R = crate::R<bool, bool>; #[doc = "Reader of field `SCO`"] pub type SCO_R = crate::R<bool, bool>; #[doc = "Reader of field `MASK`"] pub type MASK_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Comparison Edge (cleared on read)"] #[inline(always)] pub fn ce(&self) -> CE_R { CE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Synchronized Comparator Output"] #[inline(always)] pub fn sco(&self) -> SCO_R { SCO_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 31 - Flag Mask"] #[inline(always)] pub fn
(&self) -> MASK_R { MASK_R::new(((self.bits >> 31) & 0x01) != 0) } }
mask
no-comments.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Foo { pub s: ::std::os::raw::c_int, } #[test] fn bindgen_test_layout_Foo() {
concat!("Size of: ", stringify!(Foo)) ); assert_eq!( ::std::mem::align_of::<Foo>(), 4usize, concat!("Alignment of ", stringify!(Foo)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<Foo>())).s as *const _ as usize }, 0usize, concat!("Offset of field: ", stringify!(Foo), "::", stringify!(s)) ); }
assert_eq!( ::std::mem::size_of::<Foo>(), 4usize,
api.go
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package workdocs import ( "fmt" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/internal/awsutil" "github.com/aws/aws-sdk-go-v2/private/protocol" "github.com/aws/aws-sdk-go-v2/private/protocol/restjson" ) const opAbortDocumentVersionUpload = "AbortDocumentVersionUpload" // AbortDocumentVersionUploadRequest is a API request type for the AbortDocumentVersionUpload API operation. type AbortDocumentVersionUploadRequest struct { *aws.Request Input *AbortDocumentVersionUploadInput Copy func(*AbortDocumentVersionUploadInput) AbortDocumentVersionUploadRequest } // Send marshals and sends the AbortDocumentVersionUpload API request. func (r AbortDocumentVersionUploadRequest) Send() (*AbortDocumentVersionUploadOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*AbortDocumentVersionUploadOutput), nil } // AbortDocumentVersionUploadRequest returns a request value for making API operation for // Amazon WorkDocs. // // Aborts the upload of the specified document version that was previously initiated // by InitiateDocumentVersionUpload. The client should make this call only when // it no longer intends to upload the document version, or fails to do so. // // // Example sending a request using the AbortDocumentVersionUploadRequest method. // req := client.AbortDocumentVersionUploadRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/AbortDocumentVersionUpload func (c *WorkDocs) AbortDocumentVersionUploadRequest(input *AbortDocumentVersionUploadInput) AbortDocumentVersionUploadRequest { op := &aws.Operation{ Name: opAbortDocumentVersionUpload, HTTPMethod: "DELETE", HTTPPath: "/api/v1/documents/{DocumentId}/versions/{VersionId}", } if input == nil { input = &AbortDocumentVersionUploadInput{} } output := &AbortDocumentVersionUploadOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return AbortDocumentVersionUploadRequest{Request: req, Input: input, Copy: c.AbortDocumentVersionUploadRequest} } const opActivateUser = "ActivateUser" // ActivateUserRequest is a API request type for the ActivateUser API operation. type ActivateUserRequest struct { *aws.Request Input *ActivateUserInput Copy func(*ActivateUserInput) ActivateUserRequest } // Send marshals and sends the ActivateUser API request. func (r ActivateUserRequest) Send() (*ActivateUserOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*ActivateUserOutput), nil } // ActivateUserRequest returns a request value for making API operation for // Amazon WorkDocs. // // Activates the specified user. Only active users can access Amazon WorkDocs. // // // Example sending a request using the ActivateUserRequest method. // req := client.ActivateUserRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/ActivateUser func (c *WorkDocs) ActivateUserRequest(input *ActivateUserInput) ActivateUserRequest { op := &aws.Operation{ Name: opActivateUser, HTTPMethod: "POST", HTTPPath: "/api/v1/users/{UserId}/activation", } if input == nil { input = &ActivateUserInput{} } output := &ActivateUserOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return ActivateUserRequest{Request: req, Input: input, Copy: c.ActivateUserRequest} } const opAddResourcePermissions = "AddResourcePermissions" // AddResourcePermissionsRequest is a API request type for the AddResourcePermissions API operation. type AddResourcePermissionsRequest struct { *aws.Request Input *AddResourcePermissionsInput Copy func(*AddResourcePermissionsInput) AddResourcePermissionsRequest } // Send marshals and sends the AddResourcePermissions API request. func (r AddResourcePermissionsRequest) Send() (*AddResourcePermissionsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*AddResourcePermissionsOutput), nil } // AddResourcePermissionsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Creates a set of permissions for the specified folder or document. The resource // permissions are overwritten if the principals already have different permissions. // // // Example sending a request using the AddResourcePermissionsRequest method. // req := client.AddResourcePermissionsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/AddResourcePermissions func (c *WorkDocs) AddResourcePermissionsRequest(input *AddResourcePermissionsInput) AddResourcePermissionsRequest { op := &aws.Operation{ Name: opAddResourcePermissions, HTTPMethod: "POST", HTTPPath: "/api/v1/resources/{ResourceId}/permissions", } if input == nil { input = &AddResourcePermissionsInput{} } output := &AddResourcePermissionsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return AddResourcePermissionsRequest{Request: req, Input: input, Copy: c.AddResourcePermissionsRequest} } const opCreateComment = "CreateComment" // CreateCommentRequest is a API request type for the CreateComment API operation. type CreateCommentRequest struct { *aws.Request Input *CreateCommentInput Copy func(*CreateCommentInput) CreateCommentRequest } // Send marshals and sends the CreateComment API request. func (r CreateCommentRequest) Send() (*CreateCommentOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*CreateCommentOutput), nil } // CreateCommentRequest returns a request value for making API operation for // Amazon WorkDocs. // // Adds a new comment to the specified document version. // // // Example sending a request using the CreateCommentRequest method. // req := client.CreateCommentRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateComment func (c *WorkDocs) CreateCommentRequest(input *CreateCommentInput) CreateCommentRequest { op := &aws.Operation{ Name: opCreateComment, HTTPMethod: "POST", HTTPPath: "/api/v1/documents/{DocumentId}/versions/{VersionId}/comment", } if input == nil { input = &CreateCommentInput{} } output := &CreateCommentOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return CreateCommentRequest{Request: req, Input: input, Copy: c.CreateCommentRequest} } const opCreateCustomMetadata = "CreateCustomMetadata" // CreateCustomMetadataRequest is a API request type for the CreateCustomMetadata API operation. type CreateCustomMetadataRequest struct { *aws.Request Input *CreateCustomMetadataInput Copy func(*CreateCustomMetadataInput) CreateCustomMetadataRequest } // Send marshals and sends the CreateCustomMetadata API request. func (r CreateCustomMetadataRequest) Send() (*CreateCustomMetadataOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*CreateCustomMetadataOutput), nil } // CreateCustomMetadataRequest returns a request value for making API operation for // Amazon WorkDocs. // // Adds one or more custom properties to the specified resource (a folder, document, // or version). // // // Example sending a request using the CreateCustomMetadataRequest method. // req := client.CreateCustomMetadataRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateCustomMetadata func (c *WorkDocs) CreateCustomMetadataRequest(input *CreateCustomMetadataInput) CreateCustomMetadataRequest { op := &aws.Operation{ Name: opCreateCustomMetadata, HTTPMethod: "PUT", HTTPPath: "/api/v1/resources/{ResourceId}/customMetadata", } if input == nil { input = &CreateCustomMetadataInput{} } output := &CreateCustomMetadataOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return CreateCustomMetadataRequest{Request: req, Input: input, Copy: c.CreateCustomMetadataRequest} } const opCreateFolder = "CreateFolder" // CreateFolderRequest is a API request type for the CreateFolder API operation. type CreateFolderRequest struct { *aws.Request Input *CreateFolderInput Copy func(*CreateFolderInput) CreateFolderRequest } // Send marshals and sends the CreateFolder API request. func (r CreateFolderRequest) Send() (*CreateFolderOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*CreateFolderOutput), nil } // CreateFolderRequest returns a request value for making API operation for // Amazon WorkDocs. // // Creates a folder with the specified name and parent folder. // // // Example sending a request using the CreateFolderRequest method. // req := client.CreateFolderRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateFolder func (c *WorkDocs) CreateFolderRequest(input *CreateFolderInput) CreateFolderRequest { op := &aws.Operation{ Name: opCreateFolder, HTTPMethod: "POST", HTTPPath: "/api/v1/folders", } if input == nil { input = &CreateFolderInput{} } output := &CreateFolderOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return CreateFolderRequest{Request: req, Input: input, Copy: c.CreateFolderRequest} } const opCreateLabels = "CreateLabels" // CreateLabelsRequest is a API request type for the CreateLabels API operation. type CreateLabelsRequest struct { *aws.Request Input *CreateLabelsInput Copy func(*CreateLabelsInput) CreateLabelsRequest } // Send marshals and sends the CreateLabels API request. func (r CreateLabelsRequest) Send() (*CreateLabelsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*CreateLabelsOutput), nil } // CreateLabelsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Adds the specified list of labels to the given resource (a document or folder) // // // Example sending a request using the CreateLabelsRequest method. // req := client.CreateLabelsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateLabels func (c *WorkDocs) CreateLabelsRequest(input *CreateLabelsInput) CreateLabelsRequest { op := &aws.Operation{ Name: opCreateLabels, HTTPMethod: "PUT", HTTPPath: "/api/v1/resources/{ResourceId}/labels", } if input == nil { input = &CreateLabelsInput{} } output := &CreateLabelsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return CreateLabelsRequest{Request: req, Input: input, Copy: c.CreateLabelsRequest} } const opCreateNotificationSubscription = "CreateNotificationSubscription" // CreateNotificationSubscriptionRequest is a API request type for the CreateNotificationSubscription API operation. type CreateNotificationSubscriptionRequest struct { *aws.Request Input *CreateNotificationSubscriptionInput Copy func(*CreateNotificationSubscriptionInput) CreateNotificationSubscriptionRequest } // Send marshals and sends the CreateNotificationSubscription API request. func (r CreateNotificationSubscriptionRequest) Send() (*CreateNotificationSubscriptionOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*CreateNotificationSubscriptionOutput), nil } // CreateNotificationSubscriptionRequest returns a request value for making API operation for // Amazon WorkDocs. // // Configure Amazon WorkDocs to use Amazon SNS notifications. The endpoint receives // a confirmation message, and must confirm the subscription. // // For more information, see Subscribe to Notifications (http://docs.aws.amazon.com/workdocs/latest/developerguide/subscribe-notifications.html) // in the Amazon WorkDocs Developer Guide. // // // Example sending a request using the CreateNotificationSubscriptionRequest method. // req := client.CreateNotificationSubscriptionRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateNotificationSubscription func (c *WorkDocs) CreateNotificationSubscriptionRequest(input *CreateNotificationSubscriptionInput) CreateNotificationSubscriptionRequest { op := &aws.Operation{ Name: opCreateNotificationSubscription, HTTPMethod: "POST", HTTPPath: "/api/v1/organizations/{OrganizationId}/subscriptions", } if input == nil { input = &CreateNotificationSubscriptionInput{} } output := &CreateNotificationSubscriptionOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return CreateNotificationSubscriptionRequest{Request: req, Input: input, Copy: c.CreateNotificationSubscriptionRequest} } const opCreateUser = "CreateUser" // CreateUserRequest is a API request type for the CreateUser API operation. type CreateUserRequest struct { *aws.Request Input *CreateUserInput Copy func(*CreateUserInput) CreateUserRequest } // Send marshals and sends the CreateUser API request. func (r CreateUserRequest) Send() (*CreateUserOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*CreateUserOutput), nil } // CreateUserRequest returns a request value for making API operation for // Amazon WorkDocs. // // Creates a user in a Simple AD or Microsoft AD directory. The status of a // newly created user is "ACTIVE". New users can access Amazon WorkDocs. // // // Example sending a request using the CreateUserRequest method. // req := client.CreateUserRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateUser func (c *WorkDocs) CreateUserRequest(input *CreateUserInput) CreateUserRequest { op := &aws.Operation{ Name: opCreateUser, HTTPMethod: "POST", HTTPPath: "/api/v1/users", } if input == nil { input = &CreateUserInput{} } output := &CreateUserOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return CreateUserRequest{Request: req, Input: input, Copy: c.CreateUserRequest} } const opDeactivateUser = "DeactivateUser" // DeactivateUserRequest is a API request type for the DeactivateUser API operation. type DeactivateUserRequest struct { *aws.Request Input *DeactivateUserInput Copy func(*DeactivateUserInput) DeactivateUserRequest } // Send marshals and sends the DeactivateUser API request. func (r DeactivateUserRequest) Send() (*DeactivateUserOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeactivateUserOutput), nil } // DeactivateUserRequest returns a request value for making API operation for // Amazon WorkDocs. // // Deactivates the specified user, which revokes the user's access to Amazon // WorkDocs. // // // Example sending a request using the DeactivateUserRequest method. // req := client.DeactivateUserRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeactivateUser func (c *WorkDocs) DeactivateUserRequest(input *DeactivateUserInput) DeactivateUserRequest { op := &aws.Operation{ Name: opDeactivateUser, HTTPMethod: "DELETE", HTTPPath: "/api/v1/users/{UserId}/activation", } if input == nil { input = &DeactivateUserInput{} } output := &DeactivateUserOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return DeactivateUserRequest{Request: req, Input: input, Copy: c.DeactivateUserRequest} } const opDeleteComment = "DeleteComment" // DeleteCommentRequest is a API request type for the DeleteComment API operation. type DeleteCommentRequest struct { *aws.Request Input *DeleteCommentInput Copy func(*DeleteCommentInput) DeleteCommentRequest } // Send marshals and sends the DeleteComment API request. func (r DeleteCommentRequest) Send() (*DeleteCommentOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteCommentOutput), nil } // DeleteCommentRequest returns a request value for making API operation for // Amazon WorkDocs. // // Deletes the specified comment from the document version. // // // Example sending a request using the DeleteCommentRequest method. // req := client.DeleteCommentRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteComment func (c *WorkDocs) DeleteCommentRequest(input *DeleteCommentInput) DeleteCommentRequest { op := &aws.Operation{ Name: opDeleteComment, HTTPMethod: "DELETE", HTTPPath: "/api/v1/documents/{DocumentId}/versions/{VersionId}/comment/{CommentId}", } if input == nil { input = &DeleteCommentInput{} } output := &DeleteCommentOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return DeleteCommentRequest{Request: req, Input: input, Copy: c.DeleteCommentRequest} } const opDeleteCustomMetadata = "DeleteCustomMetadata" // DeleteCustomMetadataRequest is a API request type for the DeleteCustomMetadata API operation. type DeleteCustomMetadataRequest struct { *aws.Request Input *DeleteCustomMetadataInput Copy func(*DeleteCustomMetadataInput) DeleteCustomMetadataRequest } // Send marshals and sends the DeleteCustomMetadata API request. func (r DeleteCustomMetadataRequest) Send() (*DeleteCustomMetadataOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteCustomMetadataOutput), nil } // DeleteCustomMetadataRequest returns a request value for making API operation for // Amazon WorkDocs. // // Deletes custom metadata from the specified resource. // // // Example sending a request using the DeleteCustomMetadataRequest method. // req := client.DeleteCustomMetadataRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteCustomMetadata func (c *WorkDocs) DeleteCustomMetadataRequest(input *DeleteCustomMetadataInput) DeleteCustomMetadataRequest { op := &aws.Operation{ Name: opDeleteCustomMetadata, HTTPMethod: "DELETE", HTTPPath: "/api/v1/resources/{ResourceId}/customMetadata", } if input == nil { input = &DeleteCustomMetadataInput{} } output := &DeleteCustomMetadataOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DeleteCustomMetadataRequest{Request: req, Input: input, Copy: c.DeleteCustomMetadataRequest} } const opDeleteDocument = "DeleteDocument" // DeleteDocumentRequest is a API request type for the DeleteDocument API operation. type DeleteDocumentRequest struct { *aws.Request Input *DeleteDocumentInput Copy func(*DeleteDocumentInput) DeleteDocumentRequest } // Send marshals and sends the DeleteDocument API request. func (r DeleteDocumentRequest) Send() (*DeleteDocumentOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteDocumentOutput), nil } // DeleteDocumentRequest returns a request value for making API operation for // Amazon WorkDocs. // // Permanently deletes the specified document and its associated metadata. // // // Example sending a request using the DeleteDocumentRequest method. // req := client.DeleteDocumentRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteDocument func (c *WorkDocs) DeleteDocumentRequest(input *DeleteDocumentInput) DeleteDocumentRequest { op := &aws.Operation{ Name: opDeleteDocument, HTTPMethod: "DELETE", HTTPPath: "/api/v1/documents/{DocumentId}", } if input == nil { input = &DeleteDocumentInput{} } output := &DeleteDocumentOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return DeleteDocumentRequest{Request: req, Input: input, Copy: c.DeleteDocumentRequest} } const opDeleteFolder = "DeleteFolder" // DeleteFolderRequest is a API request type for the DeleteFolder API operation. type DeleteFolderRequest struct { *aws.Request Input *DeleteFolderInput Copy func(*DeleteFolderInput) DeleteFolderRequest } // Send marshals and sends the DeleteFolder API request. func (r DeleteFolderRequest) Send() (*DeleteFolderOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteFolderOutput), nil } // DeleteFolderRequest returns a request value for making API operation for // Amazon WorkDocs. // // Permanently deletes the specified folder and its contents. // // // Example sending a request using the DeleteFolderRequest method. // req := client.DeleteFolderRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteFolder func (c *WorkDocs) DeleteFolderRequest(input *DeleteFolderInput) DeleteFolderRequest { op := &aws.Operation{ Name: opDeleteFolder, HTTPMethod: "DELETE", HTTPPath: "/api/v1/folders/{FolderId}", } if input == nil { input = &DeleteFolderInput{} } output := &DeleteFolderOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return DeleteFolderRequest{Request: req, Input: input, Copy: c.DeleteFolderRequest} } const opDeleteFolderContents = "DeleteFolderContents" // DeleteFolderContentsRequest is a API request type for the DeleteFolderContents API operation. type DeleteFolderContentsRequest struct { *aws.Request Input *DeleteFolderContentsInput Copy func(*DeleteFolderContentsInput) DeleteFolderContentsRequest } // Send marshals and sends the DeleteFolderContents API request. func (r DeleteFolderContentsRequest) Send() (*DeleteFolderContentsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteFolderContentsOutput), nil } // DeleteFolderContentsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Deletes the contents of the specified folder. // // // Example sending a request using the DeleteFolderContentsRequest method. // req := client.DeleteFolderContentsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteFolderContents func (c *WorkDocs) DeleteFolderContentsRequest(input *DeleteFolderContentsInput) DeleteFolderContentsRequest { op := &aws.Operation{ Name: opDeleteFolderContents, HTTPMethod: "DELETE", HTTPPath: "/api/v1/folders/{FolderId}/contents", } if input == nil { input = &DeleteFolderContentsInput{} } output := &DeleteFolderContentsOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return DeleteFolderContentsRequest{Request: req, Input: input, Copy: c.DeleteFolderContentsRequest} } const opDeleteLabels = "DeleteLabels" // DeleteLabelsRequest is a API request type for the DeleteLabels API operation. type DeleteLabelsRequest struct { *aws.Request Input *DeleteLabelsInput Copy func(*DeleteLabelsInput) DeleteLabelsRequest } // Send marshals and sends the DeleteLabels API request. func (r DeleteLabelsRequest) Send() (*DeleteLabelsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteLabelsOutput), nil } // DeleteLabelsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Deletes the specified list of labels from a resource. // // // Example sending a request using the DeleteLabelsRequest method. // req := client.DeleteLabelsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteLabels func (c *WorkDocs) DeleteLabelsRequest(input *DeleteLabelsInput) DeleteLabelsRequest { op := &aws.Operation{ Name: opDeleteLabels, HTTPMethod: "DELETE", HTTPPath: "/api/v1/resources/{ResourceId}/labels", } if input == nil { input = &DeleteLabelsInput{} } output := &DeleteLabelsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DeleteLabelsRequest{Request: req, Input: input, Copy: c.DeleteLabelsRequest} } const opDeleteNotificationSubscription = "DeleteNotificationSubscription" // DeleteNotificationSubscriptionRequest is a API request type for the DeleteNotificationSubscription API operation. type DeleteNotificationSubscriptionRequest struct { *aws.Request Input *DeleteNotificationSubscriptionInput Copy func(*DeleteNotificationSubscriptionInput) DeleteNotificationSubscriptionRequest } // Send marshals and sends the DeleteNotificationSubscription API request. func (r DeleteNotificationSubscriptionRequest) Send() (*DeleteNotificationSubscriptionOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteNotificationSubscriptionOutput), nil } // DeleteNotificationSubscriptionRequest returns a request value for making API operation for // Amazon WorkDocs. // // Deletes the specified subscription from the specified organization. // // // Example sending a request using the DeleteNotificationSubscriptionRequest method. // req := client.DeleteNotificationSubscriptionRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteNotificationSubscription func (c *WorkDocs) DeleteNotificationSubscriptionRequest(input *DeleteNotificationSubscriptionInput) DeleteNotificationSubscriptionRequest { op := &aws.Operation{ Name: opDeleteNotificationSubscription, HTTPMethod: "DELETE", HTTPPath: "/api/v1/organizations/{OrganizationId}/subscriptions/{SubscriptionId}", } if input == nil { input = &DeleteNotificationSubscriptionInput{} } output := &DeleteNotificationSubscriptionOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return DeleteNotificationSubscriptionRequest{Request: req, Input: input, Copy: c.DeleteNotificationSubscriptionRequest} } const opDeleteUser = "DeleteUser" // DeleteUserRequest is a API request type for the DeleteUser API operation. type DeleteUserRequest struct { *aws.Request Input *DeleteUserInput Copy func(*DeleteUserInput) DeleteUserRequest } // Send marshals and sends the DeleteUser API request. func (r DeleteUserRequest) Send() (*DeleteUserOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DeleteUserOutput), nil } // DeleteUserRequest returns a request value for making API operation for // Amazon WorkDocs. // // Deletes the specified user from a Simple AD or Microsoft AD directory. // // // Example sending a request using the DeleteUserRequest method. // req := client.DeleteUserRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteUser func (c *WorkDocs) DeleteUserRequest(input *DeleteUserInput) DeleteUserRequest { op := &aws.Operation{ Name: opDeleteUser, HTTPMethod: "DELETE", HTTPPath: "/api/v1/users/{UserId}", } if input == nil { input = &DeleteUserInput{} } output := &DeleteUserOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return DeleteUserRequest{Request: req, Input: input, Copy: c.DeleteUserRequest} } const opDescribeActivities = "DescribeActivities" // DescribeActivitiesRequest is a API request type for the DescribeActivities API operation. type DescribeActivitiesRequest struct { *aws.Request Input *DescribeActivitiesInput Copy func(*DescribeActivitiesInput) DescribeActivitiesRequest } // Send marshals and sends the DescribeActivities API request. func (r DescribeActivitiesRequest) Send() (*DescribeActivitiesOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeActivitiesOutput), nil } // DescribeActivitiesRequest returns a request value for making API operation for // Amazon WorkDocs. // // Describes the user activities in a specified time period. // // // Example sending a request using the DescribeActivitiesRequest method. // req := client.DescribeActivitiesRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeActivities func (c *WorkDocs) DescribeActivitiesRequest(input *DescribeActivitiesInput) DescribeActivitiesRequest { op := &aws.Operation{ Name: opDescribeActivities, HTTPMethod: "GET", HTTPPath: "/api/v1/activities", } if input == nil { input = &DescribeActivitiesInput{} } output := &DescribeActivitiesOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeActivitiesRequest{Request: req, Input: input, Copy: c.DescribeActivitiesRequest} } const opDescribeComments = "DescribeComments" // DescribeCommentsRequest is a API request type for the DescribeComments API operation. type DescribeCommentsRequest struct { *aws.Request Input *DescribeCommentsInput Copy func(*DescribeCommentsInput) DescribeCommentsRequest } // Send marshals and sends the DescribeComments API request. func (r DescribeCommentsRequest) Send() (*DescribeCommentsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeCommentsOutput), nil } // DescribeCommentsRequest returns a request value for making API operation for // Amazon WorkDocs. // // List all the comments for the specified document version. // // // Example sending a request using the DescribeCommentsRequest method. // req := client.DescribeCommentsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeComments func (c *WorkDocs) DescribeCommentsRequest(input *DescribeCommentsInput) DescribeCommentsRequest { op := &aws.Operation{ Name: opDescribeComments, HTTPMethod: "GET", HTTPPath: "/api/v1/documents/{DocumentId}/versions/{VersionId}/comments", } if input == nil { input = &DescribeCommentsInput{} } output := &DescribeCommentsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeCommentsRequest{Request: req, Input: input, Copy: c.DescribeCommentsRequest} } const opDescribeDocumentVersions = "DescribeDocumentVersions" // DescribeDocumentVersionsRequest is a API request type for the DescribeDocumentVersions API operation. type DescribeDocumentVersionsRequest struct { *aws.Request Input *DescribeDocumentVersionsInput Copy func(*DescribeDocumentVersionsInput) DescribeDocumentVersionsRequest } // Send marshals and sends the DescribeDocumentVersions API request. func (r DescribeDocumentVersionsRequest) Send() (*DescribeDocumentVersionsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeDocumentVersionsOutput), nil } // DescribeDocumentVersionsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves the document versions for the specified document. // // By default, only active versions are returned. // // // Example sending a request using the DescribeDocumentVersionsRequest method. // req := client.DescribeDocumentVersionsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeDocumentVersions func (c *WorkDocs) DescribeDocumentVersionsRequest(input *DescribeDocumentVersionsInput) DescribeDocumentVersionsRequest { op := &aws.Operation{ Name: opDescribeDocumentVersions, HTTPMethod: "GET", HTTPPath: "/api/v1/documents/{DocumentId}/versions", Paginator: &aws.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "Limit", TruncationToken: "", }, } if input == nil { input = &DescribeDocumentVersionsInput{} } output := &DescribeDocumentVersionsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeDocumentVersionsRequest{Request: req, Input: input, Copy: c.DescribeDocumentVersionsRequest} } // Paginate pages iterates over the pages of a DescribeDocumentVersionsRequest operation, // calling the Next method for each page. Using the paginators Next // method will depict whether or not there are more pages. // // Note: This operation can generate multiple requests to a service. // // // Example iterating over at most 3 pages of a DescribeDocumentVersions operation. // req := client.DescribeDocumentVersionsRequest(input) // p := req.Paginate() // for p.Next() { // page := p.CurrentPage() // } // // if err := p.Err(); err != nil { // return err // } // func (p *DescribeDocumentVersionsRequest) Paginate(opts ...aws.Option) DescribeDocumentVersionsPager { return DescribeDocumentVersionsPager{ Pager: aws.Pager{ NewRequest: func() (*aws.Request, error) { var inCpy *DescribeDocumentVersionsInput if p.Input != nil { tmp := *p.Input inCpy = &tmp } req := p.Copy(inCpy) req.ApplyOptions(opts...) return req.Request, nil }, }, } } // DescribeDocumentVersionsPager is used to paginate the request. This can be done by // calling Next and CurrentPage. type DescribeDocumentVersionsPager struct { aws.Pager } func (p *DescribeDocumentVersionsPager) CurrentPage() *DescribeDocumentVersionsOutput { return p.Pager.CurrentPage().(*DescribeDocumentVersionsOutput) } const opDescribeFolderContents = "DescribeFolderContents" // DescribeFolderContentsRequest is a API request type for the DescribeFolderContents API operation. type DescribeFolderContentsRequest struct { *aws.Request Input *DescribeFolderContentsInput Copy func(*DescribeFolderContentsInput) DescribeFolderContentsRequest } // Send marshals and sends the DescribeFolderContents API request. func (r DescribeFolderContentsRequest) Send() (*DescribeFolderContentsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeFolderContentsOutput), nil } // DescribeFolderContentsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Describes the contents of the specified folder, including its documents and // subfolders. // // By default, Amazon WorkDocs returns the first 100 active document and folder // metadata items. If there are more results, the response includes a marker // that you can use to request the next set of results. You can also request // initialized documents. // // // Example sending a request using the DescribeFolderContentsRequest method. // req := client.DescribeFolderContentsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeFolderContents func (c *WorkDocs) DescribeFolderContentsRequest(input *DescribeFolderContentsInput) DescribeFolderContentsRequest { op := &aws.Operation{ Name: opDescribeFolderContents, HTTPMethod: "GET", HTTPPath: "/api/v1/folders/{FolderId}/contents", Paginator: &aws.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "Limit", TruncationToken: "", }, } if input == nil { input = &DescribeFolderContentsInput{} } output := &DescribeFolderContentsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeFolderContentsRequest{Request: req, Input: input, Copy: c.DescribeFolderContentsRequest} } // Paginate pages iterates over the pages of a DescribeFolderContentsRequest operation, // calling the Next method for each page. Using the paginators Next // method will depict whether or not there are more pages. // // Note: This operation can generate multiple requests to a service. // // // Example iterating over at most 3 pages of a DescribeFolderContents operation. // req := client.DescribeFolderContentsRequest(input) // p := req.Paginate() // for p.Next() { // page := p.CurrentPage() // } // // if err := p.Err(); err != nil { // return err // } // func (p *DescribeFolderContentsRequest) Paginate(opts ...aws.Option) DescribeFolderContentsPager { return DescribeFolderContentsPager{ Pager: aws.Pager{ NewRequest: func() (*aws.Request, error) { var inCpy *DescribeFolderContentsInput if p.Input != nil { tmp := *p.Input inCpy = &tmp } req := p.Copy(inCpy) req.ApplyOptions(opts...) return req.Request, nil }, }, } } // DescribeFolderContentsPager is used to paginate the request. This can be done by // calling Next and CurrentPage. type DescribeFolderContentsPager struct { aws.Pager } func (p *DescribeFolderContentsPager) CurrentPage() *DescribeFolderContentsOutput { return p.Pager.CurrentPage().(*DescribeFolderContentsOutput) } const opDescribeGroups = "DescribeGroups" // DescribeGroupsRequest is a API request type for the DescribeGroups API operation. type DescribeGroupsRequest struct { *aws.Request Input *DescribeGroupsInput Copy func(*DescribeGroupsInput) DescribeGroupsRequest } // Send marshals and sends the DescribeGroups API request. func (r DescribeGroupsRequest) Send() (*DescribeGroupsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeGroupsOutput), nil } // DescribeGroupsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Describes the groups specified by the query. Groups are defined by the underlying // Active Directory. // // // Example sending a request using the DescribeGroupsRequest method. // req := client.DescribeGroupsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeGroups func (c *WorkDocs) DescribeGroupsRequest(input *DescribeGroupsInput) DescribeGroupsRequest { op := &aws.Operation{ Name: opDescribeGroups, HTTPMethod: "GET", HTTPPath: "/api/v1/groups", } if input == nil { input = &DescribeGroupsInput{} } output := &DescribeGroupsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeGroupsRequest{Request: req, Input: input, Copy: c.DescribeGroupsRequest} } const opDescribeNotificationSubscriptions = "DescribeNotificationSubscriptions" // DescribeNotificationSubscriptionsRequest is a API request type for the DescribeNotificationSubscriptions API operation. type DescribeNotificationSubscriptionsRequest struct { *aws.Request Input *DescribeNotificationSubscriptionsInput Copy func(*DescribeNotificationSubscriptionsInput) DescribeNotificationSubscriptionsRequest } // Send marshals and sends the DescribeNotificationSubscriptions API request. func (r DescribeNotificationSubscriptionsRequest) Send() (*DescribeNotificationSubscriptionsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeNotificationSubscriptionsOutput), nil } // DescribeNotificationSubscriptionsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Lists the specified notification subscriptions. // // // Example sending a request using the DescribeNotificationSubscriptionsRequest method. // req := client.DescribeNotificationSubscriptionsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeNotificationSubscriptions func (c *WorkDocs) DescribeNotificationSubscriptionsRequest(input *DescribeNotificationSubscriptionsInput) DescribeNotificationSubscriptionsRequest { op := &aws.Operation{ Name: opDescribeNotificationSubscriptions, HTTPMethod: "GET", HTTPPath: "/api/v1/organizations/{OrganizationId}/subscriptions", } if input == nil { input = &DescribeNotificationSubscriptionsInput{} } output := &DescribeNotificationSubscriptionsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeNotificationSubscriptionsRequest{Request: req, Input: input, Copy: c.DescribeNotificationSubscriptionsRequest} } const opDescribeResourcePermissions = "DescribeResourcePermissions" // DescribeResourcePermissionsRequest is a API request type for the DescribeResourcePermissions API operation. type DescribeResourcePermissionsRequest struct { *aws.Request Input *DescribeResourcePermissionsInput Copy func(*DescribeResourcePermissionsInput) DescribeResourcePermissionsRequest } // Send marshals and sends the DescribeResourcePermissions API request. func (r DescribeResourcePermissionsRequest) Send() (*DescribeResourcePermissionsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeResourcePermissionsOutput), nil } // DescribeResourcePermissionsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Describes the permissions of a specified resource. // // // Example sending a request using the DescribeResourcePermissionsRequest method. // req := client.DescribeResourcePermissionsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeResourcePermissions func (c *WorkDocs) DescribeResourcePermissionsRequest(input *DescribeResourcePermissionsInput) DescribeResourcePermissionsRequest { op := &aws.Operation{ Name: opDescribeResourcePermissions, HTTPMethod: "GET", HTTPPath: "/api/v1/resources/{ResourceId}/permissions", } if input == nil { input = &DescribeResourcePermissionsInput{} } output := &DescribeResourcePermissionsOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeResourcePermissionsRequest{Request: req, Input: input, Copy: c.DescribeResourcePermissionsRequest} } const opDescribeRootFolders = "DescribeRootFolders" // DescribeRootFoldersRequest is a API request type for the DescribeRootFolders API operation. type DescribeRootFoldersRequest struct { *aws.Request Input *DescribeRootFoldersInput Copy func(*DescribeRootFoldersInput) DescribeRootFoldersRequest } // Send marshals and sends the DescribeRootFolders API request. func (r DescribeRootFoldersRequest) Send() (*DescribeRootFoldersOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeRootFoldersOutput), nil } // DescribeRootFoldersRequest returns a request value for making API operation for // Amazon WorkDocs. // // Describes the current user's special folders; the RootFolder and the RecycleBin. // RootFolder is the root of user's files and folders and RecycleBin is the // root of recycled items. This is not a valid action for SigV4 (administrative // API) clients. // // This action requires an authentication token. To get an authentication token, // register an application with Amazon WorkDocs. For more information, see Authentication // and Access Control for User Applications (http://docs.aws.amazon.com/workdocs/latest/developerguide/wd-auth-user.html) // in the Amazon WorkDocs Developer Guide. // // // Example sending a request using the DescribeRootFoldersRequest method. // req := client.DescribeRootFoldersRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeRootFolders func (c *WorkDocs) DescribeRootFoldersRequest(input *DescribeRootFoldersInput) DescribeRootFoldersRequest { op := &aws.Operation{ Name: opDescribeRootFolders, HTTPMethod: "GET", HTTPPath: "/api/v1/me/root", } if input == nil { input = &DescribeRootFoldersInput{} } output := &DescribeRootFoldersOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeRootFoldersRequest{Request: req, Input: input, Copy: c.DescribeRootFoldersRequest} } const opDescribeUsers = "DescribeUsers" // DescribeUsersRequest is a API request type for the DescribeUsers API operation. type DescribeUsersRequest struct { *aws.Request Input *DescribeUsersInput Copy func(*DescribeUsersInput) DescribeUsersRequest } // Send marshals and sends the DescribeUsers API request. func (r DescribeUsersRequest) Send() (*DescribeUsersOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*DescribeUsersOutput), nil } // DescribeUsersRequest returns a request value for making API operation for // Amazon WorkDocs. // // Describes the specified users. You can describe all users or filter the results // (for example, by status or organization). // // By default, Amazon WorkDocs returns the first 24 active or pending users. // If there are more results, the response includes a marker that you can use // to request the next set of results. // // // Example sending a request using the DescribeUsersRequest method. // req := client.DescribeUsersRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeUsers func (c *WorkDocs) DescribeUsersRequest(input *DescribeUsersInput) DescribeUsersRequest { op := &aws.Operation{ Name: opDescribeUsers, HTTPMethod: "GET", HTTPPath: "/api/v1/users", Paginator: &aws.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"Marker"}, LimitToken: "Limit", TruncationToken: "", }, } if input == nil { input = &DescribeUsersInput{} } output := &DescribeUsersOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return DescribeUsersRequest{Request: req, Input: input, Copy: c.DescribeUsersRequest} } // Paginate pages iterates over the pages of a DescribeUsersRequest operation, // calling the Next method for each page. Using the paginators Next // method will depict whether or not there are more pages. // // Note: This operation can generate multiple requests to a service. // // // Example iterating over at most 3 pages of a DescribeUsers operation. // req := client.DescribeUsersRequest(input) // p := req.Paginate() // for p.Next() { // page := p.CurrentPage() // } // // if err := p.Err(); err != nil { // return err // } // func (p *DescribeUsersRequest) Paginate(opts ...aws.Option) DescribeUsersPager { return DescribeUsersPager{ Pager: aws.Pager{ NewRequest: func() (*aws.Request, error) { var inCpy *DescribeUsersInput if p.Input != nil { tmp := *p.Input inCpy = &tmp } req := p.Copy(inCpy) req.ApplyOptions(opts...) return req.Request, nil }, }, } } // DescribeUsersPager is used to paginate the request. This can be done by // calling Next and CurrentPage. type DescribeUsersPager struct { aws.Pager } func (p *DescribeUsersPager) CurrentPage() *DescribeUsersOutput { return p.Pager.CurrentPage().(*DescribeUsersOutput) } const opGetCurrentUser = "GetCurrentUser" // GetCurrentUserRequest is a API request type for the GetCurrentUser API operation. type GetCurrentUserRequest struct { *aws.Request Input *GetCurrentUserInput Copy func(*GetCurrentUserInput) GetCurrentUserRequest } // Send marshals and sends the GetCurrentUser API request. func (r GetCurrentUserRequest) Send() (*GetCurrentUserOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*GetCurrentUserOutput), nil } // GetCurrentUserRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves details of the current user for whom the authentication token was // generated. This is not a valid action for SigV4 (administrative API) clients. // // // Example sending a request using the GetCurrentUserRequest method. // req := client.GetCurrentUserRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetCurrentUser func (c *WorkDocs) GetCurrentUserRequest(input *GetCurrentUserInput) GetCurrentUserRequest { op := &aws.Operation{ Name: opGetCurrentUser, HTTPMethod: "GET", HTTPPath: "/api/v1/me", } if input == nil { input = &GetCurrentUserInput{} } output := &GetCurrentUserOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return GetCurrentUserRequest{Request: req, Input: input, Copy: c.GetCurrentUserRequest} } const opGetDocument = "GetDocument" // GetDocumentRequest is a API request type for the GetDocument API operation. type GetDocumentRequest struct { *aws.Request Input *GetDocumentInput Copy func(*GetDocumentInput) GetDocumentRequest } // Send marshals and sends the GetDocument API request. func (r GetDocumentRequest) Send() (*GetDocumentOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*GetDocumentOutput), nil } // GetDocumentRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves details of a document. // // // Example sending a request using the GetDocumentRequest method. // req := client.GetDocumentRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocument func (c *WorkDocs) GetDocumentRequest(input *GetDocumentInput) GetDocumentRequest { op := &aws.Operation{ Name: opGetDocument, HTTPMethod: "GET", HTTPPath: "/api/v1/documents/{DocumentId}", } if input == nil { input = &GetDocumentInput{} } output := &GetDocumentOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return GetDocumentRequest{Request: req, Input: input, Copy: c.GetDocumentRequest} } const opGetDocumentPath = "GetDocumentPath" // GetDocumentPathRequest is a API request type for the GetDocumentPath API operation. type GetDocumentPathRequest struct { *aws.Request Input *GetDocumentPathInput Copy func(*GetDocumentPathInput) GetDocumentPathRequest } // Send marshals and sends the GetDocumentPath API request. func (r GetDocumentPathRequest) Send() (*GetDocumentPathOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*GetDocumentPathOutput), nil } // GetDocumentPathRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves the path information (the hierarchy from the root folder) for the // requested document. // // By default, Amazon WorkDocs returns a maximum of 100 levels upwards from // the requested document and only includes the IDs of the parent folders in // the path. You can limit the maximum number of levels. You can also request // the names of the parent folders. // // // Example sending a request using the GetDocumentPathRequest method. // req := client.GetDocumentPathRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentPath func (c *WorkDocs) GetDocumentPathRequest(input *GetDocumentPathInput) GetDocumentPathRequest { op := &aws.Operation{ Name: opGetDocumentPath, HTTPMethod: "GET", HTTPPath: "/api/v1/documents/{DocumentId}/path", } if input == nil { input = &GetDocumentPathInput{} } output := &GetDocumentPathOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return GetDocumentPathRequest{Request: req, Input: input, Copy: c.GetDocumentPathRequest} } const opGetDocumentVersion = "GetDocumentVersion" // GetDocumentVersionRequest is a API request type for the GetDocumentVersion API operation. type GetDocumentVersionRequest struct { *aws.Request Input *GetDocumentVersionInput Copy func(*GetDocumentVersionInput) GetDocumentVersionRequest } // Send marshals and sends the GetDocumentVersion API request. func (r GetDocumentVersionRequest) Send() (*GetDocumentVersionOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*GetDocumentVersionOutput), nil } // GetDocumentVersionRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves version metadata for the specified document. // // // Example sending a request using the GetDocumentVersionRequest method. // req := client.GetDocumentVersionRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentVersion func (c *WorkDocs) GetDocumentVersionRequest(input *GetDocumentVersionInput) GetDocumentVersionRequest { op := &aws.Operation{ Name: opGetDocumentVersion, HTTPMethod: "GET", HTTPPath: "/api/v1/documents/{DocumentId}/versions/{VersionId}", } if input == nil { input = &GetDocumentVersionInput{} } output := &GetDocumentVersionOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return GetDocumentVersionRequest{Request: req, Input: input, Copy: c.GetDocumentVersionRequest} } const opGetFolder = "GetFolder" // GetFolderRequest is a API request type for the GetFolder API operation. type GetFolderRequest struct { *aws.Request Input *GetFolderInput Copy func(*GetFolderInput) GetFolderRequest } // Send marshals and sends the GetFolder API request. func (r GetFolderRequest) Send() (*GetFolderOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*GetFolderOutput), nil } // GetFolderRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves the metadata of the specified folder. // // // Example sending a request using the GetFolderRequest method. // req := client.GetFolderRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetFolder func (c *WorkDocs) GetFolderRequest(input *GetFolderInput) GetFolderRequest { op := &aws.Operation{ Name: opGetFolder, HTTPMethod: "GET", HTTPPath: "/api/v1/folders/{FolderId}", } if input == nil { input = &GetFolderInput{} } output := &GetFolderOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return GetFolderRequest{Request: req, Input: input, Copy: c.GetFolderRequest} } const opGetFolderPath = "GetFolderPath" // GetFolderPathRequest is a API request type for the GetFolderPath API operation. type GetFolderPathRequest struct { *aws.Request Input *GetFolderPathInput Copy func(*GetFolderPathInput) GetFolderPathRequest } // Send marshals and sends the GetFolderPath API request. func (r GetFolderPathRequest) Send() (*GetFolderPathOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*GetFolderPathOutput), nil } // GetFolderPathRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves the path information (the hierarchy from the root folder) for the // specified folder. // // By default, Amazon WorkDocs returns a maximum of 100 levels upwards from // the requested folder and only includes the IDs of the parent folders in the // path. You can limit the maximum number of levels. You can also request the // parent folder names. // // // Example sending a request using the GetFolderPathRequest method. // req := client.GetFolderPathRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetFolderPath func (c *WorkDocs) GetFolderPathRequest(input *GetFolderPathInput) GetFolderPathRequest { op := &aws.Operation{ Name: opGetFolderPath, HTTPMethod: "GET", HTTPPath: "/api/v1/folders/{FolderId}/path", } if input == nil { input = &GetFolderPathInput{} } output := &GetFolderPathOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return GetFolderPathRequest{Request: req, Input: input, Copy: c.GetFolderPathRequest} } const opGetResources = "GetResources" // GetResourcesRequest is a API request type for the GetResources API operation. type GetResourcesRequest struct { *aws.Request Input *GetResourcesInput Copy func(*GetResourcesInput) GetResourcesRequest } // Send marshals and sends the GetResources API request. func (r GetResourcesRequest) Send() (*GetResourcesOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*GetResourcesOutput), nil } // GetResourcesRequest returns a request value for making API operation for // Amazon WorkDocs. // // Retrieves a collection of resources, including folders and documents. The // only CollectionType supported is SHARED_WITH_ME. // // // Example sending a request using the GetResourcesRequest method. // req := client.GetResourcesRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetResources func (c *WorkDocs) GetResourcesRequest(input *GetResourcesInput) GetResourcesRequest { op := &aws.Operation{ Name: opGetResources, HTTPMethod: "GET", HTTPPath: "/api/v1/resources", } if input == nil { input = &GetResourcesInput{} } output := &GetResourcesOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return GetResourcesRequest{Request: req, Input: input, Copy: c.GetResourcesRequest} } const opInitiateDocumentVersionUpload = "InitiateDocumentVersionUpload" // InitiateDocumentVersionUploadRequest is a API request type for the InitiateDocumentVersionUpload API operation. type InitiateDocumentVersionUploadRequest struct { *aws.Request Input *InitiateDocumentVersionUploadInput Copy func(*InitiateDocumentVersionUploadInput) InitiateDocumentVersionUploadRequest } // Send marshals and sends the InitiateDocumentVersionUpload API request. func (r InitiateDocumentVersionUploadRequest) Send() (*InitiateDocumentVersionUploadOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*InitiateDocumentVersionUploadOutput), nil } // InitiateDocumentVersionUploadRequest returns a request value for making API operation for // Amazon WorkDocs. // // Creates a new document object and version object. // // The client specifies the parent folder ID and name of the document to upload. // The ID is optionally specified when creating a new version of an existing // document. This is the first step to upload a document. Next, upload the document // to the URL returned from the call, and then call UpdateDocumentVersion. // // To cancel the document upload, call AbortDocumentVersionUpload. // // // Example sending a request using the InitiateDocumentVersionUploadRequest method. // req := client.InitiateDocumentVersionUploadRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/InitiateDocumentVersionUpload func (c *WorkDocs) InitiateDocumentVersionUploadRequest(input *InitiateDocumentVersionUploadInput) InitiateDocumentVersionUploadRequest { op := &aws.Operation{ Name: opInitiateDocumentVersionUpload, HTTPMethod: "POST", HTTPPath: "/api/v1/documents", } if input == nil { input = &InitiateDocumentVersionUploadInput{} } output := &InitiateDocumentVersionUploadOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return InitiateDocumentVersionUploadRequest{Request: req, Input: input, Copy: c.InitiateDocumentVersionUploadRequest} } const opRemoveAllResourcePermissions = "RemoveAllResourcePermissions" // RemoveAllResourcePermissionsRequest is a API request type for the RemoveAllResourcePermissions API operation. type RemoveAllResourcePermissionsRequest struct { *aws.Request Input *RemoveAllResourcePermissionsInput Copy func(*RemoveAllResourcePermissionsInput) RemoveAllResourcePermissionsRequest } // Send marshals and sends the RemoveAllResourcePermissions API request. func (r RemoveAllResourcePermissionsRequest) Send() (*RemoveAllResourcePermissionsOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*RemoveAllResourcePermissionsOutput), nil } // RemoveAllResourcePermissionsRequest returns a request value for making API operation for // Amazon WorkDocs. // // Removes all the permissions from the specified resource. // // // Example sending a request using the RemoveAllResourcePermissionsRequest method. // req := client.RemoveAllResourcePermissionsRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/RemoveAllResourcePermissions func (c *WorkDocs) RemoveAllResourcePermissionsRequest(input *RemoveAllResourcePermissionsInput) RemoveAllResourcePermissionsRequest { op := &aws.Operation{ Name: opRemoveAllResourcePermissions, HTTPMethod: "DELETE", HTTPPath: "/api/v1/resources/{ResourceId}/permissions", } if input == nil { input = &RemoveAllResourcePermissionsInput{} } output := &RemoveAllResourcePermissionsOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return RemoveAllResourcePermissionsRequest{Request: req, Input: input, Copy: c.RemoveAllResourcePermissionsRequest} } const opRemoveResourcePermission = "RemoveResourcePermission" // RemoveResourcePermissionRequest is a API request type for the RemoveResourcePermission API operation. type RemoveResourcePermissionRequest struct { *aws.Request Input *RemoveResourcePermissionInput Copy func(*RemoveResourcePermissionInput) RemoveResourcePermissionRequest } // Send marshals and sends the RemoveResourcePermission API request. func (r RemoveResourcePermissionRequest) Send() (*RemoveResourcePermissionOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*RemoveResourcePermissionOutput), nil } // RemoveResourcePermissionRequest returns a request value for making API operation for // Amazon WorkDocs. // // Removes the permission for the specified principal from the specified resource. // // // Example sending a request using the RemoveResourcePermissionRequest method. // req := client.RemoveResourcePermissionRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/RemoveResourcePermission func (c *WorkDocs) RemoveResourcePermissionRequest(input *RemoveResourcePermissionInput) RemoveResourcePermissionRequest { op := &aws.Operation{ Name: opRemoveResourcePermission, HTTPMethod: "DELETE", HTTPPath: "/api/v1/resources/{ResourceId}/permissions/{PrincipalId}", } if input == nil { input = &RemoveResourcePermissionInput{} } output := &RemoveResourcePermissionOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return RemoveResourcePermissionRequest{Request: req, Input: input, Copy: c.RemoveResourcePermissionRequest} } const opUpdateDocument = "UpdateDocument" // UpdateDocumentRequest is a API request type for the UpdateDocument API operation. type UpdateDocumentRequest struct { *aws.Request Input *UpdateDocumentInput Copy func(*UpdateDocumentInput) UpdateDocumentRequest } // Send marshals and sends the UpdateDocument API request. func (r UpdateDocumentRequest) Send() (*UpdateDocumentOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*UpdateDocumentOutput), nil } // UpdateDocumentRequest returns a request value for making API operation for // Amazon WorkDocs. // // Updates the specified attributes of a document. The user must have access // to both the document and its parent folder, if applicable. // // // Example sending a request using the UpdateDocumentRequest method. // req := client.UpdateDocumentRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateDocument func (c *WorkDocs) UpdateDocumentRequest(input *UpdateDocumentInput) UpdateDocumentRequest { op := &aws.Operation{ Name: opUpdateDocument, HTTPMethod: "PATCH", HTTPPath: "/api/v1/documents/{DocumentId}", } if input == nil { input = &UpdateDocumentInput{} } output := &UpdateDocumentOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return UpdateDocumentRequest{Request: req, Input: input, Copy: c.UpdateDocumentRequest} } const opUpdateDocumentVersion = "UpdateDocumentVersion" // UpdateDocumentVersionRequest is a API request type for the UpdateDocumentVersion API operation. type UpdateDocumentVersionRequest struct { *aws.Request Input *UpdateDocumentVersionInput Copy func(*UpdateDocumentVersionInput) UpdateDocumentVersionRequest } // Send marshals and sends the UpdateDocumentVersion API request. func (r UpdateDocumentVersionRequest) Send() (*UpdateDocumentVersionOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*UpdateDocumentVersionOutput), nil } // UpdateDocumentVersionRequest returns a request value for making API operation for // Amazon WorkDocs. // // Changes the status of the document version to ACTIVE. // // Amazon WorkDocs also sets its document container to ACTIVE. This is the last // step in a document upload, after the client uploads the document to an S3-presigned // URL returned by InitiateDocumentVersionUpload. // // // Example sending a request using the UpdateDocumentVersionRequest method. // req := client.UpdateDocumentVersionRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateDocumentVersion func (c *WorkDocs) UpdateDocumentVersionRequest(input *UpdateDocumentVersionInput) UpdateDocumentVersionRequest { op := &aws.Operation{ Name: opUpdateDocumentVersion, HTTPMethod: "PATCH", HTTPPath: "/api/v1/documents/{DocumentId}/versions/{VersionId}", } if input == nil { input = &UpdateDocumentVersionInput{} } output := &UpdateDocumentVersionOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return UpdateDocumentVersionRequest{Request: req, Input: input, Copy: c.UpdateDocumentVersionRequest} } const opUpdateFolder = "UpdateFolder" // UpdateFolderRequest is a API request type for the UpdateFolder API operation. type UpdateFolderRequest struct { *aws.Request Input *UpdateFolderInput Copy func(*UpdateFolderInput) UpdateFolderRequest } // Send marshals and sends the UpdateFolder API request. func (r UpdateFolderRequest) Send() (*UpdateFolderOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*UpdateFolderOutput), nil } // UpdateFolderRequest returns a request value for making API operation for // Amazon WorkDocs. // // Updates the specified attributes of the specified folder. The user must have // access to both the folder and its parent folder, if applicable. // // // Example sending a request using the UpdateFolderRequest method. // req := client.UpdateFolderRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateFolder func (c *WorkDocs) UpdateFolderRequest(input *UpdateFolderInput) UpdateFolderRequest { op := &aws.Operation{ Name: opUpdateFolder, HTTPMethod: "PATCH", HTTPPath: "/api/v1/folders/{FolderId}", } if input == nil { input = &UpdateFolderInput{} } output := &UpdateFolderOutput{} req := c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restjson.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) output.responseMetadata = aws.Response{Request: req} return UpdateFolderRequest{Request: req, Input: input, Copy: c.UpdateFolderRequest} } const opUpdateUser = "UpdateUser" // UpdateUserRequest is a API request type for the UpdateUser API operation. type UpdateUserRequest struct { *aws.Request Input *UpdateUserInput Copy func(*UpdateUserInput) UpdateUserRequest } // Send marshals and sends the UpdateUser API request. func (r UpdateUserRequest) Send() (*UpdateUserOutput, error) { err := r.Request.Send() if err != nil { return nil, err } return r.Request.Data.(*UpdateUserOutput), nil } // UpdateUserRequest returns a request value for making API operation for // Amazon WorkDocs. // // Updates the specified attributes of the specified user, and grants or revokes // administrative privileges to the Amazon WorkDocs site. // // // Example sending a request using the UpdateUserRequest method. // req := client.UpdateUserRequest(params) // resp, err := req.Send() // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateUser func (c *WorkDocs) UpdateUserRequest(input *UpdateUserInput) UpdateUserRequest { op := &aws.Operation{ Name: opUpdateUser, HTTPMethod: "PATCH", HTTPPath: "/api/v1/users/{UserId}", } if input == nil { input = &UpdateUserInput{} } output := &UpdateUserOutput{} req := c.newRequest(op, input, output) output.responseMetadata = aws.Response{Request: req} return UpdateUserRequest{Request: req, Input: input, Copy: c.UpdateUserRequest} } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/AbortDocumentVersionUploadRequest type AbortDocumentVersionUploadInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // The ID of the version. // // VersionId is a required field VersionId *string `location:"uri" locationName:"VersionId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s AbortDocumentVersionUploadInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s AbortDocumentVersionUploadInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *AbortDocumentVersionUploadInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "AbortDocumentVersionUploadInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.VersionId == nil { invalidParams.Add(aws.NewErrParamRequired("VersionId")) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s AbortDocumentVersionUploadInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "VersionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/AbortDocumentVersionUploadOutput type AbortDocumentVersionUploadOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s AbortDocumentVersionUploadOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s AbortDocumentVersionUploadOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s AbortDocumentVersionUploadOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s AbortDocumentVersionUploadOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/ActivateUserRequest type ActivateUserInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the user. // // UserId is a required field UserId *string `location:"uri" locationName:"UserId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s ActivateUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ActivateUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *ActivateUserInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "ActivateUserInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.UserId == nil { invalidParams.Add(aws.NewErrParamRequired("UserId")) } if s.UserId != nil && len(*s.UserId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s ActivateUserInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.UserId != nil { v := *s.UserId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "UserId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/ActivateUserResponse type ActivateUserOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The user information. User *User `type:"structure"` } // String returns the string representation func (s ActivateUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ActivateUserOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s ActivateUserOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s ActivateUserOutput) MarshalFields(e protocol.FieldEncoder) error { if s.User != nil { v := s.User metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "User", v, metadata) } return nil } // Describes the activity information. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/Activity type Activity struct { _ struct{} `type:"structure"` // Metadata of the commenting activity. This is an optional field and is filled // for commenting activities. CommentMetadata *CommentMetadata `type:"structure"` // The user who performed the action. Initiator *UserMetadata `type:"structure"` // Indicates whether an activity is indirect or direct. An indirect activity // results from a direct activity performed on a parent resource. For example, // sharing a parent folder (the direct activity) shares all of the subfolders // and documents within the parent folder (the indirect activity). IsIndirectActivity *bool `type:"boolean"` // The ID of the organization. OrganizationId *string `min:"1" type:"string"` // The original parent of the resource. This is an optional field and is filled // for move activities. OriginalParent *ResourceMetadata `type:"structure"` // The list of users or groups impacted by this action. This is an optional // field and is filled for the following sharing activities: DOCUMENT_SHARED, // DOCUMENT_SHARED, DOCUMENT_UNSHARED, FOLDER_SHARED, FOLDER_UNSHARED. Participants *Participants `type:"structure"` // The metadata of the resource involved in the user action. ResourceMetadata *ResourceMetadata `type:"structure"` // The timestamp when the action was performed. TimeStamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The activity type. Type ActivityType `type:"string" enum:"true"` } // String returns the string representation func (s Activity) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s Activity) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s Activity) MarshalFields(e protocol.FieldEncoder) error { if s.CommentMetadata != nil { v := s.CommentMetadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "CommentMetadata", v, metadata) } if s.Initiator != nil { v := s.Initiator metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Initiator", v, metadata) } if s.IsIndirectActivity != nil { v := *s.IsIndirectActivity metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "IsIndirectActivity", protocol.BoolValue(v), metadata) } if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "OrganizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.OriginalParent != nil { v := s.OriginalParent metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "OriginalParent", v, metadata) } if s.Participants != nil { v := s.Participants metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Participants", v, metadata) } if s.ResourceMetadata != nil { v := s.ResourceMetadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "ResourceMetadata", v, metadata) } if s.TimeStamp != nil { v := *s.TimeStamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "TimeStamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/AddResourcePermissionsRequest type AddResourcePermissionsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The notification options. NotificationOptions *NotificationOptions `type:"structure"` // The users, groups, or organization being granted permission. // // Principals is a required field Principals []SharePrincipal `type:"list" required:"true"` // The ID of the resource. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s AddResourcePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s AddResourcePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *AddResourcePermissionsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "AddResourcePermissionsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Principals == nil { invalidParams.Add(aws.NewErrParamRequired("Principals")) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if s.Principals != nil { for i, v := range s.Principals { if err := v.Validate(); err != nil { invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Principals", i), err.(aws.ErrInvalidParams)) } } } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s AddResourcePermissionsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.NotificationOptions != nil { v := s.NotificationOptions metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "NotificationOptions", v, metadata) } if len(s.Principals) > 0 { v := s.Principals metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Principals", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/AddResourcePermissionsResponse type AddResourcePermissionsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The share results. ShareResults []ShareResult `type:"list"` } // String returns the string representation func (s AddResourcePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s AddResourcePermissionsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s AddResourcePermissionsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s AddResourcePermissionsOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.ShareResults) > 0 { v := s.ShareResults metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "ShareResults", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil } // Describes a comment. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/Comment type Comment struct { _ struct{} `type:"structure"` // The ID of the comment. // // CommentId is a required field CommentId *string `min:"1" type:"string" required:"true"` // The details of the user who made the comment. Contributor *User `type:"structure"` // The time that the comment was created. CreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The ID of the parent comment. ParentId *string `min:"1" type:"string"` // If the comment is a reply to another user's comment, this field contains // the user ID of the user being replied to. RecipientId *string `min:"1" type:"string"` // The status of the comment. Status CommentStatusType `type:"string" enum:"true"` // The text of the comment. Text *string `min:"1" type:"string"` // The ID of the root comment in the thread. ThreadId *string `min:"1" type:"string"` // The visibility of the comment. Options are either PRIVATE, where the comment // is visible only to the comment author and document owner and co-owners, or // PUBLIC, where the comment is visible to document owners, co-owners, and contributors. Visibility CommentVisibilityType `type:"string" enum:"true"` } // String returns the string representation func (s Comment) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s Comment) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s Comment) MarshalFields(e protocol.FieldEncoder) error { if s.CommentId != nil { v := *s.CommentId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CommentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Contributor != nil { v := s.Contributor metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Contributor", v, metadata) } if s.CreatedTimestamp != nil { v := *s.CreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.ParentId != nil { v := *s.ParentId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.RecipientId != nil { v := *s.RecipientId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "RecipientId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Status) > 0 { v := s.Status metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Status", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.Text != nil { v := *s.Text metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Text", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ThreadId != nil { v := *s.ThreadId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ThreadId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Visibility) > 0 { v := s.Visibility metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Visibility", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Describes the metadata of a comment. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CommentMetadata type CommentMetadata struct { _ struct{} `type:"structure"` // The ID of the comment. CommentId *string `min:"1" type:"string"` // The status of the comment. CommentStatus CommentStatusType `type:"string" enum:"true"` // The user who made the comment. Contributor *User `type:"structure"` // The timestamp that the comment was created. CreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The ID of the user being replied to. RecipientId *string `min:"1" type:"string"` } // String returns the string representation func (s CommentMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CommentMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CommentMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.CommentId != nil { v := *s.CommentId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CommentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.CommentStatus) > 0 { v := s.CommentStatus metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CommentStatus", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.Contributor != nil { v := s.Contributor metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Contributor", v, metadata) } if s.CreatedTimestamp != nil { v := *s.CreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.RecipientId != nil { v := *s.RecipientId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "RecipientId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateCommentRequest type CreateCommentInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // Set this parameter to TRUE to send an email out to the document collaborators // after the comment is created. NotifyCollaborators *bool `type:"boolean"` // The ID of the parent comment. ParentId *string `min:"1" type:"string"` // The text of the comment. // // Text is a required field Text *string `min:"1" type:"string" required:"true"` // The ID of the root comment in the thread. ThreadId *string `min:"1" type:"string"` // The ID of the document version. // // VersionId is a required field VersionId *string `location:"uri" locationName:"VersionId" min:"1" type:"string" required:"true"` // The visibility of the comment. Options are either PRIVATE, where the comment // is visible only to the comment author and document owner and co-owners, or // PUBLIC, where the comment is visible to document owners, co-owners, and contributors. Visibility CommentVisibilityType `type:"string" enum:"true"` } // String returns the string representation func (s CreateCommentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateCommentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *CreateCommentInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "CreateCommentInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.ParentId != nil && len(*s.ParentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ParentId", 1)) } if s.Text == nil { invalidParams.Add(aws.NewErrParamRequired("Text")) } if s.Text != nil && len(*s.Text) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Text", 1)) } if s.ThreadId != nil && len(*s.ThreadId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ThreadId", 1)) } if s.VersionId == nil { invalidParams.Add(aws.NewErrParamRequired("VersionId")) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateCommentInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.NotifyCollaborators != nil { v := *s.NotifyCollaborators metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "NotifyCollaborators", protocol.BoolValue(v), metadata) } if s.ParentId != nil { v := *s.ParentId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Text != nil { v := *s.Text metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Text", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ThreadId != nil { v := *s.ThreadId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ThreadId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Visibility) > 0 { v := s.Visibility metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Visibility", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "VersionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateCommentResponse type CreateCommentOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The comment that has been created. Comment *Comment `type:"structure"` } // String returns the string representation func (s CreateCommentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateCommentOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s CreateCommentOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateCommentOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Comment != nil { v := s.Comment metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Comment", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateCustomMetadataRequest type CreateCustomMetadataInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // Custom metadata in the form of name-value pairs. // // CustomMetadata is a required field CustomMetadata map[string]string `min:"1" type:"map" required:"true"` // The ID of the resource. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` // The ID of the version, if the custom metadata is being added to a document // version. VersionId *string `location:"querystring" locationName:"versionid" min:"1" type:"string"` } // String returns the string representation func (s CreateCustomMetadataInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateCustomMetadataInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *CreateCustomMetadataInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "CreateCustomMetadataInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.CustomMetadata == nil { invalidParams.Add(aws.NewErrParamRequired("CustomMetadata")) } if s.CustomMetadata != nil && len(s.CustomMetadata) < 1 { invalidParams.Add(aws.NewErrParamMinLen("CustomMetadata", 1)) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateCustomMetadataInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if len(s.CustomMetadata) > 0 { v := s.CustomMetadata metadata := protocol.Metadata{} ms0 := e.Map(protocol.BodyTarget, "CustomMetadata", metadata) ms0.Start() for k1, v1 := range v { ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ms0.End() } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "versionid", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateCustomMetadataResponse type CreateCustomMetadataOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s CreateCustomMetadataOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateCustomMetadataOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s CreateCustomMetadataOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateCustomMetadataOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateFolderRequest type CreateFolderInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The name of the new folder. Name *string `min:"1" type:"string"` // The ID of the parent folder. // // ParentFolderId is a required field ParentFolderId *string `min:"1" type:"string" required:"true"` } // String returns the string representation func (s CreateFolderInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateFolderInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *CreateFolderInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "CreateFolderInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Name", 1)) } if s.ParentFolderId == nil { invalidParams.Add(aws.NewErrParamRequired("ParentFolderId")) } if s.ParentFolderId != nil && len(*s.ParentFolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ParentFolderId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateFolderInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ParentFolderId != nil { v := *s.ParentFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateFolderResponse type CreateFolderOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The metadata of the folder. Metadata *FolderMetadata `type:"structure"` } // String returns the string representation func (s CreateFolderOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateFolderOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s CreateFolderOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateFolderOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Metadata != nil { v := s.Metadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Metadata", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateLabelsRequest type CreateLabelsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // List of labels to add to the resource. // // Labels is a required field Labels []string `type:"list" required:"true"` // The ID of the resource. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s CreateLabelsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateLabelsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *CreateLabelsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "CreateLabelsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Labels == nil { invalidParams.Add(aws.NewErrParamRequired("Labels")) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateLabelsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if len(s.Labels) > 0 { v := s.Labels metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Labels", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ls0.End() } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateLabelsResponse type CreateLabelsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s CreateLabelsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateLabelsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s CreateLabelsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateLabelsOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateNotificationSubscriptionRequest type CreateNotificationSubscriptionInput struct { _ struct{} `type:"structure"` // The endpoint to receive the notifications. If the protocol is HTTPS, the // endpoint is a URL that begins with "https://". // // Endpoint is a required field Endpoint *string `min:"1" type:"string" required:"true"` // The ID of the organization. // // OrganizationId is a required field OrganizationId *string `location:"uri" locationName:"OrganizationId" min:"1" type:"string" required:"true"` // The protocol to use. The supported value is https, which delivers JSON-encoded // messages using HTTPS POST. // // Protocol is a required field Protocol SubscriptionProtocolType `type:"string" required:"true" enum:"true"` // The notification type. // // SubscriptionType is a required field SubscriptionType SubscriptionType `type:"string" required:"true" enum:"true"` } // String returns the string representation func (s CreateNotificationSubscriptionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateNotificationSubscriptionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *CreateNotificationSubscriptionInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "CreateNotificationSubscriptionInput"} if s.Endpoint == nil { invalidParams.Add(aws.NewErrParamRequired("Endpoint")) } if s.Endpoint != nil && len(*s.Endpoint) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Endpoint", 1)) } if s.OrganizationId == nil { invalidParams.Add(aws.NewErrParamRequired("OrganizationId")) } if s.OrganizationId != nil && len(*s.OrganizationId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("OrganizationId", 1)) } if len(s.Protocol) == 0 { invalidParams.Add(aws.NewErrParamRequired("Protocol")) } if len(s.SubscriptionType) == 0 { invalidParams.Add(aws.NewErrParamRequired("SubscriptionType")) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateNotificationSubscriptionInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.Endpoint != nil { v := *s.Endpoint metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Endpoint", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Protocol) > 0 { v := s.Protocol metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Protocol", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if len(s.SubscriptionType) > 0 { v := s.SubscriptionType metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "SubscriptionType", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "OrganizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateNotificationSubscriptionResponse type CreateNotificationSubscriptionOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The subscription. Subscription *Subscription `type:"structure"` } // String returns the string representation func (s CreateNotificationSubscriptionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateNotificationSubscriptionOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s CreateNotificationSubscriptionOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateNotificationSubscriptionOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Subscription != nil { v := s.Subscription metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Subscription", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateUserRequest type CreateUserInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The email address of the user. EmailAddress *string `min:"1" type:"string"` // The given name of the user. // // GivenName is a required field GivenName *string `min:"1" type:"string" required:"true"` // The ID of the organization. OrganizationId *string `min:"1" type:"string"` // The password of the user. // // Password is a required field Password *string `min:"4" type:"string" required:"true"` // The amount of storage for the user. StorageRule *StorageRuleType `type:"structure"` // The surname of the user. // // Surname is a required field Surname *string `min:"1" type:"string" required:"true"` // The time zone ID of the user. TimeZoneId *string `min:"1" type:"string"` // The login name of the user. // // Username is a required field Username *string `min:"1" type:"string" required:"true"` } // String returns the string representation func (s CreateUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *CreateUserInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "CreateUserInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.EmailAddress != nil && len(*s.EmailAddress) < 1 { invalidParams.Add(aws.NewErrParamMinLen("EmailAddress", 1)) } if s.GivenName == nil { invalidParams.Add(aws.NewErrParamRequired("GivenName")) } if s.GivenName != nil && len(*s.GivenName) < 1 { invalidParams.Add(aws.NewErrParamMinLen("GivenName", 1)) } if s.OrganizationId != nil && len(*s.OrganizationId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("OrganizationId", 1)) } if s.Password == nil { invalidParams.Add(aws.NewErrParamRequired("Password")) } if s.Password != nil && len(*s.Password) < 4 { invalidParams.Add(aws.NewErrParamMinLen("Password", 4)) } if s.Surname == nil { invalidParams.Add(aws.NewErrParamRequired("Surname")) } if s.Surname != nil && len(*s.Surname) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Surname", 1)) } if s.TimeZoneId != nil && len(*s.TimeZoneId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("TimeZoneId", 1)) } if s.Username == nil { invalidParams.Add(aws.NewErrParamRequired("Username")) } if s.Username != nil && len(*s.Username) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Username", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateUserInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.EmailAddress != nil { v := *s.EmailAddress metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "EmailAddress", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.GivenName != nil { v := *s.GivenName metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "GivenName", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "OrganizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Password != nil { v := *s.Password metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Password", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.StorageRule != nil { v := s.StorageRule metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "StorageRule", v, metadata) } if s.Surname != nil { v := *s.Surname metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Surname", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.TimeZoneId != nil { v := *s.TimeZoneId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "TimeZoneId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Username != nil { v := *s.Username metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Username", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/CreateUserResponse type CreateUserOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The user information. User *User `type:"structure"` } // String returns the string representation func (s CreateUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateUserOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s CreateUserOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s CreateUserOutput) MarshalFields(e protocol.FieldEncoder) error { if s.User != nil { v := s.User metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "User", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeactivateUserRequest type DeactivateUserInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the user. // // UserId is a required field UserId *string `location:"uri" locationName:"UserId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeactivateUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeactivateUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeactivateUserInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeactivateUserInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.UserId == nil { invalidParams.Add(aws.NewErrParamRequired("UserId")) } if s.UserId != nil && len(*s.UserId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeactivateUserInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.UserId != nil { v := *s.UserId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "UserId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeactivateUserOutput type DeactivateUserOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeactivateUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeactivateUserOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeactivateUserOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeactivateUserOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteCommentRequest type DeleteCommentInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the comment. // // CommentId is a required field CommentId *string `location:"uri" locationName:"CommentId" min:"1" type:"string" required:"true"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // The ID of the document version. // // VersionId is a required field VersionId *string `location:"uri" locationName:"VersionId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeleteCommentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteCommentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteCommentInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteCommentInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.CommentId == nil { invalidParams.Add(aws.NewErrParamRequired("CommentId")) } if s.CommentId != nil && len(*s.CommentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("CommentId", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.VersionId == nil { invalidParams.Add(aws.NewErrParamRequired("VersionId")) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteCommentInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.CommentId != nil { v := *s.CommentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "CommentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "VersionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteCommentOutput type DeleteCommentOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteCommentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteCommentOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteCommentOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteCommentOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteCustomMetadataRequest type DeleteCustomMetadataInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // Flag to indicate removal of all custom metadata properties from the specified // resource. DeleteAll *bool `location:"querystring" locationName:"deleteAll" type:"boolean"` // List of properties to remove. Keys []string `location:"querystring" locationName:"keys" type:"list"` // The ID of the resource, either a document or folder. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` // The ID of the version, if the custom metadata is being deleted from a document // version. VersionId *string `location:"querystring" locationName:"versionId" min:"1" type:"string"` } // String returns the string representation func (s DeleteCustomMetadataInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteCustomMetadataInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteCustomMetadataInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteCustomMetadataInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteCustomMetadataInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DeleteAll != nil { v := *s.DeleteAll metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "deleteAll", protocol.BoolValue(v), metadata) } if len(s.Keys) > 0 { v := s.Keys metadata := protocol.Metadata{} ls0 := e.List(protocol.QueryTarget, "keys", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ls0.End() } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "versionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteCustomMetadataResponse type DeleteCustomMetadataOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteCustomMetadataOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteCustomMetadataOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteCustomMetadataOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteCustomMetadataOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteDocumentRequest type DeleteDocumentInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeleteDocumentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteDocumentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteDocumentInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteDocumentInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteDocumentInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteDocumentOutput type DeleteDocumentOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteDocumentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteDocumentOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteDocumentOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteDocumentOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteFolderContentsRequest type DeleteFolderContentsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the folder. // // FolderId is a required field FolderId *string `location:"uri" locationName:"FolderId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeleteFolderContentsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteFolderContentsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteFolderContentsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteFolderContentsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.FolderId == nil { invalidParams.Add(aws.NewErrParamRequired("FolderId")) } if s.FolderId != nil && len(*s.FolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("FolderId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteFolderContentsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.FolderId != nil { v := *s.FolderId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "FolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteFolderContentsOutput type DeleteFolderContentsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteFolderContentsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteFolderContentsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteFolderContentsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteFolderContentsOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteFolderRequest type DeleteFolderInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the folder. // // FolderId is a required field FolderId *string `location:"uri" locationName:"FolderId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeleteFolderInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteFolderInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteFolderInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteFolderInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.FolderId == nil { invalidParams.Add(aws.NewErrParamRequired("FolderId")) } if s.FolderId != nil && len(*s.FolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("FolderId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteFolderInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.FolderId != nil { v := *s.FolderId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "FolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteFolderOutput type DeleteFolderOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteFolderOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteFolderOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteFolderOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteFolderOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteLabelsRequest type DeleteLabelsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // Flag to request removal of all labels from the specified resource. DeleteAll *bool `location:"querystring" locationName:"deleteAll" type:"boolean"` // List of labels to delete from the resource. Labels []string `location:"querystring" locationName:"labels" type:"list"` // The ID of the resource. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeleteLabelsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteLabelsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteLabelsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteLabelsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteLabelsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DeleteAll != nil { v := *s.DeleteAll metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "deleteAll", protocol.BoolValue(v), metadata) } if len(s.Labels) > 0 { v := s.Labels metadata := protocol.Metadata{} ls0 := e.List(protocol.QueryTarget, "labels", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ls0.End() } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteLabelsResponse type DeleteLabelsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteLabelsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteLabelsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteLabelsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteLabelsOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteNotificationSubscriptionRequest type DeleteNotificationSubscriptionInput struct { _ struct{} `type:"structure"` // The ID of the organization. // // OrganizationId is a required field OrganizationId *string `location:"uri" locationName:"OrganizationId" min:"1" type:"string" required:"true"` // The ID of the subscription. // // SubscriptionId is a required field SubscriptionId *string `location:"uri" locationName:"SubscriptionId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeleteNotificationSubscriptionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteNotificationSubscriptionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteNotificationSubscriptionInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteNotificationSubscriptionInput"} if s.OrganizationId == nil { invalidParams.Add(aws.NewErrParamRequired("OrganizationId")) } if s.OrganizationId != nil && len(*s.OrganizationId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("OrganizationId", 1)) } if s.SubscriptionId == nil { invalidParams.Add(aws.NewErrParamRequired("SubscriptionId")) } if s.SubscriptionId != nil && len(*s.SubscriptionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("SubscriptionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteNotificationSubscriptionInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "OrganizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.SubscriptionId != nil { v := *s.SubscriptionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "SubscriptionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteNotificationSubscriptionOutput type DeleteNotificationSubscriptionOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteNotificationSubscriptionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteNotificationSubscriptionOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteNotificationSubscriptionOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteNotificationSubscriptionOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteUserRequest type DeleteUserInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the user. // // UserId is a required field UserId *string `location:"uri" locationName:"UserId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DeleteUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteUserInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteUserInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.UserId == nil { invalidParams.Add(aws.NewErrParamRequired("UserId")) } if s.UserId != nil && len(*s.UserId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteUserInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.UserId != nil { v := *s.UserId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "UserId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteUserOutput type DeleteUserOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s DeleteUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteUserOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DeleteUserOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DeleteUserOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeActivitiesRequest type DescribeActivitiesInput struct { _ struct{} `type:"structure"` // Specifies which activity types to include in the response. If this field // is left empty, all activity types are returned. ActivityTypes *string `location:"querystring" locationName:"activityTypes" min:"1" type:"string"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The timestamp that determines the end time of the activities. The response // includes the activities performed before the specified timestamp. EndTime *time.Time `location:"querystring" locationName:"endTime" type:"timestamp" timestampFormat:"unix"` // Includes indirect activities. An indirect activity results from a direct // activity performed on a parent resource. For example, sharing a parent folder // (the direct activity) shares all of the subfolders and documents within the // parent folder (the indirect activity). IncludeIndirectActivities *bool `location:"querystring" locationName:"includeIndirectActivities" type:"boolean"` // The maximum number of items to return. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The ID of the organization. This is a mandatory parameter when using administrative // API (SigV4) requests. OrganizationId *string `location:"querystring" locationName:"organizationId" min:"1" type:"string"` // The document or folder ID for which to describe activity types. ResourceId *string `location:"querystring" locationName:"resourceId" min:"1" type:"string"` // The timestamp that determines the starting time of the activities. The response // includes the activities performed after the specified timestamp. StartTime *time.Time `location:"querystring" locationName:"startTime" type:"timestamp" timestampFormat:"unix"` // The ID of the user who performed the action. The response includes activities // pertaining to this user. This is an optional parameter and is only applicable // for administrative API (SigV4) requests. UserId *string `location:"querystring" locationName:"userId" min:"1" type:"string"` } // String returns the string representation func (s DescribeActivitiesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeActivitiesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeActivitiesInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeActivitiesInput"} if s.ActivityTypes != nil && len(*s.ActivityTypes) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ActivityTypes", 1)) } if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if s.OrganizationId != nil && len(*s.OrganizationId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("OrganizationId", 1)) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if s.UserId != nil && len(*s.UserId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeActivitiesInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ActivityTypes != nil { v := *s.ActivityTypes metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "activityTypes", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.EndTime != nil { v := *s.EndTime metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "endTime", protocol.TimeValue{V: v, Format: protocol.RFC822TimeFromat}, metadata) } if s.IncludeIndirectActivities != nil { v := *s.IncludeIndirectActivities metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "includeIndirectActivities", protocol.BoolValue(v), metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "organizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "resourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.StartTime != nil { v := *s.StartTime metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "startTime", protocol.TimeValue{V: v, Format: protocol.RFC822TimeFromat}, metadata) } if s.UserId != nil { v := *s.UserId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "userId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeActivitiesResponse type DescribeActivitiesOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The marker for the next set of results. Marker *string `min:"1" type:"string"` // The list of activities for the specified user and time period. UserActivities []Activity `type:"list"` } // String returns the string representation func (s DescribeActivitiesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeActivitiesOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeActivitiesOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeActivitiesOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.UserActivities) > 0 { v := s.UserActivities metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "UserActivities", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeCommentsRequest type DescribeCommentsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // The maximum number of items to return. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. This marker was received from a previous // call. Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The ID of the document version. // // VersionId is a required field VersionId *string `location:"uri" locationName:"VersionId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DescribeCommentsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeCommentsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeCommentsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeCommentsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if s.VersionId == nil { invalidParams.Add(aws.NewErrParamRequired("VersionId")) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeCommentsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "VersionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeCommentsResponse type DescribeCommentsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The list of comments for the specified document version. Comments []Comment `type:"list"` // The marker for the next set of results. This marker was received from a previous // call. Marker *string `min:"1" type:"string"` } // String returns the string representation func (s DescribeCommentsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeCommentsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeCommentsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeCommentsOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.Comments) > 0 { v := s.Comments metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Comments", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeDocumentVersionsRequest type DescribeDocumentVersionsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // Specify "SOURCE" to include initialized versions and a URL for the source // document. Fields *string `location:"querystring" locationName:"fields" min:"1" type:"string"` // A comma-separated list of values. Specify "INITIALIZED" to include incomplete // versions. Include *string `location:"querystring" locationName:"include" min:"1" type:"string"` // The maximum number of versions to return with this call. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. (You received this marker from a // previous call.) Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` } // String returns the string representation func (s DescribeDocumentVersionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeDocumentVersionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeDocumentVersionsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeDocumentVersionsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.Fields != nil && len(*s.Fields) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Fields", 1)) } if s.Include != nil && len(*s.Include) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Include", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeDocumentVersionsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Fields != nil { v := *s.Fields metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "fields", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Include != nil { v := *s.Include metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "include", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeDocumentVersionsResponse type DescribeDocumentVersionsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The document versions. DocumentVersions []DocumentVersionMetadata `type:"list"` // The marker to use when requesting the next set of results. If there are no // additional results, the string is empty. Marker *string `min:"1" type:"string"` } // String returns the string representation func (s DescribeDocumentVersionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeDocumentVersionsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeDocumentVersionsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeDocumentVersionsOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.DocumentVersions) > 0 { v := s.DocumentVersions metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "DocumentVersions", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeFolderContentsRequest type DescribeFolderContentsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the folder. // // FolderId is a required field FolderId *string `location:"uri" locationName:"FolderId" min:"1" type:"string" required:"true"` // The contents to include. Specify "INITIALIZED" to include initialized documents. Include *string `location:"querystring" locationName:"include" min:"1" type:"string"` // The maximum number of items to return with this call. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. This marker was received from a previous // call. Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The order for the contents of the folder. Order OrderType `location:"querystring" locationName:"order" type:"string" enum:"true"` // The sorting criteria. Sort ResourceSortType `location:"querystring" locationName:"sort" type:"string" enum:"true"` // The type of items. Type FolderContentType `location:"querystring" locationName:"type" type:"string" enum:"true"` } // String returns the string representation func (s DescribeFolderContentsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeFolderContentsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeFolderContentsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeFolderContentsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.FolderId == nil { invalidParams.Add(aws.NewErrParamRequired("FolderId")) } if s.FolderId != nil && len(*s.FolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("FolderId", 1)) } if s.Include != nil && len(*s.Include) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Include", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeFolderContentsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.FolderId != nil { v := *s.FolderId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "FolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Include != nil { v := *s.Include metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "include", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Order) > 0 { v := s.Order metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "order", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if len(s.Sort) > 0 { v := s.Sort metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "sort", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeFolderContentsResponse type DescribeFolderContentsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The documents in the specified folder. Documents []DocumentMetadata `type:"list"` // The subfolders in the specified folder. Folders []FolderMetadata `type:"list"` // The marker to use when requesting the next set of results. If there are no // additional results, the string is empty. Marker *string `min:"1" type:"string"` } // String returns the string representation func (s DescribeFolderContentsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeFolderContentsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeFolderContentsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeFolderContentsOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.Documents) > 0 { v := s.Documents metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Documents", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if len(s.Folders) > 0 { v := s.Folders metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Folders", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeGroupsRequest type DescribeGroupsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The maximum number of items to return with this call. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. (You received this marker from a // previous call.) Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The ID of the organization. OrganizationId *string `location:"querystring" locationName:"organizationId" min:"1" type:"string"` // A query to describe groups by group name. // // SearchQuery is a required field SearchQuery *string `location:"querystring" locationName:"searchQuery" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DescribeGroupsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeGroupsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeGroupsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeGroupsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if s.OrganizationId != nil && len(*s.OrganizationId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("OrganizationId", 1)) } if s.SearchQuery == nil { invalidParams.Add(aws.NewErrParamRequired("SearchQuery")) } if s.SearchQuery != nil && len(*s.SearchQuery) < 1 { invalidParams.Add(aws.NewErrParamMinLen("SearchQuery", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeGroupsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "organizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.SearchQuery != nil { v := *s.SearchQuery metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "searchQuery", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeGroupsResponse type DescribeGroupsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The list of groups. Groups []GroupMetadata `type:"list"` // The marker to use when requesting the next set of results. If there are no // additional results, the string is empty. Marker *string `min:"1" type:"string"` } // String returns the string representation func (s DescribeGroupsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeGroupsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeGroupsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeGroupsOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.Groups) > 0 { v := s.Groups metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Groups", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeNotificationSubscriptionsRequest type DescribeNotificationSubscriptionsInput struct { _ struct{} `type:"structure"` // The maximum number of items to return with this call. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. (You received this marker from a // previous call.) Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The ID of the organization. // // OrganizationId is a required field OrganizationId *string `location:"uri" locationName:"OrganizationId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DescribeNotificationSubscriptionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeNotificationSubscriptionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeNotificationSubscriptionsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeNotificationSubscriptionsInput"} if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if s.OrganizationId == nil { invalidParams.Add(aws.NewErrParamRequired("OrganizationId")) } if s.OrganizationId != nil && len(*s.OrganizationId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("OrganizationId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeNotificationSubscriptionsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "OrganizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeNotificationSubscriptionsResponse type DescribeNotificationSubscriptionsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The marker to use when requesting the next set of results. If there are no // additional results, the string is empty. Marker *string `min:"1" type:"string"` // The subscriptions. Subscriptions []Subscription `type:"list"` } // String returns the string representation func (s DescribeNotificationSubscriptionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeNotificationSubscriptionsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeNotificationSubscriptionsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeNotificationSubscriptionsOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Subscriptions) > 0 { v := s.Subscriptions metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Subscriptions", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeResourcePermissionsRequest type DescribeResourcePermissionsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The maximum number of items to return with this call. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. (You received this marker from a // previous call) Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The ID of the principal to filter permissions by. PrincipalId *string `location:"querystring" locationName:"principalId" min:"1" type:"string"` // The ID of the resource. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s DescribeResourcePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeResourcePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeResourcePermissionsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeResourcePermissionsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if s.PrincipalId != nil && len(*s.PrincipalId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("PrincipalId", 1)) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeResourcePermissionsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.PrincipalId != nil { v := *s.PrincipalId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "principalId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeResourcePermissionsResponse type DescribeResourcePermissionsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The marker to use when requesting the next set of results. If there are no // additional results, the string is empty. Marker *string `min:"1" type:"string"` // The principals. Principals []Principal `type:"list"` } // String returns the string representation func (s DescribeResourcePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeResourcePermissionsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeResourcePermissionsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeResourcePermissionsOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Principals) > 0 { v := s.Principals metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Principals", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeRootFoldersRequest type DescribeRootFoldersInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. // // AuthenticationToken is a required field AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string" required:"true"` // The maximum number of items to return. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. (You received this marker from a // previous call.) Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` } // String returns the string representation func (s DescribeRootFoldersInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeRootFoldersInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeRootFoldersInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeRootFoldersInput"} if s.AuthenticationToken == nil { invalidParams.Add(aws.NewErrParamRequired("AuthenticationToken")) } if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeRootFoldersInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeRootFoldersResponse type DescribeRootFoldersOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The user's special folders. Folders []FolderMetadata `type:"list"` // The marker for the next set of results. Marker *string `min:"1" type:"string"` } // String returns the string representation func (s DescribeRootFoldersOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeRootFoldersOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeRootFoldersOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeRootFoldersOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.Folders) > 0 { v := s.Folders metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Folders", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeUsersRequest type DescribeUsersInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // A comma-separated list of values. Specify "STORAGE_METADATA" to include the // user storage quota and utilization information. Fields *string `location:"querystring" locationName:"fields" min:"1" type:"string"` // The state of the users. Specify "ALL" to include inactive users. Include UserFilterType `location:"querystring" locationName:"include" type:"string" enum:"true"` // The maximum number of items to return. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. (You received this marker from a // previous call.) Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The order for the results. Order OrderType `location:"querystring" locationName:"order" type:"string" enum:"true"` // The ID of the organization. OrganizationId *string `location:"querystring" locationName:"organizationId" min:"1" type:"string"` // A query to filter users by user name. Query *string `location:"querystring" locationName:"query" min:"1" type:"string"` // The sorting criteria. Sort UserSortType `location:"querystring" locationName:"sort" type:"string" enum:"true"` // The IDs of the users. UserIds *string `location:"querystring" locationName:"userIds" min:"1" type:"string"` } // String returns the string representation func (s DescribeUsersInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeUsersInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeUsersInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DescribeUsersInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Fields != nil && len(*s.Fields) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Fields", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if s.OrganizationId != nil && len(*s.OrganizationId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("OrganizationId", 1)) } if s.Query != nil && len(*s.Query) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Query", 1)) } if s.UserIds != nil && len(*s.UserIds) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserIds", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeUsersInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Fields != nil { v := *s.Fields metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "fields", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Include) > 0 { v := s.Include metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "include", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Order) > 0 { v := s.Order metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "order", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "organizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Query != nil { v := *s.Query metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "query", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Sort) > 0 { v := s.Sort metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "sort", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.UserIds != nil { v := *s.UserIds metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "userIds", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DescribeUsersResponse type DescribeUsersOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The marker to use when requesting the next set of results. If there are no // additional results, the string is empty. Marker *string `min:"1" type:"string"` // The total number of users included in the results. TotalNumberOfUsers *int64 `deprecated:"true" type:"long"` // The users. Users []User `type:"list"` } // String returns the string representation func (s DescribeUsersOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DescribeUsersOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s DescribeUsersOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DescribeUsersOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.TotalNumberOfUsers != nil { v := *s.TotalNumberOfUsers metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "TotalNumberOfUsers", protocol.Int64Value(v), metadata) } if len(s.Users) > 0 { v := s.Users metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Users", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil } // Describes the document. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DocumentMetadata type DocumentMetadata struct { _ struct{} `type:"structure"` // The time when the document was created. CreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The ID of the creator. CreatorId *string `min:"1" type:"string"` // The ID of the document. Id *string `min:"1" type:"string"` // List of labels on the document. Labels []string `type:"list"` // The latest version of the document. LatestVersionMetadata *DocumentVersionMetadata `type:"structure"` // The time when the document was updated. ModifiedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The ID of the parent folder. ParentFolderId *string `min:"1" type:"string"` // The resource state. ResourceState ResourceStateType `type:"string" enum:"true"` } // String returns the string representation func (s DocumentMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DocumentMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DocumentMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.CreatedTimestamp != nil { v := *s.CreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.CreatorId != nil { v := *s.CreatorId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatorId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Labels) > 0 { v := s.Labels metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Labels", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ls0.End() } if s.LatestVersionMetadata != nil { v := s.LatestVersionMetadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "LatestVersionMetadata", v, metadata) } if s.ModifiedTimestamp != nil { v := *s.ModifiedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ModifiedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.ParentFolderId != nil { v := *s.ParentFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.ResourceState) > 0 { v := s.ResourceState metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ResourceState", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Describes a version of a document. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DocumentVersionMetadata type DocumentVersionMetadata struct { _ struct{} `type:"structure"` // The timestamp when the content of the document was originally created. ContentCreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The timestamp when the content of the document was modified. ContentModifiedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The content type of the document. ContentType *string `min:"1" type:"string"` // The timestamp when the document was first uploaded. CreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The ID of the creator. CreatorId *string `min:"1" type:"string"` // The ID of the version. Id *string `min:"1" type:"string"` // The timestamp when the document was last uploaded. ModifiedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The name of the version. Name *string `min:"1" type:"string"` // The signature of the document. Signature *string `type:"string"` // The size of the document, in bytes. Size *int64 `type:"long"` // The source of the document. Source map[string]string `type:"map"` // The status of the document. Status DocumentStatusType `type:"string" enum:"true"` // The thumbnail of the document. Thumbnail map[string]string `type:"map"` } // String returns the string representation func (s DocumentVersionMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DocumentVersionMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s DocumentVersionMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.ContentCreatedTimestamp != nil { v := *s.ContentCreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ContentCreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.ContentModifiedTimestamp != nil { v := *s.ContentModifiedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ContentModifiedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.ContentType != nil { v := *s.ContentType metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ContentType", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.CreatedTimestamp != nil { v := *s.CreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.CreatorId != nil { v := *s.CreatorId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatorId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ModifiedTimestamp != nil { v := *s.ModifiedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ModifiedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Signature != nil { v := *s.Signature metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Signature", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Size != nil { v := *s.Size metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Size", protocol.Int64Value(v), metadata) } if len(s.Source) > 0 { v := s.Source metadata := protocol.Metadata{} ms0 := e.Map(protocol.BodyTarget, "Source", metadata) ms0.Start() for k1, v1 := range v { ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ms0.End() } if len(s.Status) > 0 { v := s.Status metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Status", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if len(s.Thumbnail) > 0 { v := s.Thumbnail metadata := protocol.Metadata{} ms0 := e.Map(protocol.BodyTarget, "Thumbnail", metadata) ms0.Start() for k1, v1 := range v { ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ms0.End() } return nil } // Describes a folder. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/FolderMetadata type FolderMetadata struct { _ struct{} `type:"structure"` // The time when the folder was created. CreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The ID of the creator. CreatorId *string `min:"1" type:"string"` // The ID of the folder. Id *string `min:"1" type:"string"` // List of labels on the folder. Labels []string `type:"list"` // The size of the latest version of the folder metadata. LatestVersionSize *int64 `type:"long"` // The time when the folder was updated. ModifiedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The name of the folder. Name *string `min:"1" type:"string"` // The ID of the parent folder. ParentFolderId *string `min:"1" type:"string"` // The resource state of the folder. ResourceState ResourceStateType `type:"string" enum:"true"` // The unique identifier created from the subfolders and documents of the folder. Signature *string `type:"string"` // The size of the folder metadata. Size *int64 `type:"long"` } // String returns the string representation func (s FolderMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s FolderMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s FolderMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.CreatedTimestamp != nil { v := *s.CreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.CreatorId != nil { v := *s.CreatorId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatorId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Labels) > 0 { v := s.Labels metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Labels", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ls0.End() } if s.LatestVersionSize != nil { v := *s.LatestVersionSize metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "LatestVersionSize", protocol.Int64Value(v), metadata) } if s.ModifiedTimestamp != nil { v := *s.ModifiedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ModifiedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ParentFolderId != nil { v := *s.ParentFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.ResourceState) > 0 { v := s.ResourceState metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ResourceState", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.Signature != nil { v := *s.Signature metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Signature", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Size != nil { v := *s.Size metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Size", protocol.Int64Value(v), metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetCurrentUserRequest type GetCurrentUserInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. // // AuthenticationToken is a required field AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string" required:"true"` } // String returns the string representation func (s GetCurrentUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetCurrentUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *GetCurrentUserInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetCurrentUserInput"} if s.AuthenticationToken == nil { invalidParams.Add(aws.NewErrParamRequired("AuthenticationToken")) } if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetCurrentUserInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetCurrentUserResponse type GetCurrentUserOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // Metadata of the user. User *User `type:"structure"` } // String returns the string representation func (s GetCurrentUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetCurrentUserOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s GetCurrentUserOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetCurrentUserOutput) MarshalFields(e protocol.FieldEncoder) error { if s.User != nil { v := s.User metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "User", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentRequest type GetDocumentInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // Set this to TRUE to include custom metadata in the response. IncludeCustomMetadata *bool `location:"querystring" locationName:"includeCustomMetadata" type:"boolean"` } // String returns the string representation func (s GetDocumentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetDocumentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *GetDocumentInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetDocumentInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetDocumentInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.IncludeCustomMetadata != nil { v := *s.IncludeCustomMetadata metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "includeCustomMetadata", protocol.BoolValue(v), metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentResponse type GetDocumentOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The custom metadata on the document. CustomMetadata map[string]string `min:"1" type:"map"` // The metadata details of the document. Metadata *DocumentMetadata `type:"structure"` } // String returns the string representation func (s GetDocumentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetDocumentOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s GetDocumentOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetDocumentOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.CustomMetadata) > 0 { v := s.CustomMetadata metadata := protocol.Metadata{} ms0 := e.Map(protocol.BodyTarget, "CustomMetadata", metadata) ms0.Start() for k1, v1 := range v { ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ms0.End() } if s.Metadata != nil { v := s.Metadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Metadata", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentPathRequest type GetDocumentPathInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // A comma-separated list of values. Specify NAME to include the names of the // parent folders. Fields *string `location:"querystring" locationName:"fields" min:"1" type:"string"` // The maximum number of levels in the hierarchy to return. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // This value is not supported. Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` } // String returns the string representation func (s GetDocumentPathInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetDocumentPathInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *GetDocumentPathInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetDocumentPathInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.Fields != nil && len(*s.Fields) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Fields", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetDocumentPathInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Fields != nil { v := *s.Fields metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "fields", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentPathResponse type GetDocumentPathOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The path information. Path *ResourcePath `type:"structure"` } // String returns the string representation func (s GetDocumentPathOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetDocumentPathOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s GetDocumentPathOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetDocumentPathOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Path != nil { v := s.Path metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Path", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentVersionRequest type GetDocumentVersionInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // A comma-separated list of values. Specify "SOURCE" to include a URL for the // source document. Fields *string `location:"querystring" locationName:"fields" min:"1" type:"string"` // Set this to TRUE to include custom metadata in the response. IncludeCustomMetadata *bool `location:"querystring" locationName:"includeCustomMetadata" type:"boolean"` // The version ID of the document. // // VersionId is a required field VersionId *string `location:"uri" locationName:"VersionId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s GetDocumentVersionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetDocumentVersionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *GetDocumentVersionInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetDocumentVersionInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.Fields != nil && len(*s.Fields) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Fields", 1)) } if s.VersionId == nil { invalidParams.Add(aws.NewErrParamRequired("VersionId")) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetDocumentVersionInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "VersionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Fields != nil { v := *s.Fields metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "fields", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.IncludeCustomMetadata != nil { v := *s.IncludeCustomMetadata metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "includeCustomMetadata", protocol.BoolValue(v), metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetDocumentVersionResponse type GetDocumentVersionOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The custom metadata on the document version. CustomMetadata map[string]string `min:"1" type:"map"` // The version metadata. Metadata *DocumentVersionMetadata `type:"structure"` } // String returns the string representation func (s GetDocumentVersionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetDocumentVersionOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s GetDocumentVersionOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetDocumentVersionOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.CustomMetadata) > 0 { v := s.CustomMetadata metadata := protocol.Metadata{} ms0 := e.Map(protocol.BodyTarget, "CustomMetadata", metadata) ms0.Start() for k1, v1 := range v { ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ms0.End() } if s.Metadata != nil { v := s.Metadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Metadata", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetFolderRequest type GetFolderInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the folder. // // FolderId is a required field FolderId *string `location:"uri" locationName:"FolderId" min:"1" type:"string" required:"true"` // Set to TRUE to include custom metadata in the response. IncludeCustomMetadata *bool `location:"querystring" locationName:"includeCustomMetadata" type:"boolean"` } // String returns the string representation func (s GetFolderInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetFolderInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *GetFolderInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetFolderInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.FolderId == nil { invalidParams.Add(aws.NewErrParamRequired("FolderId")) } if s.FolderId != nil && len(*s.FolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("FolderId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetFolderInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.FolderId != nil { v := *s.FolderId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "FolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.IncludeCustomMetadata != nil { v := *s.IncludeCustomMetadata metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "includeCustomMetadata", protocol.BoolValue(v), metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetFolderResponse type GetFolderOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The custom metadata on the folder. CustomMetadata map[string]string `min:"1" type:"map"` // The metadata of the folder. Metadata *FolderMetadata `type:"structure"` } // String returns the string representation func (s GetFolderOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetFolderOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s GetFolderOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetFolderOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.CustomMetadata) > 0 { v := s.CustomMetadata metadata := protocol.Metadata{} ms0 := e.Map(protocol.BodyTarget, "CustomMetadata", metadata) ms0.Start() for k1, v1 := range v { ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ms0.End() } if s.Metadata != nil { v := s.Metadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Metadata", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetFolderPathRequest type GetFolderPathInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // A comma-separated list of values. Specify "NAME" to include the names of // the parent folders. Fields *string `location:"querystring" locationName:"fields" min:"1" type:"string"` // The ID of the folder. // // FolderId is a required field FolderId *string `location:"uri" locationName:"FolderId" min:"1" type:"string" required:"true"` // The maximum number of levels in the hierarchy to return. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // This value is not supported. Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` } // String returns the string representation func (s GetFolderPathInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetFolderPathInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *GetFolderPathInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetFolderPathInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Fields != nil && len(*s.Fields) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Fields", 1)) } if s.FolderId == nil { invalidParams.Add(aws.NewErrParamRequired("FolderId")) } if s.FolderId != nil && len(*s.FolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("FolderId", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetFolderPathInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.FolderId != nil { v := *s.FolderId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "FolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Fields != nil { v := *s.Fields metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "fields", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetFolderPathResponse type GetFolderPathOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The path information. Path *ResourcePath `type:"structure"` } // String returns the string representation func (s GetFolderPathOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetFolderPathOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s GetFolderPathOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetFolderPathOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Path != nil { v := s.Path metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Path", v, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetResourcesRequest type GetResourcesInput struct { _ struct{} `type:"structure"` // The Amazon WorkDocs authentication token. Do not set this field when using // administrative API actions, as in accessing the API operation using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The collection type. CollectionType ResourceCollectionType `location:"querystring" locationName:"collectionType" type:"string" enum:"true"` // The maximum number of resources to return. Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // The marker for the next set of results. This marker was received from a previous // call. Marker *string `location:"querystring" locationName:"marker" min:"1" type:"string"` // The user ID for the resource collection. This is a required field for accessing // the API operation using IAM credentials. UserId *string `location:"querystring" locationName:"userId" min:"1" type:"string"` } // String returns the string representation func (s GetResourcesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetResourcesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *GetResourcesInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "GetResourcesInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(aws.NewErrParamMinValue("Limit", 1)) } if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Marker", 1)) } if s.UserId != nil && len(*s.UserId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetResourcesInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.CollectionType) > 0 { v := s.CollectionType metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "collectionType", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.Limit != nil { v := *s.Limit metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "limit", protocol.Int64Value(v), metadata) } if s.Marker != nil { v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.UserId != nil { v := *s.UserId metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "userId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GetResourcesResponse type GetResourcesOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The documents in the specified collection. Documents []DocumentMetadata `type:"list"` // The folders in the specified folder. Folders []FolderMetadata `type:"list"` // The marker to use when requesting the next set of results. If there are no // additional results, the string is empty. Marker *string `min:"1" type:"string"` } // String returns the string representation func (s GetResourcesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetResourcesOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s GetResourcesOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GetResourcesOutput) MarshalFields(e protocol.FieldEncoder) error { if len(s.Documents) > 0 { v := s.Documents metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Documents", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if len(s.Folders) > 0 { v := s.Folders metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Folders", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if s.Marker != nil
return nil } // Describes the metadata of a user group. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/GroupMetadata type GroupMetadata struct { _ struct{} `type:"structure"` // The ID of the user group. Id *string `min:"1" type:"string"` // The name of the group. Name *string `type:"string"` } // String returns the string representation func (s GroupMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GroupMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s GroupMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/InitiateDocumentVersionUploadRequest type InitiateDocumentVersionUploadInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The timestamp when the content of the document was originally created. ContentCreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The timestamp when the content of the document was modified. ContentModifiedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The content type of the document. ContentType *string `min:"1" type:"string"` // The size of the document, in bytes. DocumentSizeInBytes *int64 `type:"long"` // The ID of the document. Id *string `min:"1" type:"string"` // The name of the document. Name *string `min:"1" type:"string"` // The ID of the parent folder. // // ParentFolderId is a required field ParentFolderId *string `min:"1" type:"string" required:"true"` } // String returns the string representation func (s InitiateDocumentVersionUploadInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s InitiateDocumentVersionUploadInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *InitiateDocumentVersionUploadInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "InitiateDocumentVersionUploadInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.ContentType != nil && len(*s.ContentType) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ContentType", 1)) } if s.Id != nil && len(*s.Id) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Id", 1)) } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Name", 1)) } if s.ParentFolderId == nil { invalidParams.Add(aws.NewErrParamRequired("ParentFolderId")) } if s.ParentFolderId != nil && len(*s.ParentFolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ParentFolderId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s InitiateDocumentVersionUploadInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.ContentCreatedTimestamp != nil { v := *s.ContentCreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ContentCreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.ContentModifiedTimestamp != nil { v := *s.ContentModifiedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ContentModifiedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.ContentType != nil { v := *s.ContentType metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ContentType", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentSizeInBytes != nil { v := *s.DocumentSizeInBytes metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "DocumentSizeInBytes", protocol.Int64Value(v), metadata) } if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ParentFolderId != nil { v := *s.ParentFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/InitiateDocumentVersionUploadResponse type InitiateDocumentVersionUploadOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The document metadata. Metadata *DocumentMetadata `type:"structure"` // The upload metadata. UploadMetadata *UploadMetadata `type:"structure"` } // String returns the string representation func (s InitiateDocumentVersionUploadOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s InitiateDocumentVersionUploadOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s InitiateDocumentVersionUploadOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s InitiateDocumentVersionUploadOutput) MarshalFields(e protocol.FieldEncoder) error { if s.Metadata != nil { v := s.Metadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Metadata", v, metadata) } if s.UploadMetadata != nil { v := s.UploadMetadata metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "UploadMetadata", v, metadata) } return nil } // Set of options which defines notification preferences of given action. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/NotificationOptions type NotificationOptions struct { _ struct{} `type:"structure"` // Text value to be included in the email body. EmailMessage *string `type:"string"` // Boolean value to indicate an email notification should be sent to the receipients. SendEmail *bool `type:"boolean"` } // String returns the string representation func (s NotificationOptions) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s NotificationOptions) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s NotificationOptions) MarshalFields(e protocol.FieldEncoder) error { if s.EmailMessage != nil { v := *s.EmailMessage metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "EmailMessage", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.SendEmail != nil { v := *s.SendEmail metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "SendEmail", protocol.BoolValue(v), metadata) } return nil } // Describes the users or user groups. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/Participants type Participants struct { _ struct{} `type:"structure"` // The list of user groups. Groups []GroupMetadata `type:"list"` // The list of users. Users []UserMetadata `type:"list"` } // String returns the string representation func (s Participants) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s Participants) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s Participants) MarshalFields(e protocol.FieldEncoder) error { if len(s.Groups) > 0 { v := s.Groups metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Groups", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if len(s.Users) > 0 { v := s.Users metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Users", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil } // Describes the permissions. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/PermissionInfo type PermissionInfo struct { _ struct{} `type:"structure"` // The role of the user. Role RoleType `type:"string" enum:"true"` // The type of permissions. Type RolePermissionType `type:"string" enum:"true"` } // String returns the string representation func (s PermissionInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s PermissionInfo) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s PermissionInfo) MarshalFields(e protocol.FieldEncoder) error { if len(s.Role) > 0 { v := s.Role metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Role", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Describes a resource. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/Principal type Principal struct { _ struct{} `type:"structure"` // The ID of the resource. Id *string `min:"1" type:"string"` // The permission information for the resource. Roles []PermissionInfo `type:"list"` // The type of resource. Type PrincipalType `type:"string" enum:"true"` } // String returns the string representation func (s Principal) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s Principal) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s Principal) MarshalFields(e protocol.FieldEncoder) error { if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Roles) > 0 { v := s.Roles metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Roles", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/RemoveAllResourcePermissionsRequest type RemoveAllResourcePermissionsInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the resource. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s RemoveAllResourcePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s RemoveAllResourcePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *RemoveAllResourcePermissionsInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "RemoveAllResourcePermissionsInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s RemoveAllResourcePermissionsInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/RemoveAllResourcePermissionsOutput type RemoveAllResourcePermissionsOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s RemoveAllResourcePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s RemoveAllResourcePermissionsOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s RemoveAllResourcePermissionsOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s RemoveAllResourcePermissionsOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/RemoveResourcePermissionRequest type RemoveResourcePermissionInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The principal ID of the resource. // // PrincipalId is a required field PrincipalId *string `location:"uri" locationName:"PrincipalId" min:"1" type:"string" required:"true"` // The principal type of the resource. PrincipalType PrincipalType `location:"querystring" locationName:"type" type:"string" enum:"true"` // The ID of the resource. // // ResourceId is a required field ResourceId *string `location:"uri" locationName:"ResourceId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s RemoveResourcePermissionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s RemoveResourcePermissionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *RemoveResourcePermissionInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "RemoveResourcePermissionInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.PrincipalId == nil { invalidParams.Add(aws.NewErrParamRequired("PrincipalId")) } if s.PrincipalId != nil && len(*s.PrincipalId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("PrincipalId", 1)) } if s.ResourceId == nil { invalidParams.Add(aws.NewErrParamRequired("ResourceId")) } if s.ResourceId != nil && len(*s.ResourceId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ResourceId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s RemoveResourcePermissionInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.PrincipalId != nil { v := *s.PrincipalId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "PrincipalId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ResourceId != nil { v := *s.ResourceId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "ResourceId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.PrincipalType) > 0 { v := s.PrincipalType metadata := protocol.Metadata{} e.SetValue(protocol.QueryTarget, "type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/RemoveResourcePermissionOutput type RemoveResourcePermissionOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s RemoveResourcePermissionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s RemoveResourcePermissionOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s RemoveResourcePermissionOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s RemoveResourcePermissionOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Describes the metadata of a resource. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/ResourceMetadata type ResourceMetadata struct { _ struct{} `type:"structure"` // The ID of the resource. Id *string `min:"1" type:"string"` // The name of the resource. Name *string `min:"1" type:"string"` // The original name of the resource before a rename operation. OriginalName *string `min:"1" type:"string"` // The owner of the resource. Owner *UserMetadata `type:"structure"` // The parent ID of the resource before a rename operation. ParentId *string `min:"1" type:"string"` // The type of resource. Type ResourceType `type:"string" enum:"true"` // The version ID of the resource. This is an optional field and is filled for // action on document version. VersionId *string `min:"1" type:"string"` } // String returns the string representation func (s ResourceMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ResourceMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s ResourceMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.OriginalName != nil { v := *s.OriginalName metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "OriginalName", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Owner != nil { v := s.Owner metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Owner", v, metadata) } if s.ParentId != nil { v := *s.ParentId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "VersionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Describes the path information of a resource. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/ResourcePath type ResourcePath struct { _ struct{} `type:"structure"` // The components of the resource path. Components []ResourcePathComponent `type:"list"` } // String returns the string representation func (s ResourcePath) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ResourcePath) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s ResourcePath) MarshalFields(e protocol.FieldEncoder) error { if len(s.Components) > 0 { v := s.Components metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "Components", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil } // Describes the resource path. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/ResourcePathComponent type ResourcePathComponent struct { _ struct{} `type:"structure"` // The ID of the resource path. Id *string `min:"1" type:"string"` // The name of the resource path. Name *string `min:"1" type:"string"` } // String returns the string representation func (s ResourcePathComponent) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ResourcePathComponent) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s ResourcePathComponent) MarshalFields(e protocol.FieldEncoder) error { if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Describes the recipient type and ID, if available. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/SharePrincipal type SharePrincipal struct { _ struct{} `type:"structure"` // The ID of the recipient. // // Id is a required field Id *string `min:"1" type:"string" required:"true"` // The role of the recipient. // // Role is a required field Role RoleType `type:"string" required:"true" enum:"true"` // The type of the recipient. // // Type is a required field Type PrincipalType `type:"string" required:"true" enum:"true"` } // String returns the string representation func (s SharePrincipal) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SharePrincipal) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *SharePrincipal) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "SharePrincipal"} if s.Id == nil { invalidParams.Add(aws.NewErrParamRequired("Id")) } if s.Id != nil && len(*s.Id) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Id", 1)) } if len(s.Role) == 0 { invalidParams.Add(aws.NewErrParamRequired("Role")) } if len(s.Type) == 0 { invalidParams.Add(aws.NewErrParamRequired("Type")) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s SharePrincipal) MarshalFields(e protocol.FieldEncoder) error { if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Role) > 0 { v := s.Role metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Role", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Describes the share results of a resource. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/ShareResult type ShareResult struct { _ struct{} `type:"structure"` // The ID of the invited user. InviteePrincipalId *string `min:"1" type:"string"` // The ID of the principal. PrincipalId *string `min:"1" type:"string"` // The role. Role RoleType `type:"string" enum:"true"` // The ID of the resource that was shared. ShareId *string `min:"1" type:"string"` // The status. Status ShareStatusType `type:"string" enum:"true"` // The status message. StatusMessage *string `type:"string"` } // String returns the string representation func (s ShareResult) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ShareResult) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s ShareResult) MarshalFields(e protocol.FieldEncoder) error { if s.InviteePrincipalId != nil { v := *s.InviteePrincipalId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "InviteePrincipalId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.PrincipalId != nil { v := *s.PrincipalId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "PrincipalId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Role) > 0 { v := s.Role metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Role", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.ShareId != nil { v := *s.ShareId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ShareId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Status) > 0 { v := s.Status metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Status", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.StatusMessage != nil { v := *s.StatusMessage metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "StatusMessage", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Describes the storage for a user. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/StorageRuleType type StorageRuleType struct { _ struct{} `type:"structure"` // The amount of storage allocated, in bytes. StorageAllocatedInBytes *int64 `type:"long"` // The type of storage. StorageType StorageType `type:"string" enum:"true"` } // String returns the string representation func (s StorageRuleType) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s StorageRuleType) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s StorageRuleType) MarshalFields(e protocol.FieldEncoder) error { if s.StorageAllocatedInBytes != nil { v := *s.StorageAllocatedInBytes metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "StorageAllocatedInBytes", protocol.Int64Value(v), metadata) } if len(s.StorageType) > 0 { v := s.StorageType metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "StorageType", protocol.QuotedValue{ValueMarshaler: v}, metadata) } return nil } // Describes a subscription. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/Subscription type Subscription struct { _ struct{} `type:"structure"` // The endpoint of the subscription. EndPoint *string `min:"1" type:"string"` // The protocol of the subscription. Protocol SubscriptionProtocolType `type:"string" enum:"true"` // The ID of the subscription. SubscriptionId *string `min:"1" type:"string"` } // String returns the string representation func (s Subscription) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s Subscription) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s Subscription) MarshalFields(e protocol.FieldEncoder) error { if s.EndPoint != nil { v := *s.EndPoint metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "EndPoint", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Protocol) > 0 { v := s.Protocol metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Protocol", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.SubscriptionId != nil { v := *s.SubscriptionId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "SubscriptionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateDocumentRequest type UpdateDocumentInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // The name of the document. Name *string `min:"1" type:"string"` // The ID of the parent folder. ParentFolderId *string `min:"1" type:"string"` // The resource state of the document. Only ACTIVE and RECYCLED are supported. ResourceState ResourceStateType `type:"string" enum:"true"` } // String returns the string representation func (s UpdateDocumentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateDocumentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateDocumentInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "UpdateDocumentInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Name", 1)) } if s.ParentFolderId != nil && len(*s.ParentFolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ParentFolderId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateDocumentInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ParentFolderId != nil { v := *s.ParentFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.ResourceState) > 0 { v := s.ResourceState metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ResourceState", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateDocumentOutput type UpdateDocumentOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s UpdateDocumentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateDocumentOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s UpdateDocumentOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateDocumentOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateDocumentVersionRequest type UpdateDocumentVersionInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the document. // // DocumentId is a required field DocumentId *string `location:"uri" locationName:"DocumentId" min:"1" type:"string" required:"true"` // The version ID of the document. // // VersionId is a required field VersionId *string `location:"uri" locationName:"VersionId" min:"1" type:"string" required:"true"` // The status of the version. VersionStatus DocumentVersionStatus `type:"string" enum:"true"` } // String returns the string representation func (s UpdateDocumentVersionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateDocumentVersionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateDocumentVersionInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "UpdateDocumentVersionInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.DocumentId == nil { invalidParams.Add(aws.NewErrParamRequired("DocumentId")) } if s.DocumentId != nil && len(*s.DocumentId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("DocumentId", 1)) } if s.VersionId == nil { invalidParams.Add(aws.NewErrParamRequired("VersionId")) } if s.VersionId != nil && len(*s.VersionId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("VersionId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateDocumentVersionInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if len(s.VersionStatus) > 0 { v := s.VersionStatus metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "VersionStatus", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.DocumentId != nil { v := *s.DocumentId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "DocumentId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.VersionId != nil { v := *s.VersionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "VersionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateDocumentVersionOutput type UpdateDocumentVersionOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s UpdateDocumentVersionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateDocumentVersionOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s UpdateDocumentVersionOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateDocumentVersionOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateFolderRequest type UpdateFolderInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The ID of the folder. // // FolderId is a required field FolderId *string `location:"uri" locationName:"FolderId" min:"1" type:"string" required:"true"` // The name of the folder. Name *string `min:"1" type:"string"` // The ID of the parent folder. ParentFolderId *string `min:"1" type:"string"` // The resource state of the folder. Only ACTIVE and RECYCLED are accepted values // from the API. ResourceState ResourceStateType `type:"string" enum:"true"` } // String returns the string representation func (s UpdateFolderInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateFolderInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateFolderInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "UpdateFolderInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.FolderId == nil { invalidParams.Add(aws.NewErrParamRequired("FolderId")) } if s.FolderId != nil && len(*s.FolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("FolderId", 1)) } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Name", 1)) } if s.ParentFolderId != nil && len(*s.ParentFolderId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("ParentFolderId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateFolderInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.Name != nil { v := *s.Name metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Name", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.ParentFolderId != nil { v := *s.ParentFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ParentFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.ResourceState) > 0 { v := s.ResourceState metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ResourceState", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.FolderId != nil { v := *s.FolderId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "FolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateFolderOutput type UpdateFolderOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response } // String returns the string representation func (s UpdateFolderOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateFolderOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s UpdateFolderOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateFolderOutput) MarshalFields(e protocol.FieldEncoder) error { return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateUserRequest type UpdateUserInput struct { _ struct{} `type:"structure"` // Amazon WorkDocs authentication token. Do not set this field when using administrative // API actions, as in accessing the API using AWS credentials. AuthenticationToken *string `location:"header" locationName:"Authentication" min:"1" type:"string"` // The given name of the user. GivenName *string `min:"1" type:"string"` // Boolean value to determine whether the user is granted Poweruser privileges. GrantPoweruserPrivileges BooleanEnumType `type:"string" enum:"true"` // The locale of the user. Locale LocaleType `type:"string" enum:"true"` // The amount of storage for the user. StorageRule *StorageRuleType `type:"structure"` // The surname of the user. Surname *string `min:"1" type:"string"` // The time zone ID of the user. TimeZoneId *string `min:"1" type:"string"` // The type of the user. Type UserType `type:"string" enum:"true"` // The ID of the user. // // UserId is a required field UserId *string `location:"uri" locationName:"UserId" min:"1" type:"string" required:"true"` } // String returns the string representation func (s UpdateUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateUserInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "UpdateUserInput"} if s.AuthenticationToken != nil && len(*s.AuthenticationToken) < 1 { invalidParams.Add(aws.NewErrParamMinLen("AuthenticationToken", 1)) } if s.GivenName != nil && len(*s.GivenName) < 1 { invalidParams.Add(aws.NewErrParamMinLen("GivenName", 1)) } if s.Surname != nil && len(*s.Surname) < 1 { invalidParams.Add(aws.NewErrParamMinLen("Surname", 1)) } if s.TimeZoneId != nil && len(*s.TimeZoneId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("TimeZoneId", 1)) } if s.UserId == nil { invalidParams.Add(aws.NewErrParamRequired("UserId")) } if s.UserId != nil && len(*s.UserId) < 1 { invalidParams.Add(aws.NewErrParamMinLen("UserId", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateUserInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/x-amz-json-1.1"), protocol.Metadata{}) if s.GivenName != nil { v := *s.GivenName metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "GivenName", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.GrantPoweruserPrivileges) > 0 { v := s.GrantPoweruserPrivileges metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "GrantPoweruserPrivileges", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if len(s.Locale) > 0 { v := s.Locale metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Locale", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.StorageRule != nil { v := s.StorageRule metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "StorageRule", v, metadata) } if s.Surname != nil { v := *s.Surname metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Surname", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.TimeZoneId != nil { v := *s.TimeZoneId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "TimeZoneId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.AuthenticationToken != nil { v := *s.AuthenticationToken metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "Authentication", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.UserId != nil { v := *s.UserId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "UserId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UpdateUserResponse type UpdateUserOutput struct { _ struct{} `type:"structure"` responseMetadata aws.Response // The user information. User *User `type:"structure"` } // String returns the string representation func (s UpdateUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UpdateUserOutput) GoString() string { return s.String() } // SDKResponseMetdata return sthe response metadata for the API. func (s UpdateUserOutput) SDKResponseMetadata() aws.Response { return s.responseMetadata } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateUserOutput) MarshalFields(e protocol.FieldEncoder) error { if s.User != nil { v := s.User metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "User", v, metadata) } return nil } // Describes the upload. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UploadMetadata type UploadMetadata struct { _ struct{} `type:"structure"` // The signed headers. SignedHeaders map[string]string `type:"map"` // The URL of the upload. UploadUrl *string `min:"1" type:"string"` } // String returns the string representation func (s UploadMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UploadMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UploadMetadata) MarshalFields(e protocol.FieldEncoder) error { if len(s.SignedHeaders) > 0 { v := s.SignedHeaders metadata := protocol.Metadata{} ms0 := e.Map(protocol.BodyTarget, "SignedHeaders", metadata) ms0.Start() for k1, v1 := range v { ms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)}) } ms0.End() } if s.UploadUrl != nil { v := *s.UploadUrl metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "UploadUrl", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Describes a user. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/User type User struct { _ struct{} `type:"structure"` // The time when the user was created. CreatedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The email address of the user. EmailAddress *string `min:"1" type:"string"` // The given name of the user. GivenName *string `min:"1" type:"string"` // The ID of the user. Id *string `min:"1" type:"string"` // The locale of the user. Locale LocaleType `type:"string" enum:"true"` // The time when the user was modified. ModifiedTimestamp *time.Time `type:"timestamp" timestampFormat:"unix"` // The ID of the organization. OrganizationId *string `min:"1" type:"string"` // The ID of the recycle bin folder. RecycleBinFolderId *string `min:"1" type:"string"` // The ID of the root folder. RootFolderId *string `min:"1" type:"string"` // The status of the user. Status UserStatusType `type:"string" enum:"true"` // The storage for the user. Storage *UserStorageMetadata `type:"structure"` // The surname of the user. Surname *string `min:"1" type:"string"` // The time zone ID of the user. TimeZoneId *string `min:"1" type:"string"` // The type of user. Type UserType `type:"string" enum:"true"` // The login name of the user. Username *string `min:"1" type:"string"` } // String returns the string representation func (s User) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s User) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s User) MarshalFields(e protocol.FieldEncoder) error { if s.CreatedTimestamp != nil { v := *s.CreatedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "CreatedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.EmailAddress != nil { v := *s.EmailAddress metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "EmailAddress", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.GivenName != nil { v := *s.GivenName metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "GivenName", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Locale) > 0 { v := s.Locale metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Locale", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.ModifiedTimestamp != nil { v := *s.ModifiedTimestamp metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "ModifiedTimestamp", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata) } if s.OrganizationId != nil { v := *s.OrganizationId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "OrganizationId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.RecycleBinFolderId != nil { v := *s.RecycleBinFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "RecycleBinFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.RootFolderId != nil { v := *s.RootFolderId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "RootFolderId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Status) > 0 { v := s.Status metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Status", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.Storage != nil { v := s.Storage metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "Storage", v, metadata) } if s.Surname != nil { v := *s.Surname metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Surname", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.TimeZoneId != nil { v := *s.TimeZoneId metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "TimeZoneId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if len(s.Type) > 0 { v := s.Type metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Type", protocol.QuotedValue{ValueMarshaler: v}, metadata) } if s.Username != nil { v := *s.Username metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Username", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Describes the metadata of the user. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UserMetadata type UserMetadata struct { _ struct{} `type:"structure"` // The email address of the user. EmailAddress *string `min:"1" type:"string"` // The given name of the user before a rename operation. GivenName *string `min:"1" type:"string"` // The ID of the user. Id *string `min:"1" type:"string"` // The surname of the user. Surname *string `min:"1" type:"string"` // The name of the user. Username *string `min:"1" type:"string"` } // String returns the string representation func (s UserMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UserMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UserMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.EmailAddress != nil { v := *s.EmailAddress metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "EmailAddress", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.GivenName != nil { v := *s.GivenName metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "GivenName", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Id", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Surname != nil { v := *s.Surname metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Surname", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } if s.Username != nil { v := *s.Username metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Username", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil } // Describes the storage for a user. // Please also see https://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/UserStorageMetadata type UserStorageMetadata struct { _ struct{} `type:"structure"` // The storage for a user. StorageRule *StorageRuleType `type:"structure"` // The amount of storage used, in bytes. StorageUtilizedInBytes *int64 `type:"long"` } // String returns the string representation func (s UserStorageMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s UserStorageMetadata) GoString() string { return s.String() } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UserStorageMetadata) MarshalFields(e protocol.FieldEncoder) error { if s.StorageRule != nil { v := s.StorageRule metadata := protocol.Metadata{} e.SetFields(protocol.BodyTarget, "StorageRule", v, metadata) } if s.StorageUtilizedInBytes != nil { v := *s.StorageUtilizedInBytes metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "StorageUtilizedInBytes", protocol.Int64Value(v), metadata) } return nil } type ActivityType string // Enum values for ActivityType const ( ActivityTypeDocumentCheckedIn ActivityType = "DOCUMENT_CHECKED_IN" ActivityTypeDocumentCheckedOut ActivityType = "DOCUMENT_CHECKED_OUT" ActivityTypeDocumentRenamed ActivityType = "DOCUMENT_RENAMED" ActivityTypeDocumentVersionUploaded ActivityType = "DOCUMENT_VERSION_UPLOADED" ActivityTypeDocumentVersionDeleted ActivityType = "DOCUMENT_VERSION_DELETED" ActivityTypeDocumentVersionViewed ActivityType = "DOCUMENT_VERSION_VIEWED" ActivityTypeDocumentVersionDownloaded ActivityType = "DOCUMENT_VERSION_DOWNLOADED" ActivityTypeDocumentRecycled ActivityType = "DOCUMENT_RECYCLED" ActivityTypeDocumentRestored ActivityType = "DOCUMENT_RESTORED" ActivityTypeDocumentReverted ActivityType = "DOCUMENT_REVERTED" ActivityTypeDocumentShared ActivityType = "DOCUMENT_SHARED" ActivityTypeDocumentUnshared ActivityType = "DOCUMENT_UNSHARED" ActivityTypeDocumentSharePermissionChanged ActivityType = "DOCUMENT_SHARE_PERMISSION_CHANGED" ActivityTypeDocumentShareableLinkCreated ActivityType = "DOCUMENT_SHAREABLE_LINK_CREATED" ActivityTypeDocumentShareableLinkRemoved ActivityType = "DOCUMENT_SHAREABLE_LINK_REMOVED" ActivityTypeDocumentShareableLinkPermissionChanged ActivityType = "DOCUMENT_SHAREABLE_LINK_PERMISSION_CHANGED" ActivityTypeDocumentMoved ActivityType = "DOCUMENT_MOVED" ActivityTypeDocumentCommentAdded ActivityType = "DOCUMENT_COMMENT_ADDED" ActivityTypeDocumentCommentDeleted ActivityType = "DOCUMENT_COMMENT_DELETED" ActivityTypeDocumentAnnotationAdded ActivityType = "DOCUMENT_ANNOTATION_ADDED" ActivityTypeDocumentAnnotationDeleted ActivityType = "DOCUMENT_ANNOTATION_DELETED" ActivityTypeFolderCreated ActivityType = "FOLDER_CREATED" ActivityTypeFolderDeleted ActivityType = "FOLDER_DELETED" ActivityTypeFolderRenamed ActivityType = "FOLDER_RENAMED" ActivityTypeFolderRecycled ActivityType = "FOLDER_RECYCLED" ActivityTypeFolderRestored ActivityType = "FOLDER_RESTORED" ActivityTypeFolderShared ActivityType = "FOLDER_SHARED" ActivityTypeFolderUnshared ActivityType = "FOLDER_UNSHARED" ActivityTypeFolderSharePermissionChanged ActivityType = "FOLDER_SHARE_PERMISSION_CHANGED" ActivityTypeFolderShareableLinkCreated ActivityType = "FOLDER_SHAREABLE_LINK_CREATED" ActivityTypeFolderShareableLinkRemoved ActivityType = "FOLDER_SHAREABLE_LINK_REMOVED" ActivityTypeFolderShareableLinkPermissionChanged ActivityType = "FOLDER_SHAREABLE_LINK_PERMISSION_CHANGED" ActivityTypeFolderMoved ActivityType = "FOLDER_MOVED" ) func (enum ActivityType) MarshalValue() (string, error) { return string(enum), nil } func (enum ActivityType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type BooleanEnumType string // Enum values for BooleanEnumType const ( BooleanEnumTypeTrue BooleanEnumType = "TRUE" BooleanEnumTypeFalse BooleanEnumType = "FALSE" ) func (enum BooleanEnumType) MarshalValue() (string, error) { return string(enum), nil } func (enum BooleanEnumType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type CommentStatusType string // Enum values for CommentStatusType const ( CommentStatusTypeDraft CommentStatusType = "DRAFT" CommentStatusTypePublished CommentStatusType = "PUBLISHED" CommentStatusTypeDeleted CommentStatusType = "DELETED" ) func (enum CommentStatusType) MarshalValue() (string, error) { return string(enum), nil } func (enum CommentStatusType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type CommentVisibilityType string // Enum values for CommentVisibilityType const ( CommentVisibilityTypePublic CommentVisibilityType = "PUBLIC" CommentVisibilityTypePrivate CommentVisibilityType = "PRIVATE" ) func (enum CommentVisibilityType) MarshalValue() (string, error) { return string(enum), nil } func (enum CommentVisibilityType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type DocumentSourceType string // Enum values for DocumentSourceType const ( DocumentSourceTypeOriginal DocumentSourceType = "ORIGINAL" DocumentSourceTypeWithComments DocumentSourceType = "WITH_COMMENTS" ) func (enum DocumentSourceType) MarshalValue() (string, error) { return string(enum), nil } func (enum DocumentSourceType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type DocumentStatusType string // Enum values for DocumentStatusType const ( DocumentStatusTypeInitialized DocumentStatusType = "INITIALIZED" DocumentStatusTypeActive DocumentStatusType = "ACTIVE" ) func (enum DocumentStatusType) MarshalValue() (string, error) { return string(enum), nil } func (enum DocumentStatusType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type DocumentThumbnailType string // Enum values for DocumentThumbnailType const ( DocumentThumbnailTypeSmall DocumentThumbnailType = "SMALL" DocumentThumbnailTypeSmallHq DocumentThumbnailType = "SMALL_HQ" DocumentThumbnailTypeLarge DocumentThumbnailType = "LARGE" ) func (enum DocumentThumbnailType) MarshalValue() (string, error) { return string(enum), nil } func (enum DocumentThumbnailType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type DocumentVersionStatus string // Enum values for DocumentVersionStatus const ( DocumentVersionStatusActive DocumentVersionStatus = "ACTIVE" ) func (enum DocumentVersionStatus) MarshalValue() (string, error) { return string(enum), nil } func (enum DocumentVersionStatus) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type FolderContentType string // Enum values for FolderContentType const ( FolderContentTypeAll FolderContentType = "ALL" FolderContentTypeDocument FolderContentType = "DOCUMENT" FolderContentTypeFolder FolderContentType = "FOLDER" ) func (enum FolderContentType) MarshalValue() (string, error) { return string(enum), nil } func (enum FolderContentType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type LocaleType string // Enum values for LocaleType const ( LocaleTypeEn LocaleType = "en" LocaleTypeFr LocaleType = "fr" LocaleTypeKo LocaleType = "ko" LocaleTypeDe LocaleType = "de" LocaleTypeEs LocaleType = "es" LocaleTypeJa LocaleType = "ja" LocaleTypeRu LocaleType = "ru" LocaleTypeZhCn LocaleType = "zh_CN" LocaleTypeZhTw LocaleType = "zh_TW" LocaleTypePtBr LocaleType = "pt_BR" LocaleTypeDefault LocaleType = "default" ) func (enum LocaleType) MarshalValue() (string, error) { return string(enum), nil } func (enum LocaleType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type OrderType string // Enum values for OrderType const ( OrderTypeAscending OrderType = "ASCENDING" OrderTypeDescending OrderType = "DESCENDING" ) func (enum OrderType) MarshalValue() (string, error) { return string(enum), nil } func (enum OrderType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type PrincipalType string // Enum values for PrincipalType const ( PrincipalTypeUser PrincipalType = "USER" PrincipalTypeGroup PrincipalType = "GROUP" PrincipalTypeInvite PrincipalType = "INVITE" PrincipalTypeAnonymous PrincipalType = "ANONYMOUS" PrincipalTypeOrganization PrincipalType = "ORGANIZATION" ) func (enum PrincipalType) MarshalValue() (string, error) { return string(enum), nil } func (enum PrincipalType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type ResourceCollectionType string // Enum values for ResourceCollectionType const ( ResourceCollectionTypeSharedWithMe ResourceCollectionType = "SHARED_WITH_ME" ) func (enum ResourceCollectionType) MarshalValue() (string, error) { return string(enum), nil } func (enum ResourceCollectionType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type ResourceSortType string // Enum values for ResourceSortType const ( ResourceSortTypeDate ResourceSortType = "DATE" ResourceSortTypeName ResourceSortType = "NAME" ) func (enum ResourceSortType) MarshalValue() (string, error) { return string(enum), nil } func (enum ResourceSortType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type ResourceStateType string // Enum values for ResourceStateType const ( ResourceStateTypeActive ResourceStateType = "ACTIVE" ResourceStateTypeRestoring ResourceStateType = "RESTORING" ResourceStateTypeRecycling ResourceStateType = "RECYCLING" ResourceStateTypeRecycled ResourceStateType = "RECYCLED" ) func (enum ResourceStateType) MarshalValue() (string, error) { return string(enum), nil } func (enum ResourceStateType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type ResourceType string // Enum values for ResourceType const ( ResourceTypeFolder ResourceType = "FOLDER" ResourceTypeDocument ResourceType = "DOCUMENT" ) func (enum ResourceType) MarshalValue() (string, error) { return string(enum), nil } func (enum ResourceType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type RolePermissionType string // Enum values for RolePermissionType const ( RolePermissionTypeDirect RolePermissionType = "DIRECT" RolePermissionTypeInherited RolePermissionType = "INHERITED" ) func (enum RolePermissionType) MarshalValue() (string, error) { return string(enum), nil } func (enum RolePermissionType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type RoleType string // Enum values for RoleType const ( RoleTypeViewer RoleType = "VIEWER" RoleTypeContributor RoleType = "CONTRIBUTOR" RoleTypeOwner RoleType = "OWNER" RoleTypeCoowner RoleType = "COOWNER" ) func (enum RoleType) MarshalValue() (string, error) { return string(enum), nil } func (enum RoleType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type ShareStatusType string // Enum values for ShareStatusType const ( ShareStatusTypeSuccess ShareStatusType = "SUCCESS" ShareStatusTypeFailure ShareStatusType = "FAILURE" ) func (enum ShareStatusType) MarshalValue() (string, error) { return string(enum), nil } func (enum ShareStatusType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type StorageType string // Enum values for StorageType const ( StorageTypeUnlimited StorageType = "UNLIMITED" StorageTypeQuota StorageType = "QUOTA" ) func (enum StorageType) MarshalValue() (string, error) { return string(enum), nil } func (enum StorageType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type SubscriptionProtocolType string // Enum values for SubscriptionProtocolType const ( SubscriptionProtocolTypeHttps SubscriptionProtocolType = "HTTPS" ) func (enum SubscriptionProtocolType) MarshalValue() (string, error) { return string(enum), nil } func (enum SubscriptionProtocolType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type SubscriptionType string // Enum values for SubscriptionType const ( SubscriptionTypeAll SubscriptionType = "ALL" ) func (enum SubscriptionType) MarshalValue() (string, error) { return string(enum), nil } func (enum SubscriptionType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type UserFilterType string // Enum values for UserFilterType const ( UserFilterTypeAll UserFilterType = "ALL" UserFilterTypeActivePending UserFilterType = "ACTIVE_PENDING" ) func (enum UserFilterType) MarshalValue() (string, error) { return string(enum), nil } func (enum UserFilterType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type UserSortType string // Enum values for UserSortType const ( UserSortTypeUserName UserSortType = "USER_NAME" UserSortTypeFullName UserSortType = "FULL_NAME" UserSortTypeStorageLimit UserSortType = "STORAGE_LIMIT" UserSortTypeUserStatus UserSortType = "USER_STATUS" UserSortTypeStorageUsed UserSortType = "STORAGE_USED" ) func (enum UserSortType) MarshalValue() (string, error) { return string(enum), nil } func (enum UserSortType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type UserStatusType string // Enum values for UserStatusType const ( UserStatusTypeActive UserStatusType = "ACTIVE" UserStatusTypeInactive UserStatusType = "INACTIVE" UserStatusTypePending UserStatusType = "PENDING" ) func (enum UserStatusType) MarshalValue() (string, error) { return string(enum), nil } func (enum UserStatusType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil } type UserType string // Enum values for UserType const ( UserTypeUser UserType = "USER" UserTypeAdmin UserType = "ADMIN" UserTypePoweruser UserType = "POWERUSER" UserTypeMinimaluser UserType = "MINIMALUSER" UserTypeWorkspacesuser UserType = "WORKSPACESUSER" ) func (enum UserType) MarshalValue() (string, error) { return string(enum), nil } func (enum UserType) MarshalValueBuf(b []byte) ([]byte, error) { b = b[0:0] return append(b, enum...), nil }
{ v := *s.Marker metadata := protocol.Metadata{} e.SetValue(protocol.BodyTarget, "Marker", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) }
refresh.py
"""The data store contains offline versions of the data so that you can run a demo version of the website without the vault keys, or simply develop parts of the website that don't require actively updated data without having to worry. This data is used for the actual website when the `USE_MOCK_DATA` config variable is True. It is useful for dev, but it should never be used in production. This file is a CLI to refresh the data store. You can run it with: `python flagging_site/data/_store/refresh.py` """ import os import sys from typing import Optional import click DATA_STORE_PATH = os.path.dirname(__file__) @click.command() @click.option('--vault_password', prompt=True, default=lambda: os.environ.get('VAULT_PASSWORD', None)) def
(vault_password: Optional[str] = None) -> None: """When run, this function runs all the functions that compose the data store. The app itself should not be running this function; in fact, this function will raise an error if the app is turned on. This should only be run from the command line or a Python console. """ os.environ['USE_MOCK_DATA'] = 'false' if vault_password: os.environ['VAULT_PASSWORD'] = vault_password from flask import current_app if current_app: raise Exception('The app should not be running when the data store is ' 'being refreshed.') from flagging_site.data.hobolink import get_live_hobolink_data from flagging_site.data.hobolink import HOBOLINK_STATIC_FILE_NAME get_live_hobolink_data('code_for_boston_export_21d')\ .to_pickle(os.path.join(DATA_STORE_PATH, HOBOLINK_STATIC_FILE_NAME)) from flagging_site.data.usgs import get_live_usgs_data from flagging_site.data.usgs import USGS_STATIC_FILE_NAME get_live_usgs_data()\ .to_pickle(os.path.join(DATA_STORE_PATH, USGS_STATIC_FILE_NAME)) if __name__ == '__main__': sys.path.append('.') refresh_data_store()
refresh_data_store
project.py
#------------------------------------------------------------------------------------------- # project.py # # Author : Felix Gonda # Date : July 10, 2015 # School : Harvard University # # Project : Master Thesis # An Interactive Deep Learning Toolkit for # Automatic Segmentation of Images # # Summary : This file contains database access layer implementation footer # sqlite3 #------------------------------------------------------------------------------------------- import os import sqlite3 as lite import sys import json import glob import time import uuid from datetime import datetime, date base_path = os.path.dirname(__file__) sys.path.insert(1,os.path.join(base_path, '../common')) from utility import Utility from paths import Paths from label import Label from image import Image class Project (object): CNN = 'CNN' MLP = 'MLP' UNET = 'UNET' INVALID = -1 ONLINE = 0 OFFLINE = 1 TrainTime = 15 # 15 seconds SyncTime = 20 # 20 seconds # create a new project object #---------------------------- def __init__(self, id, type, revision=0, baseModel='', patchSize=39, batchSize=16, learningRate=0.01, momentum=0.9, hiddenUnits=[500,500,500], nKernels=[48,48], kernelSizes=[5,5], threshold=0.5, mean=0.5, data_mean=0.5, data_std=1.0 ): self.activemode = Project.ONLINE self.id = id self.type = type self.baseModel = baseModel self.std = data_std self.mean = data_mean self.threshold = threshold self.patchSize = patchSize self.batchSize = batchSize self.learningRate = learningRate self.momentum = momentum self.hiddenUnits = hiddenUnits self.nKernels = nKernels self.kernelSizes = kernelSizes self.trainTime = Project.TrainTime self.syncTime = Project.SyncTime self.epochs = 100 self.labels = [] self.images = [] self.validation_images = [] def addLabel(self, index, name, r, g, b): self.labels.append( Label(index, name, r, g, b) ) def addImage(self, imageId, annFile=None, segFile=None, score=0.0, purpose='train'): image = Image( imageId ) image.purpose = purpose image.annotationFile = annFile image.segmentationFile = segFile image.traningScore = score self.images.append( image ) def toJson(self): data = {} data['id'] = self.id data['std'] = self.std data['mean'] = self.mean data['threshold'] = self.threshold data['training_mod_status'] = self.trainingStatus data['training_mod_status_str'] = Project.statusToStr( self.trainingStatus ) data['segmentation_mod_status'] = self.predictionStatus; data['segmentation_mod_status_str'] = Project.statusToStr( self.predictionStatus ) data['initial_model'] = self.baseModel data['model_type'] = self.type data['sample_size'] = self.patchSize data['learning_rate'] = self.learningRate data['momentum'] = self.momentum data['batch_size'] = self.batchSize data['epochs'] = self.epochs data['train_time'] = self.trainTime data['sync_time'] = self.syncTime data['model_mod_time'] = self.modelTime data['locked'] = self.locked data['labels'] = [l.toJson() for l in self.labels ] data['hidden_layers'] = json.dumps( self.hiddenUnits ) data['num_kernels'] = json.dumps( self.nKernels ) data['kernel_sizes'] = json.dumps( self.kernelSizes ) data['images'] = [i.toJson() for i in self.images ] data['validation_images'] = [i.toJson() for i in self.validation_images ] data['offline'] = self.offline data['online'] = self.online data['baseline'] = self.baseline data['stats'] = [ s.toJson() for s in self.stats ] return data @staticmethod def fromJson(data): project = Project(id=data['id'], type=data['model_type']) project.baseModel = data['initial_model'] project.std = data['std'] project.mean = data['mean'] project.threshold = data['threshold'] project.patchSize = data['sample_size'] project.batchSize = data['batch_size'] project.learningRate = data['learning_rate'] project.momentum = data['momentum'] project.trainTime = data['train_time'] project.syncTime = data['sync_time'] print 'hidden_layers:', data['hidden_layers'] print 'num_kernels:', data['num_kernels'] print 'kernel_sizes:', data['kernel_sizes'], type(data['kernel_sizes']) project.hiddenUnits = data['hidden_layers'] #json.loads( data['hidden_layers'] ) project.nKernels = data['num_kernels'] #jjson.loads( data['num_kernels'] ) project.kernelSizes = data['kernel_sizes'] #jjson.loads( data['kernel_sizes'] ) return project def
(self): if len(self.labels) == 0: print 'no labels found...' return False if self.type == 'MLP': if len(self.hiddenUnits) == 0: print 'no hidden layer units found...' return False if self.type == 'CNN': if len(self.nKernels) == 0: print 'number of kernels not found...' return False elif len(self.kernelSizes) == 0: print 'kernel sizes not found...' return False return True @staticmethod def statusToStr( status ): if status == 1: return 'Active' elif status == 2: return 'Pending Annotations' else: return 'Inactive'
isTrainable
test_int.py
import struct import unittest from typing import List import pyparcel DATA: List[int] = [ -1 << 31, -1000, -57, -26, -20, -5, -2,
2, 5, 20, 57, 1000, (1 << 31) - 1, ] class MyTestCase(unittest.TestCase): def test_pack(self): for i in DATA: self.assertEqual(pyparcel.pack(i), struct.pack("i", i)) def test_pack_unpack(self): for i in DATA: self.assertEqual(i, pyparcel.unpack(pyparcel.pack(i), int())) if __name__ == "__main__": unittest.main()
-1, 0, 1,
tsc.rs
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. use crate::ast::parse; use crate::ast::Location; use crate::diagnostics::Diagnostics; use crate::disk_cache::DiskCache; use crate::file_fetcher::SourceFile; use crate::file_fetcher::SourceFileFetcher; use crate::flags::Flags; use crate::js; use crate::media_type::MediaType; use crate::module_graph::ModuleGraph; use crate::module_graph::ModuleGraphLoader; use crate::permissions::Permissions; use crate::program_state::ProgramState; use crate::tsc_config; use crate::version; use deno_core::error::generic_error; use deno_core::error::AnyError; use deno_core::error::JsError; use deno_core::json_op_sync; use deno_core::serde_json; use deno_core::serde_json::json; use deno_core::serde_json::Value; use deno_core::url::Url; use deno_core::JsRuntime; use deno_core::ModuleSpecifier; use deno_core::RuntimeOptions; use log::debug; use regex::Regex; use serde::Deserialize; use serde::Serialize; use serde::Serializer; use sourcemap::SourceMap; use std::collections::HashMap; use std::collections::HashSet; use std::fs; use std::io; use std::ops::Deref; use std::path::PathBuf; use std::str; use std::sync::Arc; use std::sync::Mutex; use swc_common::comments::Comment; use swc_common::comments::CommentKind; use swc_ecmascript::dep_graph; pub const AVAILABLE_LIBS: &[&str] = &[ "deno.ns", "deno.window", "deno.worker", "deno.shared_globals", "deno.unstable", "dom", "dom.iterable", "es5", "es6", "esnext", "es2020", "es2020.full", "es2019", "es2019.full", "es2018", "es2018.full", "es2017", "es2017.full", "es2016", "es2016.full", "es2015", "es2015.collection", "es2015.core", "es2015.generator", "es2015.iterable", "es2015.promise", "es2015.proxy", "es2015.reflect", "es2015.symbol", "es2015.symbol.wellknown", "es2016.array.include", "es2017.intl", "es2017.object", "es2017.sharedmemory", "es2017.string", "es2017.typedarrays", "es2018.asyncgenerator", "es2018.asynciterable", "es2018.intl", "es2018.promise", "es2018.regexp", "es2019.array", "es2019.object", "es2019.string", "es2019.symbol", "es2020.bigint", "es2020.promise", "es2020.string", "es2020.symbol.wellknown", "esnext.array", "esnext.asynciterable", "esnext.bigint", "esnext.intl", "esnext.promise", "esnext.string", "esnext.symbol", "esnext.weakref", "scripthost", "webworker", "webworker.importscripts", ]; #[derive(Debug, Clone)] pub struct CompiledModule { pub code: String, pub name: String, } lazy_static! { /// Matches the `@deno-types` pragma. static ref DENO_TYPES_RE: Regex = Regex::new(r#"(?i)^\s*@deno-types\s*=\s*(?:["']([^"']+)["']|(\S+))"#) .unwrap(); /// Matches a `/// <reference ... />` comment reference. static ref TRIPLE_SLASH_REFERENCE_RE: Regex = Regex::new(r"(?i)^/\s*<reference\s.*?/>").unwrap(); /// Matches a path reference, which adds a dependency to a module static ref PATH_REFERENCE_RE: Regex = Regex::new(r#"(?i)\spath\s*=\s*["']([^"']*)["']"#).unwrap(); /// Matches a types reference, which for JavaScript files indicates the /// location of types to use when type checking a program that includes it as /// a dependency. static ref TYPES_REFERENCE_RE: Regex = Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap(); /// Matches a lib reference. static ref LIB_REFERENCE_RE: Regex = Regex::new(r#"(?i)\slib\s*=\s*["']([^"']*)["']"#).unwrap(); } #[derive(Clone)] pub enum TargetLib { Main, Worker, } /// Struct which represents the state of the compiler /// configuration where the first is canonical name for the configuration file, /// second is a vector of the bytes of the contents of the configuration file, /// third is bytes of the hash of contents. #[derive(Clone)] pub struct CompilerConfig { pub path: Option<PathBuf>, pub options: Value, pub maybe_ignored_options: Option<tsc_config::IgnoredCompilerOptions>, pub hash: String, pub compile_js: bool, } impl CompilerConfig { /// Take the passed flag and resolve the file name relative to the cwd. pub fn load(maybe_config_path: Option<String>) -> Result<Self, AnyError> { if maybe_config_path.is_none() { return Ok(Self { path: Some(PathBuf::new()), options: json!({}), maybe_ignored_options: None, hash: "".to_string(), compile_js: false, }); } let raw_config_path = maybe_config_path.unwrap(); debug!("Compiler config file: {}", raw_config_path); let cwd = std::env::current_dir().unwrap(); let config_file = cwd.join(raw_config_path); // Convert the PathBuf to a canonicalized string. This is needed by the // compiler to properly deal with the configuration. let config_path = config_file.canonicalize().map_err(|_| { io::Error::new( io::ErrorKind::InvalidInput, format!( "Could not find the config file: {}", config_file.to_string_lossy() ), ) })?; // Load the contents of the configuration file debug!("Attempt to load config: {}", config_path.to_str().unwrap()); let config_bytes = fs::read(&config_file)?; let config_hash = crate::checksum::gen(&[&config_bytes]); let config_str = String::from_utf8(config_bytes)?; let (options, maybe_ignored_options) = if config_str.is_empty() { (json!({}), None) } else { tsc_config::parse_config(&config_str, &config_path)? }; // If `checkJs` is set to true in `compilerOptions` then we're gonna be compiling // JavaScript files as well let compile_js = options["checkJs"].as_bool().unwrap_or(false); Ok(Self { path: Some(config_path), options, maybe_ignored_options, hash: config_hash, compile_js, }) } } /// Information associated with compiled file in cache. /// version_hash is used to validate versions of the file /// and could be used to remove stale file in cache. #[derive(Deserialize, Serialize)] pub struct CompiledFileMetadata { pub version_hash: String, } impl CompiledFileMetadata { pub fn to_json_string(&self) -> Result<String, serde_json::Error> { serde_json::to_string(self) } } /// Emit a SHA256 hash based on source code, deno version and TS config. /// Used to check if a recompilation for source code is needed. fn source_code_version_hash( source_code: &[u8], version: &str, config_hash: &[u8], ) -> String { crate::checksum::gen(&[source_code, version.as_bytes(), config_hash]) } pub struct TsCompilerInner { pub file_fetcher: SourceFileFetcher, pub flags: Flags, pub config: CompilerConfig, pub disk_cache: DiskCache, /// Set of all URLs that have been compiled. This prevents double /// compilation of module. pub compiled: Mutex<HashSet<Url>>, /// This setting is controlled by `--reload` flag. Unless the flag /// is provided disk cache is used. pub use_disk_cache: bool, /// This setting is controlled by `compilerOptions.checkJs` pub compile_js: bool, } #[derive(Clone)] pub struct TsCompiler(Arc<TsCompilerInner>); impl Deref for TsCompiler { type Target = TsCompilerInner; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Stat { key: String, value: f64, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct EmittedSource { filename: String, contents: String, } // TODO(bartlomieju): possible deduplicate once TS refactor is stabilized #[derive(Deserialize)] #[serde(rename_all = "camelCase")] #[allow(unused)] struct RuntimeBundleResponse { diagnostics: Diagnostics, output: String, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct RuntimeCompileResponse { diagnostics: Diagnostics, emit_map: HashMap<String, EmittedSource>, } impl TsCompiler { pub fn new( file_fetcher: SourceFileFetcher, flags: Flags, disk_cache: DiskCache, ) -> Result<Self, AnyError> { let config = CompilerConfig::load(flags.config_path.clone())?; let use_disk_cache = !flags.reload; Ok(TsCompiler(Arc::new(TsCompilerInner { file_fetcher, flags, disk_cache, compile_js: config.compile_js, config, compiled: Mutex::new(HashSet::new()), use_disk_cache, }))) } /// Mark given module URL as compiled to avoid multiple compilations of same /// module in single run. fn mark_compiled(&self, url: &Url) { let mut c = self.compiled.lock().unwrap(); c.insert(url.clone()); } fn cache_emitted_files( &self, emit_map: HashMap<String, EmittedSource>, ) -> std::io::Result<()> { for (emitted_name, source) in emit_map.iter() { let specifier = ModuleSpecifier::resolve_url(&source.filename) .expect("Should be a valid module specifier"); let source_file = self .file_fetcher .fetch_cached_source_file(&specifier, Permissions::allow_all()) .expect("Source file not found"); // NOTE: JavaScript files are only cached to disk if `checkJs` // option in on if source_file.media_type == MediaType::JavaScript && !self.compile_js { continue; } if emitted_name.ends_with(".map") { self.cache_source_map(&specifier, &source.contents)?; } else if emitted_name.ends_with(".js") { self.cache_compiled_file(&specifier, source_file, &source.contents)?; } else { panic!("Trying to cache unknown file type {}", emitted_name); } } Ok(()) } /// Save compiled JS file for given TS module to on-disk cache. /// /// Along compiled file a special metadata file is saved as well containing /// hash that can be validated to avoid unnecessary recompilation. fn cache_compiled_file( &self, module_specifier: &ModuleSpecifier, source_file: SourceFile, contents: &str, ) -> std::io::Result<()> { let js_key = self .disk_cache .get_cache_filename_with_extension(module_specifier.as_url(), "js"); self.disk_cache.set(&js_key, contents.as_bytes())?; self.mark_compiled(module_specifier.as_url()); let version_hash = source_code_version_hash( &source_file.source_code.as_bytes(), version::DENO, &self.config.hash.as_bytes(), ); let compiled_file_metadata = CompiledFileMetadata { version_hash }; let meta_key = self .disk_cache .get_cache_filename_with_extension(module_specifier.as_url(), "meta"); self.disk_cache.set( &meta_key, compiled_file_metadata.to_json_string()?.as_bytes(), ) } /// Save source map file for given TS module to on-disk cache. fn cache_source_map( &self, module_specifier: &ModuleSpecifier, contents: &str, ) -> std::io::Result<()> { let js_key = self .disk_cache .get_cache_filename_with_extension(module_specifier.as_url(), "js"); let js_path = self.disk_cache.location.join(js_key); let js_file_url = Url::from_file_path(js_path).expect("Bad file URL for file"); let source_map_key = self .disk_cache .get_cache_filename_with_extension(module_specifier.as_url(), "js.map"); let mut sm = SourceMap::from_slice(contents.as_bytes()) .expect("Invalid source map content"); sm.set_file(Some(&js_file_url.to_string())); sm.set_source(0, &module_specifier.to_string()); let mut output: Vec<u8> = vec![]; sm.to_writer(&mut output) .expect("Failed to write source map"); self.disk_cache.set(&source_map_key, &output) } } #[derive(Debug, Deserialize)] struct CreateHashArgs { data: String, } fn execute_in_tsc( program_state: Arc<ProgramState>, req: String, ) -> Result<String, AnyError> { let mut js_runtime = JsRuntime::new(RuntimeOptions { startup_snapshot: Some(js::compiler_isolate_init()), ..Default::default() }); let debug_flag = program_state .flags .log_level .map_or(false, |l| l == log::Level::Debug); let response = Arc::new(Mutex::new(None)); { js_runtime.register_op( "op_fetch_asset", crate::op_fetch_asset::op_fetch_asset(HashMap::default()), ); let res = response.clone(); js_runtime.register_op( "op_compiler_respond", json_op_sync(move |_state, args, _bufs| { let mut response_slot = res.lock().unwrap(); let replaced_value = response_slot.replace(args.to_string()); assert!( replaced_value.is_none(), "op_compiler_respond found unexpected existing compiler output", ); Ok(json!({})) }), ); js_runtime.register_op( "op_create_hash", json_op_sync(move |_s, args, _bufs| { let v: CreateHashArgs = serde_json::from_value(args)?; let hash = crate::checksum::gen(&[v.data.as_bytes()]); Ok(json!({ "hash": hash })) }), ); } let bootstrap_script = format!( "globalThis.startup({{ debugFlag: {}, legacy: true }})", debug_flag ); js_runtime.execute("<compiler>", &bootstrap_script)?; let script = format!("globalThis.tsCompilerOnMessage({{ data: {} }});", req); js_runtime.execute("<compiler>", &script)?; let maybe_response = response.lock().unwrap().take(); assert!( maybe_response.is_some(), "Unexpected missing response from TS compiler" ); Ok(maybe_response.unwrap()) } async fn create_runtime_module_graph( program_state: &Arc<ProgramState>, permissions: Permissions, root_name: &str, sources: &Option<HashMap<String, String>>, type_files: Vec<String>, ) -> Result<(Vec<String>, ModuleGraph), AnyError> { let mut root_names = vec![]; let mut module_graph_loader = ModuleGraphLoader::new( program_state.file_fetcher.clone(), None, permissions, false, false, ); if let Some(s_map) = sources { root_names.push(root_name.to_string()); module_graph_loader.build_local_graph(root_name, s_map)?; } else { let module_specifier = ModuleSpecifier::resolve_import(root_name, "<unknown>")?; root_names.push(module_specifier.to_string()); module_graph_loader .add_to_graph(&module_specifier, None) .await?; } // download all additional files from TSconfig and add them to root_names for type_file in type_files { let type_specifier = ModuleSpecifier::resolve_url_or_path(&type_file)?; module_graph_loader .add_to_graph(&type_specifier, None) .await?; root_names.push(type_specifier.to_string()) } Ok((root_names, module_graph_loader.get_graph())) } fn extract_js_error(error: AnyError) -> AnyError { match error.downcast::<JsError>() { Ok(js_error) => { let msg = format!("Error in TS compiler:\n{}", js_error); generic_error(msg) } Err(error) => error, } } /// This function is used by `Deno.compile()` API. pub async fn runtime_compile( program_state: &Arc<ProgramState>, permissions: Permissions, root_name: &str, sources: &Option<HashMap<String, String>>, maybe_options: &Option<String>, ) -> Result<Value, AnyError> { let mut user_options = if let Some(options) = maybe_options { tsc_config::parse_raw_config(options)? } else { json!({}) }; // Intentionally calling "take()" to replace value with `null` - otherwise TSC will try to load that file // using `fileExists` API let type_files = if let Some(types) = user_options["types"].take().as_array() { types .iter() .map(|type_value| type_value.as_str().unwrap_or("").to_string()) .filter(|type_str| !type_str.is_empty()) .collect() } else { vec![] }; let unstable = program_state.flags.unstable; let mut lib = vec![]; if let Some(user_libs) = user_options["lib"].take().as_array() { let libs = user_libs .iter() .map(|type_value| type_value.as_str().unwrap_or("").to_string()) .filter(|type_str| !type_str.is_empty()) .collect::<Vec<String>>(); lib.extend(libs); } else { lib.push("deno.window".to_string()); } if unstable { lib.push("deno.unstable".to_string()); } let mut compiler_options = json!({ "allowJs": false, "allowNonTsExtensions": true, "checkJs": false, "esModuleInterop": true, "isolatedModules": true, "jsx": "react", "module": "esnext", "sourceMap": true, "strict": true, "removeComments": true, "target": "esnext", }); tsc_config::json_merge(&mut compiler_options, &user_options); tsc_config::json_merge(&mut compiler_options, &json!({ "lib": lib })); let (root_names, module_graph) = create_runtime_module_graph( &program_state, permissions.clone(), root_name, sources, type_files, ) .await?; let module_graph_json = serde_json::to_value(module_graph).expect("Failed to serialize data"); let req_msg = json!({ "type": CompilerRequestType::RuntimeCompile, "target": "runtime", "rootNames": root_names, "sourceFileMap": module_graph_json, "compilerOptions": compiler_options, }) .to_string(); let compiler = program_state.ts_compiler.clone(); let json_str = execute_in_tsc(program_state.clone(), req_msg).map_err(extract_js_error)?; let response: RuntimeCompileResponse = serde_json::from_str(&json_str)?; if response.diagnostics.0.is_empty() && sources.is_none() { compiler.cache_emitted_files(response.emit_map)?; } // We're returning `Ok()` instead of `Err()` because it's not runtime // error if there were diagnostics produced; we want to let user handle // diagnostics in the runtime. Ok(serde_json::from_str::<Value>(&json_str).unwrap()) } /// This function is used by `Deno.bundle()` API. pub async fn runtime_bundle( program_state: &Arc<ProgramState>, permissions: Permissions, root_name: &str, sources: &Option<HashMap<String, String>>, maybe_options: &Option<String>, ) -> Result<Value, AnyError> { let mut user_options = if let Some(options) = maybe_options { tsc_config::parse_raw_config(options)? } else { json!({}) }; // Intentionally calling "take()" to replace value with `null` - otherwise TSC will try to load that file // using `fileExists` API let type_files = if let Some(types) = user_options["types"].take().as_array() { types .iter() .map(|type_value| type_value.as_str().unwrap_or("").to_string()) .filter(|type_str| !type_str.is_empty()) .collect() } else { vec![] }; let (root_names, module_graph) = create_runtime_module_graph( &program_state, permissions.clone(), root_name, sources, type_files, ) .await?; let module_graph_json = serde_json::to_value(module_graph).expect("Failed to serialize data"); let unstable = program_state.flags.unstable; let mut lib = vec![]; if let Some(user_libs) = user_options["lib"].take().as_array() { let libs = user_libs .iter() .map(|type_value| type_value.as_str().unwrap_or("").to_string()) .filter(|type_str| !type_str.is_empty()) .collect::<Vec<String>>(); lib.extend(libs);
if unstable { lib.push("deno.unstable".to_string()); } let mut compiler_options = json!({ "allowJs": false, "allowNonTsExtensions": true, "checkJs": false, "esModuleInterop": true, "jsx": "react", "module": "esnext", "outDir": null, "sourceMap": true, "strict": true, "removeComments": true, "target": "esnext", }); let bundler_options = json!({ "allowJs": true, "inlineSourceMap": false, "module": "system", "outDir": null, "outFile": "deno:///bundle.js", // disabled until we have effective way to modify source maps "sourceMap": false, }); tsc_config::json_merge(&mut compiler_options, &user_options); tsc_config::json_merge(&mut compiler_options, &json!({ "lib": lib })); tsc_config::json_merge(&mut compiler_options, &bundler_options); let req_msg = json!({ "type": CompilerRequestType::RuntimeBundle, "target": "runtime", "rootNames": root_names, "sourceFileMap": module_graph_json, "compilerOptions": compiler_options, }) .to_string(); let json_str = execute_in_tsc(program_state.clone(), req_msg).map_err(extract_js_error)?; let _response: RuntimeBundleResponse = serde_json::from_str(&json_str)?; // We're returning `Ok()` instead of `Err()` because it's not runtime // error if there were diagnostics produced; we want to let user handle // diagnostics in the runtime. Ok(serde_json::from_str::<Value>(&json_str).unwrap()) } /// This function is used by `Deno.transpileOnly()` API. pub async fn runtime_transpile( program_state: Arc<ProgramState>, sources: &HashMap<String, String>, maybe_options: &Option<String>, ) -> Result<Value, AnyError> { let user_options = if let Some(options) = maybe_options { tsc_config::parse_raw_config(options)? } else { json!({}) }; let mut compiler_options = json!({ "esModuleInterop": true, "module": "esnext", "sourceMap": true, "scriptComments": true, "target": "esnext", }); tsc_config::json_merge(&mut compiler_options, &user_options); let req_msg = json!({ "type": CompilerRequestType::RuntimeTranspile, "sources": sources, "compilerOptions": compiler_options, }) .to_string(); let json_str = execute_in_tsc(program_state, req_msg).map_err(extract_js_error)?; let v = serde_json::from_str::<Value>(&json_str) .expect("Error decoding JSON string."); Ok(v) } #[derive(Clone, Debug, PartialEq)] pub struct ImportDesc { pub specifier: String, pub deno_types: Option<String>, pub location: Location, } #[derive(Clone, Debug, PartialEq)] pub enum TsReferenceKind { Lib, Types, Path, } #[derive(Clone, Debug, PartialEq)] pub struct TsReferenceDesc { pub kind: TsReferenceKind, pub specifier: String, pub location: Location, } // TODO(bartlomieju): handle imports in ambient contexts/TS modules /// This function is a port of `ts.preProcessFile()` /// /// Additionally it captures `@deno-types` references directly /// preceeding `import .. from` and `export .. from` statements. pub fn pre_process_file( file_name: &str, media_type: MediaType, source_code: &str, analyze_dynamic_imports: bool, ) -> Result<(Vec<ImportDesc>, Vec<TsReferenceDesc>), AnyError> { let specifier = ModuleSpecifier::resolve_url_or_path(file_name)?; let module = parse(&specifier, source_code, &media_type)?; let dependency_descriptors = module.analyze_dependencies(); // for each import check if there's relevant @deno-types directive let imports = dependency_descriptors .iter() .filter(|desc| desc.kind != dep_graph::DependencyKind::Require) .filter(|desc| { if analyze_dynamic_imports { return true; } !desc.is_dynamic }) .map(|desc| { let deno_types = get_deno_types(&desc.leading_comments); ImportDesc { specifier: desc.specifier.to_string(), deno_types, location: Location { filename: file_name.to_string(), col: desc.col, line: desc.line, }, } }) .collect(); // analyze comment from beginning of the file and find TS directives let comments = module.get_leading_comments(); let mut references = vec![]; for comment in comments { if comment.kind != CommentKind::Line { continue; } let text = comment.text.to_string(); if let Some((kind, specifier)) = parse_ts_reference(text.trim()) { let location = module.get_location(&comment.span); references.push(TsReferenceDesc { kind, specifier, location, }); } } Ok((imports, references)) } fn get_deno_types(comments: &[Comment]) -> Option<String> { if comments.is_empty() { return None; } // @deno-types must directly prepend import statement - hence // checking last comment for span let last = comments.last().unwrap(); let comment = last.text.trim_start(); parse_deno_types(&comment) } fn parse_ts_reference(comment: &str) -> Option<(TsReferenceKind, String)> { if !TRIPLE_SLASH_REFERENCE_RE.is_match(comment) { return None; } let (kind, specifier) = if let Some(capture_groups) = PATH_REFERENCE_RE.captures(comment) { (TsReferenceKind::Path, capture_groups.get(1).unwrap()) } else if let Some(capture_groups) = TYPES_REFERENCE_RE.captures(comment) { (TsReferenceKind::Types, capture_groups.get(1).unwrap()) } else if let Some(capture_groups) = LIB_REFERENCE_RE.captures(comment) { (TsReferenceKind::Lib, capture_groups.get(1).unwrap()) } else { return None; }; Some((kind, specifier.as_str().to_string())) } fn parse_deno_types(comment: &str) -> Option<String> { if let Some(capture_groups) = DENO_TYPES_RE.captures(comment) { if let Some(specifier) = capture_groups.get(1) { return Some(specifier.as_str().to_string()); } if let Some(specifier) = capture_groups.get(2) { return Some(specifier.as_str().to_string()); } } None } // Warning! The values in this enum are duplicated in js/compiler.ts // Update carefully! #[repr(i32)] #[derive(Clone, Copy, PartialEq, Debug)] pub enum CompilerRequestType { RuntimeCompile = 2, RuntimeBundle = 3, RuntimeTranspile = 4, } impl Serialize for CompilerRequestType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let value: i32 = match self { CompilerRequestType::RuntimeCompile => 2 as i32, CompilerRequestType::RuntimeBundle => 3 as i32, CompilerRequestType::RuntimeTranspile => 4 as i32, }; Serialize::serialize(&value, serializer) } } #[cfg(test)] mod tests { use super::*; use crate::fs as deno_fs; use tempfile::TempDir; #[test] fn test_parse_deno_types() { assert_eq!( parse_deno_types("@deno-types=./a/b/c.d.ts"), Some("./a/b/c.d.ts".to_string()) ); assert_eq!( parse_deno_types("@deno-types=\"./a/b/c.d.ts\""), Some("./a/b/c.d.ts".to_string()) ); assert_eq!( parse_deno_types("@deno-types = https://dneo.land/x/some/package/a.d.ts"), Some("https://dneo.land/x/some/package/a.d.ts".to_string()) ); assert_eq!( parse_deno_types("@deno-types = ./a/b/c.d.ts"), Some("./a/b/c.d.ts".to_string()) ); assert!(parse_deno_types("asdf").is_none()); assert!(parse_deno_types("// deno-types = fooo").is_none()); assert_eq!( parse_deno_types("@deno-types=./a/b/c.d.ts some comment"), Some("./a/b/c.d.ts".to_string()) ); assert_eq!( parse_deno_types( "@deno-types=./a/b/c.d.ts // some comment after slashes" ), Some("./a/b/c.d.ts".to_string()) ); assert_eq!( parse_deno_types(r#"@deno-types="https://deno.land/x/foo/index.d.ts";"#), Some("https://deno.land/x/foo/index.d.ts".to_string()) ); } #[test] fn test_parse_ts_reference() { assert_eq!( parse_ts_reference(r#"/ <reference lib="deno.shared_globals" />"#), Some((TsReferenceKind::Lib, "deno.shared_globals".to_string())) ); assert_eq!( parse_ts_reference(r#"/ <reference path="./type/reference/dep.ts" />"#), Some((TsReferenceKind::Path, "./type/reference/dep.ts".to_string())) ); assert_eq!( parse_ts_reference(r#"/ <reference types="./type/reference.d.ts" />"#), Some((TsReferenceKind::Types, "./type/reference.d.ts".to_string())) ); assert!(parse_ts_reference("asdf").is_none()); assert!( parse_ts_reference(r#"/ <reference unknown="unknown" />"#).is_none() ); assert!(parse_ts_reference(r#"/ <asset path="./styles.css" />"#).is_none()); } #[test] fn test_source_code_version_hash() { assert_eq!( "0185b42de0686b4c93c314daaa8dee159f768a9e9a336c2a5e3d5b8ca6c4208c", source_code_version_hash(b"1+2", "0.4.0", b"{}") ); // Different source_code should result in different hash. assert_eq!( "e58631f1b6b6ce2b300b133ec2ad16a8a5ba6b7ecf812a8c06e59056638571ac", source_code_version_hash(b"1", "0.4.0", b"{}") ); // Different version should result in different hash. assert_eq!( "307e6200347a88dbbada453102deb91c12939c65494e987d2d8978f6609b5633", source_code_version_hash(b"1", "0.1.0", b"{}") ); // Different config should result in different hash. assert_eq!( "195eaf104a591d1d7f69fc169c60a41959c2b7a21373cd23a8f675f877ec385f", source_code_version_hash(b"1", "0.4.0", b"{\"compilerOptions\": {}}") ); } #[test] fn test_compile_js() { let temp_dir = TempDir::new().expect("tempdir fail"); let temp_dir_path = temp_dir.path(); let test_cases = vec![ // valid JSON (r#"{ "compilerOptions": { "checkJs": true } } "#, true), // JSON with comment ( r#"{ "compilerOptions": { // force .js file compilation by Deno "checkJs": true } }"#, true, ), // without content ("", false), ]; let path = temp_dir_path.join("tsconfig.json"); let path_str = path.to_str().unwrap().to_string(); for (json_str, expected) in test_cases { deno_fs::write_file(&path, json_str.as_bytes(), 0o666).unwrap(); let config = CompilerConfig::load(Some(path_str.clone())).unwrap(); assert_eq!(config.compile_js, expected); } } #[test] fn test_compiler_config_load() { let temp_dir = TempDir::new().expect("tempdir fail"); let temp_dir_path = temp_dir.path(); let path = temp_dir_path.join("doesnotexist.json"); let path_str = path.to_str().unwrap().to_string(); let res = CompilerConfig::load(Some(path_str)); assert!(res.is_err()); } }
} else { lib.push("deno.window".to_string()); }
TaskButton.tsx
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import IconButton from '@material-ui/core/IconButton'; import Portal from '@material-ui/core/Portal'; import Snackbar from '@material-ui/core/Snackbar'; import SnackbarContent from '@material-ui/core/SnackbarContent'; import { createStyles, Theme, WithStyles, withStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; import AddIcon from '@material-ui/icons/Add'; import CloseIcon from '@material-ui/icons/Close'; import CloudUploadIcon from '@material-ui/icons/CloudUpload'; import * as React from 'react'; const styles = (theme: Theme) => createStyles({ leftIcon: { marginRight: theme.spacing(1), }, uploadButton: { marginBottom: theme.spacing(3), }, errorSnackBar: { background: theme.palette.error.dark, }, }); interface Props extends WithStyles<typeof styles> { onSubmitTask: (taskCfg: string) => Promise<void> } interface States { dialogOpened: boolean errorOpened: boolean errorMessage: string taskConfig: string } class TaskButton extends React.Component<Props, States> { constructor(props: Props) { super(props); this.state = { dialogOpened: false, errorOpened: false, errorMessage: '', taskConfig: '', }; } handleOpenDialog = () => this.setState({ dialogOpened: true }); handleCloseDialog = () => this.setState({ dialogOpened: false });
handleCloseError = () => this.setState({ errorOpened: false }); handleUploadFile = (e: React.ChangeEvent<HTMLInputElement>) => { const files = e.currentTarget.files; if (files === null) { return; } const reader = new FileReader(); reader.onload = (e: any) => this.setState({ taskConfig: e.target.result }); reader.readAsText(files[0]); }; handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => this.setState({ taskConfig: e.target.value }); handleSubmitTask = async () => { try { await this.props.onSubmitTask(this.state.taskConfig); this.handleCloseDialog(); } catch (e) { this.setState({ errorOpened: true, errorMessage: '' + e }); } }; render() { const { classes } = this.props; return ( <div> <IconButton onClick={this.handleOpenDialog} color='inherit' title='Submit new task'> <AddIcon /> </IconButton> <Dialog open={this.state.dialogOpened} onClose={this.handleCloseDialog} fullWidth maxWidth='sm' disableBackdropClick> <DialogTitle>Submit task</DialogTitle> <DialogContent> <div className={classes.uploadButton}> <input accept='.toml' hidden id='upload-task-config' type='file' onChange={this.handleUploadFile} /> <label htmlFor='upload-task-config'> <Button component='span' variant='contained' > <CloudUploadIcon className={classes.leftIcon} /> Upload </Button> </label> </div> <TextField label='Task configuration' multiline fullWidth rows='20' value={this.state.taskConfig} onChange={this.handleChange} /> </DialogContent> <DialogActions> <Button onClick={this.handleCloseDialog} color='primary'> Cancel </Button> <Button onClick={this.handleSubmitTask} color='secondary' disabled={this.state.taskConfig.length === 0}> Submit </Button> </DialogActions> </Dialog> <Portal> {/* the Portal workarounds mui-org/material-ui#12201 */} <Snackbar open={this.state.errorOpened} autoHideDuration={5000} onClose={this.handleCloseError}> <SnackbarContent className={classes.errorSnackBar} message={this.state.errorMessage} action={ <IconButton color='inherit' onClick={this.handleCloseError}> <CloseIcon /> </IconButton> } /> </Snackbar> </Portal> </div> ) } } export default withStyles(styles)(TaskButton);
authentication.py
from six import text_type from rest_framework import HTTP_HEADER_ENCODING, exceptions from django.core.exceptions import PermissionDenied from django.utils.translation import ugettext_lazy as _ from atlassian_connect_django.models.connect import AtlassianUser from atlassian_connect_django import helpers from .models import SecurityContextToken def
(request, raise_exceptions=True): def exception(msg): if not raise_exceptions: return None, None if raise_exceptions == 'rest_framework': raise exceptions.AuthenticationFailed(msg) raise PermissionDenied(msg) auth = request.META.get('HTTP_X_JIRA_SECURITY_CONTEXT', b'') if isinstance(auth, text_type): # Work around django test client oddness auth = auth.encode(HTTP_HEADER_ENCODING) auth = auth.split() if not auth or auth[0].lower() != b'token': return None, None if len(auth) == 1: return exception(_('Invalid x-jira-security-context token header. No credentials provided.')) elif len(auth) > 2: return exception(_('Invalid x-jira-security-context token header. Token string should not contain spaces.')) try: token = auth[1].decode() except UnicodeError: return exception(_('Invalid x-jira-security-context token header. Token string should not contain invalid characters.')) try: token = SecurityContextToken.objects.select_related('security_context').get(key=token) except SecurityContextToken.DoesNotExist: return exception(_('Invalid x-jira-security-context token.')) if not token.security_context.is_plugin_enabled: return exception(_('Security context inactive or deleted.')) site = helpers.get_current_site(request=request) if site and site != token.security_context.site: return exception(_('Invalid x-jira-security-context token header. SecurityContext site "%s" not equals to "%s"' % (token.security_context.site.name, site.name))) atlassian_user = AtlassianUser(accountId=token.atlassian_user_account_id) atlassian_user.set_secutiry_context(security_context=token.security_context) return token.security_context, atlassian_user
get_atlassian_security_context_and_user_from_request
TestItem.ts
export default class TestItem { public logText: string = ""; public async init(): Promise<any> { return 0; } public async dispose(): Promise<any> { return 0; } public log(text: string): void { if (text) { this.logText += text;
public delay(n: number): Promise<any> { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, n); }); } }
} }
test_forward.py
import os import os.path as op import warnings import gc from nose.tools import assert_true, assert_raises import numpy as np from numpy.testing import (assert_array_almost_equal, assert_equal, assert_array_equal, assert_allclose) from mne.datasets import testing from mne.io import Raw from mne import (read_forward_solution, apply_forward, apply_forward_raw, average_forward_solutions, write_forward_solution, convert_forward_solution) from mne import SourceEstimate, pick_types_forward, read_evokeds from mne.label import read_label from mne.utils import (requires_mne, run_subprocess, _TempDir, run_tests_if_main, slow_test) from mne.forward import (restrict_forward_to_stc, restrict_forward_to_label, Forward) data_path = testing.data_path(download=False) fname_meeg = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') fname_meeg_grad = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-2-grad-fwd.fif') fname_raw = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data', 'test_raw.fif') fname_evoked = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data', 'test-ave.fif') fname_mri = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-trans.fif') subjects_dir = os.path.join(data_path, 'subjects') fname_src = op.join(subjects_dir, 'sample', 'bem', 'sample-oct-4-src.fif') def compare_forwards(f1, f2): """Helper to compare two potentially converted forward solutions""" assert_allclose(f1['sol']['data'], f2['sol']['data']) assert_equal(f1['sol']['ncol'], f2['sol']['ncol']) assert_allclose(f1['source_nn'], f2['source_nn']) if f1['sol_grad'] is not None: assert_true(f2['sol_grad'] is not None) assert_allclose(f1['sol_grad']['data'], f2['sol_grad']['data']) assert_equal(f1['sol_grad']['ncol'], f2['sol_grad']['ncol']) else: assert_true(f2['sol_grad'] is None) assert_equal(f1['source_ori'], f2['source_ori']) assert_equal(f1['surf_ori'], f2['surf_ori']) @testing.requires_testing_data def test_convert_forward(): """Test converting forward solution between different representations """ fwd = read_forward_solution(fname_meeg_grad) assert_true(repr(fwd)) assert_true(isinstance(fwd, Forward)) # look at surface orientation fwd_surf = convert_forward_solution(fwd, surf_ori=True) fwd_surf_io = read_forward_solution(fname_meeg_grad, surf_ori=True) compare_forwards(fwd_surf, fwd_surf_io) del fwd_surf_io gc.collect() # go back fwd_new = convert_forward_solution(fwd_surf, surf_ori=False) assert_true(repr(fwd_new)) assert_true(isinstance(fwd_new, Forward)) compare_forwards(fwd, fwd_new) # now go to fixed fwd_fixed = convert_forward_solution(fwd_surf, surf_ori=False, force_fixed=True) del fwd_surf gc.collect() assert_true(repr(fwd_fixed)) assert_true(isinstance(fwd_fixed, Forward)) fwd_fixed_io = read_forward_solution(fname_meeg_grad, surf_ori=False, force_fixed=True) compare_forwards(fwd_fixed, fwd_fixed_io) del fwd_fixed_io gc.collect() # now go back to cartesian (original condition) fwd_new = convert_forward_solution(fwd_fixed) assert_true(repr(fwd_new)) assert_true(isinstance(fwd_new, Forward)) compare_forwards(fwd, fwd_new) del fwd, fwd_new, fwd_fixed gc.collect() @slow_test @testing.requires_testing_data def test_io_forward(): """Test IO for forward solutions """ temp_dir = _TempDir() # do extensive tests with MEEG + grad n_channels, n_src = 366, 108 fwd = read_forward_solution(fname_meeg_grad) assert_true(isinstance(fwd, Forward)) fwd = read_forward_solution(fname_meeg_grad, surf_ori=True) leadfield = fwd['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd['sol']['row_names']), n_channels) fname_temp = op.join(temp_dir, 'test-fwd.fif') write_forward_solution(fname_temp, fwd, overwrite=True) fwd = read_forward_solution(fname_meeg_grad, surf_ori=True) fwd_read = read_forward_solution(fname_temp, surf_ori=True) leadfield = fwd_read['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src)) assert_equal(len(fwd_read['sol']['row_names']), n_channels) assert_equal(len(fwd_read['info']['chs']), n_channels) assert_true('dev_head_t' in fwd_read['info']) assert_true('mri_head_t' in fwd_read) assert_array_almost_equal(fwd['sol']['data'], fwd_read['sol']['data']) fwd = read_forward_solution(fname_meeg_grad, force_fixed=True) leadfield = fwd['sol']['data'] assert_equal(leadfield.shape, (n_channels, n_src / 3)) assert_equal(len(fwd['sol']['row_names']), n_channels) assert_equal(len(fwd['info']['chs']), n_channels) assert_true('dev_head_t' in fwd['info']) assert_true('mri_head_t' in fwd) assert_true(fwd['surf_ori']) # test warnings on bad filenames fwd = read_forward_solution(fname_meeg_grad) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fwd_badname = op.join(temp_dir, 'test-bad-name.fif.gz') write_forward_solution(fwd_badname, fwd) read_forward_solution(fwd_badname) assert_true(len(w) == 2) fwd = read_forward_solution(fname_meeg) write_forward_solution(fname_temp, fwd, overwrite=True) fwd_read = read_forward_solution(fname_temp) compare_forwards(fwd, fwd_read) @testing.requires_testing_data def test_apply_forward(): """Test projection of source space data to sensor space """ start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) assert_true(isinstance(fwd, Forward)) vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) gain_sum = np.sum(fwd['sol']['data'], axis=1) # Evoked with warnings.catch_warnings(record=True) as w: evoked = read_evokeds(fname_evoked, condition=0) evoked = apply_forward(fwd, stc, evoked, start=start, stop=stop) assert_equal(len(w), 2) data = evoked.data times = evoked.times # do some tests assert_array_almost_equal(evoked.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) assert_array_almost_equal(times[0], t_start) assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq) # Raw raw = Raw(fname_raw) raw_proj = apply_forward_raw(fwd, stc, raw, start=start, stop=stop) data, times = raw_proj[:, :] # do some tests assert_array_almost_equal(raw_proj.info['sfreq'], sfreq) assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum) atol = 1. / sfreq assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol) assert_allclose(raw_proj.last_samp / sfreq, t_start + (n_times - 1) / sfreq, atol=atol) @testing.requires_testing_data def test_restrict_forward_to_stc():
@testing.requires_testing_data def test_restrict_forward_to_label(): """Test restriction of source space to label """ fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = (np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) + len(fwd['src'][0]['vertno'])) assert_equal(fwd_out['sol']['ncol'], len(src_sel_lh) + len(src_sel_rh)) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], src_sel_lh) assert_equal(fwd_out['src'][1]['vertno'], src_sel_rh) fwd = read_forward_solution(fname_meeg, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = (np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) + len(fwd['src'][0]['vertno'])) assert_equal(fwd_out['sol']['ncol'], 3 * (len(src_sel_lh) + len(src_sel_rh))) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], src_sel_lh) assert_equal(fwd_out['src'][1]['vertno'], src_sel_rh) @testing.requires_testing_data @requires_mne def test_average_forward_solution(): """Test averaging forward solutions """ temp_dir = _TempDir() fwd = read_forward_solution(fname_meeg) # input not a list assert_raises(TypeError, average_forward_solutions, 1) # list is too short assert_raises(ValueError, average_forward_solutions, []) # negative weights assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [-1, 0]) # all zero weights assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0]) # weights not same length assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0, 0]) # list does not only have all dict() assert_raises(TypeError, average_forward_solutions, [1, fwd]) # try an easy case fwd_copy = average_forward_solutions([fwd]) assert_true(isinstance(fwd_copy, Forward)) assert_array_equal(fwd['sol']['data'], fwd_copy['sol']['data']) # modify a fwd solution, save it, use MNE to average with old one fwd_copy['sol']['data'] *= 0.5 fname_copy = op.join(temp_dir, 'copy-fwd.fif') write_forward_solution(fname_copy, fwd_copy, overwrite=True) cmd = ('mne_average_forward_solutions', '--fwd', fname_meeg, '--fwd', fname_copy, '--out', fname_copy) run_subprocess(cmd) # now let's actually do it, with one filename and one fwd fwd_ave = average_forward_solutions([fwd, fwd_copy]) assert_array_equal(0.75 * fwd['sol']['data'], fwd_ave['sol']['data']) # fwd_ave_mne = read_forward_solution(fname_copy) # assert_array_equal(fwd_ave_mne['sol']['data'], fwd_ave['sol']['data']) # with gradient fwd = read_forward_solution(fname_meeg_grad) fwd_ave = average_forward_solutions([fwd, fwd]) compare_forwards(fwd, fwd_ave) run_tests_if_main()
"""Test restriction of source space to source SourceEstimate """ start = 0 stop = 5 n_times = stop - start - 1 sfreq = 10.0 t_start = 0.123 fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_true(isinstance(fwd_out, Forward)) assert_equal(fwd_out['sol']['ncol'], 20) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5]) fwd = read_forward_solution(fname_meeg, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) vertno = [fwd['src'][0]['vertno'][0:15], fwd['src'][1]['vertno'][0:5]] stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times)) stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq) fwd_out = restrict_forward_to_stc(fwd, stc) assert_equal(fwd_out['sol']['ncol'], 60) assert_equal(fwd_out['src'][0]['nuse'], 15) assert_equal(fwd_out['src'][1]['nuse'], 5) assert_equal(fwd_out['src'][0]['vertno'], fwd['src'][0]['vertno'][0:15]) assert_equal(fwd_out['src'][1]['vertno'], fwd['src'][1]['vertno'][0:5])
0001_initial.py
# Generated by Django 3.1.5 on 2021-01-08 20:56 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration):
initial = True dependencies = [("auth", "0012_alter_user_first_name_max_length")] operations = [ migrations.CreateModel( name="CustomUser", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("password", models.CharField(max_length=128, verbose_name="password")), ( "last_login", models.DateTimeField( blank=True, null=True, verbose_name="last login" ), ), ( "is_superuser", models.BooleanField( default=False, help_text="Designates that this user has all permissions without explicitly assigning them.", verbose_name="superuser status", ), ), ( "username", models.CharField( error_messages={ "unique": "A user with that username already exists." }, help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.", max_length=150, unique=True, validators=[ django.contrib.auth.validators.UnicodeUsernameValidator() ], verbose_name="username", ), ), ( "first_name", models.CharField( blank=True, max_length=150, verbose_name="first name" ), ), ( "last_name", models.CharField( blank=True, max_length=150, verbose_name="last name" ), ), ( "email", models.EmailField( blank=True, max_length=254, verbose_name="email address" ), ), ( "is_staff", models.BooleanField( default=False, help_text="Designates whether the user can log into this admin site.", verbose_name="staff status", ), ), ( "is_active", models.BooleanField( default=True, help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.", verbose_name="active", ), ), ( "date_joined", models.DateTimeField( default=django.utils.timezone.now, verbose_name="date joined" ), ), ( "groups", models.ManyToManyField( blank=True, help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.", related_name="user_set", related_query_name="user", to="auth.Group", verbose_name="groups", ), ), ( "user_permissions", models.ManyToManyField( blank=True, help_text="Specific permissions for this user.", related_name="user_set", related_query_name="user", to="auth.Permission", verbose_name="user permissions", ), ), ], options={ "verbose_name": "user", "verbose_name_plural": "users", "abstract": False, }, managers=[("objects", django.contrib.auth.models.UserManager())], ), migrations.CreateModel( name="Tweet", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("content", models.CharField(max_length=512)), ("votes", models.IntegerField()), ( "poster", models.ForeignKey( null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, ), ), ], ), ]
example1.py
from duckduckgo import query, Topic from sys import argv visited = [] def
(qr, depth=0): print ' '* depth * 4 + qr ds = query(qr) if depth == 2: return if ds.error_code != 0: return visited.append(qr) if ds.related == []: return else: for r in ds.related: if isinstance(r, Topic) == True: r_used = r.name.encode('ascii', 'ignore') else: r_used = r.text.encode('ascii', 'ignore').split('-')[0].strip() try: visited.index(r_used) except: build_web_tree(r_used, depth=depth+1) if __name__ == '__main__': build_web_tree(' '.join(argv[1:]))
build_web_tree
plugins.ts
import {remote} from 'electron'; // TODO: Should be updates to new async API https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31 import {connect as reduxConnect, Options} from 'react-redux'; import {basename} from 'path'; // patching Module._load // so plugins can `require` them without needing their own version // https://github.com/zeit/hyper/issues/619 import React, {PureComponent} from 'react'; import ReactDOM from 'react-dom'; import Notification from '../components/notification'; import notify from './notify'; import {hyperPlugin, IUiReducer, ISessionReducer, ITermGroupReducer, HyperState} from '../hyper'; import {Dispatch, Middleware} from 'redux'; // remote interface to `../plugins` const plugins = remote.require('./plugins') as typeof import('../../app/plugins'); // `require`d modules let modules: any; // cache of decorated components let decorated: Record<string, any> = {}; // various caches extracted of the plugin methods let connectors: { Terms: {state: any[]; dispatch: any[]}; Header: {state: any[]; dispatch: any[]}; Hyper: {state: any[]; dispatch: any[]}; Notifications: {state: any[]; dispatch: any[]}; }; let middlewares: any[]; let uiReducers: IUiReducer[]; let sessionsReducers: ISessionReducer[]; let termGroupsReducers: ITermGroupReducer[]; let tabPropsDecorators: any[]; let tabsPropsDecorators: any[]; let termPropsDecorators: any[]; let termGroupPropsDecorators: any[]; let propsDecorators: { getTermProps: any[]; getTabProps: any[]; getTabsProps: any[]; getTermGroupProps: any[]; }; let reducersDecorators: { reduceUI: IUiReducer[]; reduceSessions: ISessionReducer[]; reduceTermGroups: ITermGroupReducer[]; }; // expose decorated component instance to the higher-order components function exposeDecorated(Component_: any) { return class DecoratedComponent extends React.Component<any, any> { constructor(props: any, context: any) { super(props, context); } onRef = (decorated_: any) => { if (this.props.onDecorated) { try { this.props.onDecorated(decorated_); } catch (e) { notify('Plugin error', `Error occurred. Check Developer Tools for details`, {error: e}); } } }; render() { return React.createElement(Component_, Object.assign({}, this.props, {ref: this.onRef})); } }; } function getDecorated(parent: any, name: string) { if (!decorated[name]) { let class_ = exposeDecorated(parent); (class_ as any).displayName = `_exposeDecorated(${name})`; modules.forEach((mod: any) => { const method = 'decorate' + name; const fn = mod[method]; if (fn) { let class__; try { class__ = fn(class_, {React, PureComponent, Notification, notify}); class__.displayName = `${fn._pluginName}(${name})`; } catch (err) { notify( 'Plugin error', `${fn._pluginName}: Error occurred in \`${method}\`. Check Developer Tools for details`, {error: err} ); return; } if (!class__ || typeof class__.prototype.render !== 'function') { notify( 'Plugin error', `${fn._pluginName}: Invalid return value of \`${method}\`. No \`render\` method found. Please return a \`React.Component\`.` ); return; } class_ = class__; } }); decorated[name] = class_; } return decorated[name]; } // for each component, we return a higher-order component // that wraps with the higher-order components // exposed by plugins export function decorate(Component_: any, name: string) { return class DecoratedComponent extends React.Component<any, {hasError: boolean}> { constructor(props: any) { super(props); this.state = {hasError: false}; } componentDidCatch() { this.setState({hasError: true}); // No need to detail this error because React print these information. notify( 'Plugin error', `Plugins decorating ${name} has been disabled because of a plugin crash. Check Developer Tools for details.` ); } render() { const Sub = this.state.hasError ? Component_ : getDecorated(Component_, name); return React.createElement(Sub, this.props); } }; } const Module = require('module') as typeof import('module') & {_load: Function}; const originalLoad = Module._load; Module._load = function _load(path: string) { // PLEASE NOTE: Code changes here, also need to be changed in // app/plugins.js switch (path) { case 'react': //eslint-disable-next-line no-console console.warn('DEPRECATED: If your plugin requires `react`, it must bundle it as a dependency'); return React; case 'react-dom': //eslint-disable-next-line no-console console.warn('DEPRECATED: If your plugin requires `react-dom`, it must bundle it as a dependency'); return ReactDOM; case 'hyper/component': //eslint-disable-next-line no-console console.warn( 'DEPRECATED: If your plugin requires `hyper/component`, it must requires `react.PureComponent` instead and bundle `react` as a dependency' ); return PureComponent; case 'hyper/notify': return notify; case 'hyper/Notification': return Notification; case 'hyper/decorate': return decorate; default: // eslint-disable-next-line prefer-rest-params return originalLoad.apply(this, arguments); } }; const clearModulesCache = () => { // the fs locations where user plugins are stored const {path, localPath} = plugins.getBasePaths(); // trigger unload hooks modules.forEach((mod: any) => { if (mod.onRendererUnload) { mod.onRendererUnload(window); } }); // clear require cache for (const entry in window.require.cache) { if (entry.indexOf(path) === 0 || entry.indexOf(localPath) === 0) { // `require` is webpacks', `window.require` is electron's delete window.require.cache[entry]; } } }; const pathModule = window.require('path') as typeof import('path'); const getPluginName = (path: string) => pathModule.basename(path); const getPluginVersion = (path: string): string | null => { let version = null; try { version = (window.require(pathModule.resolve(path, 'package.json')) as any).version as string; } catch (err) { //eslint-disable-next-line no-console console.warn(`No package.json found in ${path}`); } return version; }; const loadModules = () => { //eslint-disable-next-line no-console console.log('(re)loading renderer plugins'); const paths = plugins.getPaths(); // initialize cache that we populate with extension methods connectors = { Terms: {state: [], dispatch: []}, Header: {state: [], dispatch: []}, Hyper: {state: [], dispatch: []}, Notifications: {state: [], dispatch: []} }; uiReducers = []; middlewares = []; sessionsReducers = []; termGroupsReducers = []; tabPropsDecorators = []; tabsPropsDecorators = []; termPropsDecorators = []; termGroupPropsDecorators = []; propsDecorators = { getTermProps: termPropsDecorators, getTabProps: tabPropsDecorators, getTabsProps: tabsPropsDecorators, getTermGroupProps: termGroupPropsDecorators }; reducersDecorators = { reduceUI: uiReducers, reduceSessions: sessionsReducers, reduceTermGroups: termGroupsReducers }; const loadedPlugins = plugins.getLoadedPluginVersions().map((plugin: any) => plugin.name); modules = paths.plugins .concat(paths.localPlugins) .filter((plugin: any) => loadedPlugins.indexOf(basename(plugin)) !== -1) .map((path: any) => { let mod: hyperPlugin; const pluginName = getPluginName(path); const pluginVersion = getPluginVersion(path); // window.require allows us to ensure this doesn't get // in the way of our build try { mod = window.require(path) as any; } catch (err) { notify( 'Plugin load error', `"${pluginName}" failed to load in the renderer process. Check Developer Tools for details.`, {error: err} ); return undefined; } (Object.keys(mod) as (keyof typeof mod)[]).forEach(i => { if (Object.hasOwnProperty.call(mod, i)) { mod[i]._pluginName = pluginName; mod[i]._pluginVersion = pluginVersion; } }); // mapHyperTermState mapping for backwards compatibility with hyperterm if (mod.mapHyperTermState) { mod.mapHyperState = mod.mapHyperTermState; //eslint-disable-next-line no-console console.error('mapHyperTermState is deprecated. Use mapHyperState instead.'); } // mapHyperTermDispatch mapping for backwards compatibility with hyperterm if (mod.mapHyperTermDispatch) { mod.mapHyperDispatch = mod.mapHyperTermDispatch; //eslint-disable-next-line no-console console.error('mapHyperTermDispatch is deprecated. Use mapHyperDispatch instead.'); } if (mod.middleware) { middlewares.push(mod.middleware); } if (mod.reduceUI) { uiReducers.push(mod.reduceUI); } if (mod.reduceSessions) { sessionsReducers.push(mod.reduceSessions); } if (mod.reduceTermGroups) { termGroupsReducers.push(mod.reduceTermGroups); } if (mod.mapTermsState) { connectors.Terms.state.push(mod.mapTermsState); } if (mod.mapTermsDispatch) { connectors.Terms.dispatch.push(mod.mapTermsDispatch); } if (mod.mapHeaderState) { connectors.Header.state.push(mod.mapHeaderState); } if (mod.mapHeaderDispatch) { connectors.Header.dispatch.push(mod.mapHeaderDispatch); } if (mod.mapHyperState) { connectors.Hyper.state.push(mod.mapHyperState); } if (mod.mapHyperDispatch) { connectors.Hyper.dispatch.push(mod.mapHyperDispatch); } if (mod.mapNotificationsState) { connectors.Notifications.state.push(mod.mapNotificationsState); } if (mod.mapNotificationsDispatch) { connectors.Notifications.dispatch.push(mod.mapNotificationsDispatch); } if (mod.getTermGroupProps) { termGroupPropsDecorators.push(mod.getTermGroupProps); } if (mod.getTermProps) { termPropsDecorators.push(mod.getTermProps); } if (mod.getTabProps) { tabPropsDecorators.push(mod.getTabProps); } if (mod.getTabsProps) { tabsPropsDecorators.push(mod.getTabsProps); } if (mod.onRendererWindow) { mod.onRendererWindow(window); } //eslint-disable-next-line no-console console.log(`Plugin ${pluginName} (${pluginVersion}) loaded.`); return mod; }) .filter((mod: any) => Boolean(mod)); const deprecatedPlugins: Record<string, any> = plugins.getDeprecatedConfig(); Object.keys(deprecatedPlugins).forEach(name => { const {css} = deprecatedPlugins[name]; if (css) { //eslint-disable-next-line no-console console.warn(`Warning: "${name}" plugin uses some deprecated CSS classes (${css.join(', ')}).`); } }); }; // load modules for initial decoration loadModules(); export function reload() { clearModulesCache(); loadModules(); // trigger re-decoration when components // get re-rendered decorated = {}; } function getProps(name: keyof typeof propsDecorators, props: any, ...fnArgs: any[]) { const decorators = propsDecorators[name]; let props_: typeof props; decorators.forEach(fn => { let ret_; if (!props_) { props_ = Object.assign({}, props); } try { ret_ = fn(...fnArgs, props_); } catch (err) { notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`, { error: err }); return; } if (!ret_ || typeof ret_ !== 'object') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\` (object expected).`); return; } props_ = ret_; }); return props_ || props; } export function getTermGroupProps(uid: string, parentProps: any, props: any) { return getProps('getTermGroupProps', props, uid, parentProps); } export function
(uid: string, parentProps: any, props: any) { return getProps('getTermProps', props, uid, parentProps); } export function getTabsProps(parentProps: any, props: any) { return getProps('getTabsProps', props, parentProps); } export function getTabProps(tab: any, parentProps: any, props: any) { return getProps('getTabProps', props, tab, parentProps); } // connects + decorates a class // plugins can override mapToState, dispatchToProps // and the class gets decorated (proxied) export function connect<stateProps, dispatchProps>( stateFn: (state: HyperState) => stateProps, dispatchFn: (dispatch: Dispatch<any>) => dispatchProps, c: any, d: Options = {} ) { return (Class: any, name: keyof typeof connectors) => { return reduxConnect<stateProps, dispatchProps, any, HyperState>( state => { let ret = stateFn(state); connectors[name].state.forEach(fn => { let ret_; try { ret_ = fn(state, ret); } catch (err) { notify( 'Plugin error', `${fn._pluginName}: Error occurred in \`map${name}State\`. Check Developer Tools for details.`, {error: err} ); return; } if (!ret_ || typeof ret_ !== 'object') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`map${name}State\` (object expected).`); return; } ret = ret_; }); return ret; }, dispatch => { let ret = dispatchFn(dispatch); connectors[name].dispatch.forEach(fn => { let ret_; try { ret_ = fn(dispatch, ret); } catch (err) { notify( 'Plugin error', `${fn._pluginName}: Error occurred in \`map${name}Dispatch\`. Check Developer Tools for details.`, {error: err} ); return; } if (!ret_ || typeof ret_ !== 'object') { notify( 'Plugin error', `${fn._pluginName}: Invalid return value of \`map${name}Dispatch\` (object expected).` ); return; } ret = ret_; }); return ret; }, c, d )(decorate(Class, name)); }; } const decorateReducer: { (name: 'reduceUI', fn: IUiReducer): IUiReducer; (name: 'reduceSessions', fn: ISessionReducer): ISessionReducer; (name: 'reduceTermGroups', fn: ITermGroupReducer): ITermGroupReducer; } = <T extends keyof typeof reducersDecorators>(name: T, fn: any) => { const reducers = reducersDecorators[name]; return (state: any, action: any) => { let state_ = fn(state, action); reducers.forEach((pluginReducer: any) => { let state__; try { state__ = pluginReducer(state_, action); } catch (err) { notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`, { error: err }); return; } if (!state__ || typeof state__ !== 'object') { notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\`.`); return; } state_ = state__; }); return state_; }; }; export function decorateTermGroupsReducer(fn: ITermGroupReducer) { return decorateReducer('reduceTermGroups', fn); } export function decorateUIReducer(fn: IUiReducer) { return decorateReducer('reduceUI', fn); } export function decorateSessionsReducer(fn: ISessionReducer) { return decorateReducer('reduceSessions', fn); } // redux middleware generator export const middleware: Middleware = store => next => action => { const nextMiddleware = (remaining: Middleware[]) => (action_: any) => remaining.length ? remaining[0](store)(nextMiddleware(remaining.slice(1)))(action_) : next(action_); nextMiddleware(middlewares)(action); };
getTermProps
ty.rs
use std::hash::{Hash, Hasher}; use std::ops::{Deref, DerefMut}; use std::fmt; use common::Field; macro_rules! wrapper { (@eq_impl @direct_eq $name:ident) => { impl PartialEq for $name { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl Eq for $name {} }; (@eq_impl @sub_eq $name:ident) => { impl PartialEq for $name { fn eq(&self, other: &Self) -> bool { **self == **other } } impl Eq for $name {} }; ($name:ident -> $sub_ty:ty, @$eq:ident) => { #[derive(Debug, Clone, Copy)] pub struct $name(*mut $sub_ty); impl $name { pub fn from_raw(sub: *mut $sub_ty) -> Self { $name(sub) } } unsafe impl Send for $name {} impl Deref for $name { type Target = $sub_ty; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } wrapper!(@eq_impl @$eq $name); impl DerefMut for $name { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { &mut *self.0 } } } impl Hash for $name { fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state); } } } } wrapper!(Type -> TypeValue, @direct_eq); wrapper!(StructType -> StructTypeValue, @sub_eq); impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match **self { TypeValue::Incomplete => write!(f, "incomplete"), TypeValue::Int => write!(f, "int"), TypeValue::Double => write!(f, "double"), TypeValue::Boolean => write!(f, "boolean"), TypeValue::String => write!(f, "string"), TypeValue::Void => write!(f, "void"), TypeValue::Pointer(ref sub) => write!(f, "*{}", sub), TypeValue::Struct(ref s) => write!(f, "struct {} {{ .. }}", s.name), TypeValue::Array(ref sub, ref size) => write!(f, "[{}; {}]", sub, size), _ => panic!("Type not supposed to be displayed"), } } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum TypeValue { Incomplete, Int, Double, Boolean, String, Void, Struct(StructType), Tuple(Vec<Type>), LValue(Type, bool), // assignable Pointer(Type), Array(Type, usize), FunctionPtr(FunctionType), } #[derive(Debug, Clone)] pub enum FieldInfo { StructField(usize, Type), TupleField(usize, Type), ArrayLen(usize), } impl TypeValue { pub fn
(&self, field: &Field) -> Option<FieldInfo> { match *self { TypeValue::Struct(st) => { if let Field::Named(ref field_name) = *field { for (index, &(ref name, ty)) in st.fields.iter().enumerate() { if name == field_name { return Some(FieldInfo::StructField(index, ty)); } } } None } TypeValue::Array(_, size) => { if let Field::Named(ref field_name) = *field { if field_name == "len" { return Some(FieldInfo::ArrayLen(size)); } } None } TypeValue::Tuple(ref types) => { if let Field::Index(index) = *field { if index < types.len() { return Some(FieldInfo::TupleField(index, types[index])); } } None } _ => None, } } } #[derive(Debug, Clone, Eq)] pub struct StructTypeValue { pub name: String, pub fields: Vec<(String, Type)>, } impl PartialEq for StructTypeValue { fn eq(&self, other: &Self) -> bool { self.name == other.name // currently we eq on name because we don't have any module/namespace. Maybe use an id } } impl Hash for StructTypeValue { fn hash<H: Hasher>(&self, state: &mut H) { self.name.hash(state); } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FunctionType { pub return_ty: Type, pub parameters_ty: Vec<Type>, pub is_vararg: bool, }
has_field
key_test.go
package gojwk import ( "crypto/x509" "crypto/x509/pkix" "fmt" "github.com/golang-jwt/jwt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zebox/gojwk/storage" "math/big" "os" "testing" "time" )
const ( testPrivateKey = "test_private.key.tmp" testPublicKey = "test_public.key.tmp" ) var testRootPath = os.TempDir() + "/" func TestNewKeys(t *testing.T) { k, err := NewKeys() require.NoError(t, err) require.NotNil(t, k) } func TestNewKeys_withCustomBitSize(t *testing.T) { k, err := NewKeys(BitSize(128)) require.NoError(t, err) require.NotNil(t, k) err = k.Generate() require.NoError(t, err) assert.NotNil(t, k.privateKey) k, err = NewKeys(BitSize(127)) require.Error(t, err) assert.Nil(t, k) } func TestNewKeys_withStorage(t *testing.T) { fs := storage.NewFileStorage(testRootPath, testPrivateKey, testPublicKey) keys, err := NewKeys(Storage(fs)) require.NoError(t, err) assert.NotNil(t, keys) err = keys.Generate() require.NoError(t, err) require.NoError(t, keys.Save()) changeKeyFilesPermission(t) defer deleteTestFile(t) _, err = os.Stat(testRootPath + testPrivateKey) assert.NoError(t, err) _, err = os.Stat(testRootPath + testPublicKey) assert.NoError(t, err) } func TestKey_GenerateKeys(t *testing.T) { k, err := NewKeys() require.NoError(t, err) require.NotNil(t, k) err = k.Generate() require.NoError(t, err) assert.NotNil(t, k.publicKey) assert.NotNil(t, k.privateKey) k.bitSize = 8 require.Error(t, k.Generate()) } func TestKey_CreateCACertificate(t *testing.T) { fs := storage.NewFileStorage(testRootPath, testPrivateKey, testPublicKey) keys, err := NewKeys(Storage(fs)) require.NoError(t, err) assert.NotNil(t, keys) assert.NoError(t, keys.Generate()) ca := &x509.Certificate{ SerialNumber: big.NewInt(2019), Subject: pkix.Name{ Organization: []string{"TEST, INC."}, Country: []string{"RU"}, Province: []string{""}, Locality: []string{"Krasnodar"}, StreetAddress: []string{"Krasnaya"}, PostalCode: []string{"350000"}, }, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Second * 30), IsCA: true, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, BasicConstraintsValid: true, } assert.NoError(t, keys.CreateCAROOT(ca)) assert.NotNil(t, keys.CertCA()) // test without or wrong private key keys.privateKey = nil assert.Error(t, keys.CreateCAROOT(ca)) } func TestPEMBytes(t *testing.T) { keys, err := NewKeys() require.NoError(t, err) assert.NotNil(t, keys) assert.NoError(t, keys.Generate()) privatePemBytes, err := PEMBytes(keys.privateKey) assert.NoError(t, err) assert.NotNil(t, privatePemBytes) publicPemBytes, err := PEMBytes(keys.publicKey) assert.NoError(t, err) assert.NotNil(t, publicPemBytes) publicPemBytes, err = PEMBytes(struct{}{}) assert.Error(t, err) assert.Nil(t, publicPemBytes) } func TestKeys_CertCA(t *testing.T) { keys, err := NewKeys() require.NoError(t, err) assert.NotNil(t, keys) assert.NoError(t, keys.Generate()) assert.Nil(t, keys.certCARoot) ca := &x509.Certificate{ SerialNumber: big.NewInt(2019), Subject: pkix.Name{ Organization: []string{"TEST, INC."}, Country: []string{"RU"}, Province: []string{""}, Locality: []string{"Krasnodar"}, StreetAddress: []string{"Krasnaya"}, PostalCode: []string{"350000"}, }, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Second * 30), IsCA: true, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, BasicConstraintsValid: true, } assert.NoError(t, keys.CreateCAROOT(ca)) assert.NotNil(t, keys.certCARoot) } func TestKey_Save(t *testing.T) { fs := storage.NewFileStorage(testRootPath, testPrivateKey, testPublicKey) keys, err := NewKeys(Storage(fs)) require.NoError(t, err) assert.NotNil(t, keys) err = keys.Generate() ca := &x509.Certificate{ SerialNumber: big.NewInt(2019), Subject: pkix.Name{ Organization: []string{"TEST, INC."}, Country: []string{"RU"}, Province: []string{""}, Locality: []string{"Krasnodar"}, StreetAddress: []string{"Krasnaya"}, PostalCode: []string{"350000"}, }, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Second * 30), IsCA: true, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, BasicConstraintsValid: true, } assert.NoError(t, keys.CreateCAROOT(ca)) require.NoError(t, err) require.NoError(t, keys.Save()) changeKeyFilesPermission(t) defer deleteTestFile(t) // check files for exist on a filesystem _, err = os.Stat(testRootPath + testPrivateKey) assert.NoError(t, err) _, err = os.Stat(testRootPath + testPublicKey) assert.NoError(t, err) CAPath := fmt.Sprintf("%sCA_%s.crt", testRootPath, testPublicKey) _, err = os.Stat(CAPath) assert.NoError(t, err) err = os.Remove(CAPath) assert.NoError(t, err) keys, err = NewKeys() require.NoError(t, err) err = keys.Save() changeKeyFilesPermission(t) assert.Error(t, err) } func TestKey_Load(t *testing.T) { fs := storage.NewFileStorage(testRootPath, testPrivateKey, testPublicKey) keys, err := NewKeys(Storage(fs)) require.NoError(t, err) assert.NotNil(t, keys) err = keys.Generate() require.NoError(t, err) require.NoError(t, keys.Save()) changeKeyFilesPermission(t) defer deleteTestFile(t) _, err = os.Stat(testRootPath + testPrivateKey) assert.NoError(t, err) _, err = os.Stat(testRootPath + testPublicKey) assert.NoError(t, err) // trying load key pair from file storage provider keys, err = NewKeys(Storage(fs)) assert.NoError(t, err) assert.Nil(t, keys.publicKey) assert.Nil(t, keys.privateKey) assert.NoError(t, keys.Load()) assert.NotNil(t, keys.publicKey) assert.NotNil(t, keys.privateKey) badFs := storage.NewFileStorage("fake_path", testPrivateKey, testPublicKey) keys, errNewKeys := NewKeys(Storage(badFs)) assert.NoError(t, errNewKeys) assert.Error(t, keys.Load()) keys.storage = nil assert.Error(t, keys.Load()) } func TestKey_JWK(t *testing.T) { k, err := NewKeys() require.NoError(t, err) require.NotNil(t, k) err = k.Generate() require.NoError(t, err) assert.NotNil(t, k.publicKey) assert.NotNil(t, k.privateKey) jwk, err := k.JWK() t.Log(jwk) assert.NoError(t, err) assert.NotEmpty(t, jwk) assert.Equal(t, k.KeyID, jwk.Kid) } func TestKey_signJWT(t *testing.T) { claims := &jwt.MapClaims{ "iss": "http://go.localhost.test", "iat": time.Now().Unix(), "exp": time.Now().Add(time.Second * 30).Unix(), "aud": "zebox/gojwk", "sub": "user_id", "email": "[email protected]", } k, err := NewKeys() require.NoError(t, err) err = k.Generate() require.NoError(t, err) assert.NotNil(t, k.publicKey) assert.NotNil(t, k.privateKey) tkn := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) jwk, err := k.JWK() t.Log(jwk.ToString()) assert.NoError(t, err) assert.NotEmpty(t, jwk) tkn.Header["alg"] = jwk.Alg tkn.Header["kid"] = jwk.Kid tokenString, err := tkn.SignedString(k.Private()) require.NoError(t, err) assert.NotEmpty(t, tokenString) t.Log(tokenString) checkClaims := &jwt.MapClaims{} token, err := jwt.ParseWithClaims(tokenString, checkClaims, jwk.KeyFunc) assert.NoError(t, err) assert.NotNil(t, token) } func deleteTestFile(t *testing.T) { err := os.Remove(testRootPath + testPrivateKey) assert.NoError(t, err) err = os.Remove(testRootPath + testPublicKey) assert.NoError(t, err) } // changeKeyFilesPermission use in GitHub action for test only func changeKeyFilesPermission(t *testing.T) { if os.Getenv("GITHUB_WORKSPACE") != "" { err := os.Chmod(testRootPath+testPrivateKey, 0777) assert.NoError(t, err) err = os.Chmod(testRootPath+testPublicKey, 0777) assert.NoError(t, err) } }
libraryCourse.js
import React, { Component } from "react"; import { connect } from "react-redux"; import * as actions from "../../actions"; import Icon from "../icon"; import Arrow from "../arrow"; import Action from "../action"; import AnimateHeight from "react-animate-height"; class LibraryCourse extends Component { constructor(props) { super(props); this.state = { status: true, height: 0 }; } handleCallback = function(status) { let height = this.state.height == 0 ? 'auto' : 0; if (!status) { document.getElementById(this.id).classList.add("library-course-selected"); } else { document.getElementById(this.id).classList.remove("library-course-selected"); } this.setState({ status, height }); }.bind(this); render() { this.id = `library-course-${this.props.id}`; return ( <div id={this.id} className="library-course"> <div className="library-course__title-check"> <div className="library-course__title">{this.props.title}</div> { this.props.enrolled ? Icon("fas fa-check", "library-course__icon") : ''} </div> <Arrow callback={status => this.handleCallback(status)} id={this.props.id} className="library-course__arrow" /> <Action id={this.props.id} onClick={() => this.props.toggleEnrolled(this.props.id)} className={`library-course__action ${this.props.enrolled ? 'action-remove' : ''}`} /> <AnimateHeight duration={300} height={this.state.height} > <div className="library-course__description"> <label>Course Description</label>
<p>{this.props.description}</p> </div> </AnimateHeight> </div> ); } } export default connect(null, actions)(LibraryCourse);
clipboard.rs
// Copyright 2022 pyke.io // 2019-2021 Tauri Programme within The Commons Conservancy // [https://tauri.studio/] // // 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. use std::{ffi::OsStr, os::windows::ffi::OsStrExt, ptr}; use windows::{ core::PWSTR, Win32::{ Foundation::{HANDLE, HWND}, System::{ DataExchange::{CloseClipboard, EmptyClipboard, GetClipboardData, OpenClipboard, RegisterClipboardFormatA, SetClipboardData}, Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE}, SystemServices::CF_UNICODETEXT } } }; use crate::clipboard::{ClipboardFormat, FormatId}; #[derive(Debug, Clone, Default)] pub struct
; impl Clipboard { pub fn write_text(&mut self, s: impl AsRef<str>) { let s = s.as_ref(); let format: ClipboardFormat = s.into(); self.put_formats(&[format]) } pub(crate) fn read_text(&self) -> Option<String> { with_clipboard(|| unsafe { let handle = GetClipboardData(CF_UNICODETEXT.0).unwrap_or_default(); if handle.is_invalid() { None } else { let unic_str = PWSTR(GlobalLock(handle.0) as *mut _); let mut len = 0; while *unic_str.0.offset(len) != 0 { len += 1; } let utf16_slice = std::slice::from_raw_parts(unic_str.0, len as usize); let result = String::from_utf16(utf16_slice); if let Ok(result) = result { GlobalUnlock(handle.0); return Some(result); } None } }) .flatten() } pub(crate) fn put_formats(&mut self, formats: &[ClipboardFormat]) { with_clipboard(|| unsafe { EmptyClipboard(); for format in formats { let handle = make_handle(format); let format_id = match get_format_id(format.identifier) { Some(id) => id, None => { #[cfg(debug_assertions)] println!("failed to register clipboard format {}", &format.identifier); continue; } }; #[cfg_attr(not(debug_assertions), allow(unused_variables))] if let Err(err) = SetClipboardData(format_id, handle) { #[cfg(debug_assertions)] println!("failed to set clipboard for fmt {}, error: {}", &format.identifier, err); } } }); } } fn get_format_id(format: FormatId) -> Option<u32> { if let Some((id, _)) = STANDARD_FORMATS.iter().find(|(_, s)| s == &format) { return Some(*id); } match format { ClipboardFormat::TEXT => Some(CF_UNICODETEXT.0), other => register_identifier(other) } } fn register_identifier(ident: &str) -> Option<u32> { unsafe { let pb_format = RegisterClipboardFormatA(ident); if pb_format == 0 { #[cfg(debug_assertions)] println!("failed to register clipboard format '{}'; error {}.", ident, windows::core::Error::from_win32().code().0); return None; } Some(pb_format) } } unsafe fn make_handle(format: &ClipboardFormat) -> HANDLE { HANDLE(if format.identifier == ClipboardFormat::TEXT { let s: &OsStr = std::str::from_utf8_unchecked(&format.data).as_ref(); let wstr: Vec<u16> = s.encode_wide().chain(Some(0)).collect(); let handle = GlobalAlloc(GMEM_MOVEABLE, wstr.len() * std::mem::size_of::<u16>()); let locked = GlobalLock(handle) as *mut _; ptr::copy_nonoverlapping(wstr.as_ptr(), locked, wstr.len()); GlobalUnlock(handle); handle } else { let handle = GlobalAlloc(GMEM_MOVEABLE, format.data.len() * std::mem::size_of::<u8>()); let locked = GlobalLock(handle) as *mut _; ptr::copy_nonoverlapping(format.data.as_ptr(), locked, format.data.len()); GlobalUnlock(handle); handle }) } fn with_clipboard<V>(f: impl FnOnce() -> V) -> Option<V> { unsafe { if !OpenClipboard(HWND::default()).as_bool() { return None; } let result = f(); CloseClipboard(); Some(result) } } // https://docs.microsoft.com/en-ca/windows/win32/dataxchg/standard-clipboard-formats static STANDARD_FORMATS: &[(u32, &str)] = &[ (1, "CF_TEXT"), (2, "CF_BITMAP"), (3, "CF_METAFILEPICT"), (4, "CF_SYLK"), (5, "CF_DIF"), (6, "CF_TIFF"), (7, "CF_OEMTEXT"), (8, "CF_DIB"), (9, "CF_PALETTE"), (10, "CF_PENDATA"), (11, "CF_RIFF"), (12, "CF_WAVE"), (13, "CF_UNICODETEXT"), (14, "CF_ENHMETAFILE"), (15, "CF_HDROP"), (16, "CF_LOCALE"), (17, "CF_DIBV5"), (0x0080, "CF_OWNERDISPLAY"), (0x0081, "CF_DSPTEXT"), (0x0082, "CF_DSPBITMAP"), (0x0083, "CF_DSPMETAFILEPICT"), (0x008E, "CF_DSPENHMETAFILE"), (0x0200, "CF_PRIVATEFIRST"), (0x02FF, "CF_PRIVATELAST"), (0x0300, "CF_GDIOBJFIRST"), (0x03FF, "CF_GDIOBJLAST") ];
Clipboard
onnx2lbann.py
#!/usr/bin/env python3 """ Convert an ONNX model to a LBANN model Run "./onnx2lbann.py --help" for more details. """ import argparse import onnx import google.protobuf.text_format as txtf import lbann.onnx.o2l from lbann.lbann_proto import lbann_pb2 dataLayerName = "image" labelLayerName = "label" probLayerName = "prob" crossEntropyLayerName = "cross_entropy" top1AccuracyLayerName = "top1_accuracy" top5AccuracyLayerName = "top5_accuracy" def convertAndSave(path, outputPath):
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert an ONNX model to a LBANN model", epilog="Usage: onnx2lbann.py model.onnx output.prototext") parser.add_argument("onnx_path", type=str, help="Path to an ONNX model") parser.add_argument("lbann_path", type=str, help="Path to a LBANN model in .prototext") args = parser.parse_args() onnxPath = args.onnx_path lbannPath = args.lbann_path convertAndSave(onnxPath, lbannPath)
o = onnx.load(path) onnxInputLayer, = set(map(lambda x: x.name, o.graph.input)) - set(map(lambda x: x.name, o.graph.initializer)) # Parse layers layers = lbann.onnx.o2l.onnxToLbannLayers( o, [dataLayerName, labelLayerName], {dataLayerName: onnxInputLayer}, ) # Add a softmax layer outputLayerName = layers[-1].name probLayerName = outputLayerName # layers.append(lbann_pb2.Layer(name=probLayerName, # parents=lbann.onnx.util.list2LbannList([outputLayerName]), # data_layout="data_parallel", # softmax=lbann_pb2.Softmax())) # Add metric layers for name, dic in [(crossEntropyLayerName, {"cross_entropy": lbann_pb2.CrossEntropy()}), (top1AccuracyLayerName, {"categorical_accuracy": lbann_pb2.CategoricalAccuracy()}), (top5AccuracyLayerName, {"top_k_categorical_accuracy": lbann_pb2.TopKCategoricalAccuracy(k=5)})]: layers.append(lbann_pb2.Layer(name=name, parents=lbann.onnx.util.list2LbannList([probLayerName, labelLayerName]), data_layout="data_parallel", **dic)) # Define an objective function objective = lbann_pb2.ObjectiveFunction( layer_term = [lbann_pb2.LayerTerm(layer=crossEntropyLayerName)], l2_weight_regularization = [lbann_pb2.L2WeightRegularization(scale_factor=1e-4)] ) # Add metrics metrics = [] for name, layer, unit in [("categorical accuracy", top1AccuracyLayerName, "%"), ("top-5 categorical accuracy", top5AccuracyLayerName, "%")]: metrics.append(lbann_pb2.Metric(layer_metric=lbann_pb2.LayerMetric(name=name, layer=layer, unit=unit))) # Add callbacks callbacks = [] for dic in [{"print": lbann_pb2.CallbackPrint()}, {"timer": lbann_pb2.CallbackTimer()}, {"imcomm": lbann_pb2.CallbackImComm(intermodel_comm_method="normal", all_optimizers=True)}]: callbacks.append(lbann_pb2.Callback(**dic)) model = lbann_pb2.Model( data_layout = "data_parallel", mini_batch_size = 256, block_size = 256, num_epochs = 10, num_parallel_readers = 0, procs_per_model = 0, objective_function = objective, metric = metrics, callback = callbacks, layer = layers ) with open(outputPath, "w") as f: f.write(txtf.MessageToString(lbann_pb2.LbannPB(model=model)))
mail_agent.py
from flask import Flask from flask_mail import Message, Mail from app.lazy import lazy_async class MailAgent: def __init__(self, app: Flask): self.mail = Mail(app) self.app = app @lazy_async def
(self, msg: Message): with self.app.app_context(): self.mail.send(msg) def send_mail(self, msg: Message): self._async_mail(msg)
_async_mail
build.rs
fn main()
{ let mut build = cc::Build::new(); build .files(&["basisu/transcoder/basisu_transcoder.cpp", "src/basisrs_interface.cpp"]) .cpp(true) .flag_if_supported("-std=c++14") .flag_if_supported("/std:c++14"); if cfg!(debug_assertions) { build.define("BASISU_FORCE_DEVEL_MESSAGES", None); } build.compile("basisu") }
factory.go
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metricsgenerationprocessor import ( "context" "fmt" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/config" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/processor/processorhelper" ) const ( // The value of "type" key in configuration. typeStr = "experimental_metricsgeneration" ) var processorCapabilities = consumer.Capabilities{MutatesData: true} // NewFactory returns a new factory for the Metrics Generation processor. func NewFactory() component.ProcessorFactory { return processorhelper.NewFactory( typeStr, createDefaultConfig, processorhelper.WithMetrics(createMetricsProcessor)) } func createDefaultConfig() config.Processor { return &Config{ ProcessorSettings: config.NewProcessorSettings(config.NewID(typeStr)), } } func
( ctx context.Context, params component.ProcessorCreateSettings, cfg config.Processor, nextConsumer consumer.Metrics, ) (component.MetricsProcessor, error) { processorConfig, ok := cfg.(*Config) if !ok { return nil, fmt.Errorf("configuration parsing error") } processorConfig.Validate() metricsProcessor := newMetricsGenerationProcessor(buildInternalConfig(processorConfig), params.Logger) return processorhelper.NewMetricsProcessor( cfg, nextConsumer, metricsProcessor, processorhelper.WithCapabilities(processorCapabilities)) } // buildInternalConfig constructs the internal metric generation rules func buildInternalConfig(config *Config) []internalRule { internalRules := make([]internalRule, len(config.Rules)) for i, rule := range config.Rules { customRule := internalRule{ name: rule.Name, ruleType: string(rule.Type), metric1: rule.Metric1, metric2: rule.Metric2, operation: string(rule.Operation), scaleBy: rule.ScaleBy, } internalRules[i] = customRule } return internalRules }
createMetricsProcessor
epaxos.go
package epaxos import ( "bloomfilter" "dlog" "encoding/binary" "epaxosproto" "fastrpc" "genericsmr" "genericsmrproto" "io" "log" "math" "state" "sync" "time" ) const MAX_DEPTH_DEP = 10 const TRUE = uint8(1) const FALSE = uint8(0) const DS = 5 const ADAPT_TIME_SEC = 10 const MAX_BATCH = 1000 const COMMIT_GRACE_PERIOD = 10 * 1e9 //Changing it to 2 microseconds for testing - actual 10 seconds const BF_K = 4 const BF_M_N = 32.0 var bf_PT uint32 const DO_CHECKPOINTING = false const HT_INIT_SIZE = 200000 const CHECKPOINT_PERIOD = 10000 var cpMarker []state.Command var cpcounter = 0 type CommitGraceTimeoutS struct { lock *sync.Mutex timeout uint64 flag bool } func NewCommitGraceTimeout(const_timeout uint64) *CommitGraceTimeoutS { return &CommitGraceTimeoutS{ new(sync.Mutex), const_timeout, false, } } func (c *CommitGraceTimeoutS) Check(timeout uint64) bool { c.lock.Lock() defer c.lock.Unlock() return c.flag || c.timeout <= timeout } func (c *CommitGraceTimeoutS) EnableFlag() { dlog.Println("Enabled timeout flag") c.lock.Lock() defer c.lock.Unlock() c.flag = true } func (c *CommitGraceTimeoutS) DisableFlag() { dlog.Println("Disabled timeout flag") c.lock.Lock() defer c.lock.Unlock() c.flag = false } var CommitGraceTimeout = NewCommitGraceTimeout(COMMIT_GRACE_PERIOD) type Replica struct { *genericsmr.Replica prepareChan chan fastrpc.Serializable preAcceptChan chan fastrpc.Serializable acceptChan chan fastrpc.Serializable commitChan chan fastrpc.Serializable commitShortChan chan fastrpc.Serializable prepareReplyChan chan fastrpc.Serializable preAcceptReplyChan chan fastrpc.Serializable preAcceptOKChan chan fastrpc.Serializable acceptReplyChan chan fastrpc.Serializable tryPreAcceptChan chan fastrpc.Serializable tryPreAcceptReplyChan chan fastrpc.Serializable timeoutMessageChan chan fastrpc.Serializable prepareRPC uint8 prepareReplyRPC uint8 preAcceptRPC uint8 preAcceptReplyRPC uint8 preAcceptOKRPC uint8 acceptRPC uint8 acceptReplyRPC uint8 commitRPC uint8 commitShortRPC uint8 tryPreAcceptRPC uint8 tryPreAcceptReplyRPC uint8 timeoutMessageRPC uint8 InstanceSpace [][]*Instance // the space of all instances (used and not yet used) crtInstance []int32 // highest active instance numbers that this replica knows about CommittedUpTo [DS]int32 // highest committed instance per replica that this replica knows about ExecedUpTo []int32 // instance up to which all commands have been executed (including iteslf) exec *Exec conflicts []map[state.Key]int32 maxSeqPerKey map[state.Key]int32 maxSeq int32 latestCPReplica int32 latestCPInstance int32 clientMutex *sync.Mutex // for synchronizing when sending replies to clients from multiple go-routines instancesToRecover chan *instanceId } type Instance struct { Cmds []state.Command ballot int32 Status int8 Seq int32 Deps [DS]int32 lb *LeaderBookkeeping Index, Lowlink int bfilter *bloomfilter.Bloomfilter } type instanceId struct { replica int32 instance int32 } type RecoveryInstance struct { cmds []state.Command status int8 seq int32 deps [DS]int32 preAcceptCount int leaderResponded bool } type LeaderBookkeeping struct { clientProposals []*genericsmr.Propose maxRecvBallot int32 prepareOKs int allEqual bool preAcceptOKs int acceptOKs int nacks int originalDeps [DS]int32 committedDeps []int32 recoveryInst *RecoveryInstance preparing bool tryingToPreAccept bool possibleQuorum []bool tpaOKs int } func NewReplica(id int, peerAddrList []string, masterAddrPort string, thrifty bool, exec bool, dreply bool, beacon bool, durable bool, slave bool) *Replica { r := &Replica{ genericsmr.NewReplica(id, peerAddrList, masterAddrPort, thrifty, exec, dreply, slave), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE*3), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE*3), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE*2), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), make(chan fastrpc.Serializable, genericsmr.CHAN_BUFFER_SIZE), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, make([][]*Instance, len(peerAddrList)), make([]int32, len(peerAddrList)), [DS]int32{-1, -1, -1, -1, -1}, make([]int32, len(peerAddrList)), nil, make([]map[state.Key]int32, len(peerAddrList)), make(map[state.Key]int32), 0, 0, -1, new(sync.Mutex), make(chan *instanceId, genericsmr.CHAN_BUFFER_SIZE)} r.Beacon = beacon r.Durable = durable for i := 0; i < r.N; i++ { r.InstanceSpace[i] = make([]*Instance, 2*1024*1024) r.crtInstance[i] = 0 r.ExecedUpTo[i] = -1 r.conflicts[i] = make(map[state.Key]int32, HT_INIT_SIZE) } for bf_PT = 1; math.Pow(2, float64(bf_PT))/float64(MAX_BATCH) < BF_M_N; { bf_PT++ } r.exec = &Exec{r} cpMarker = make([]state.Command, 0) //register RPCs r.prepareRPC = r.RegisterRPC(new(epaxosproto.Prepare), r.prepareChan) r.prepareReplyRPC = r.RegisterRPC(new(epaxosproto.PrepareReply), r.prepareReplyChan) r.preAcceptRPC = r.RegisterRPC(new(epaxosproto.PreAccept), r.preAcceptChan) r.preAcceptReplyRPC = r.RegisterRPC(new(epaxosproto.PreAcceptReply), r.preAcceptReplyChan) r.preAcceptOKRPC = r.RegisterRPC(new(epaxosproto.PreAcceptOK), r.preAcceptOKChan) r.acceptRPC = r.RegisterRPC(new(epaxosproto.Accept), r.acceptChan) r.acceptReplyRPC = r.RegisterRPC(new(epaxosproto.AcceptReply), r.acceptReplyChan) r.commitRPC = r.RegisterRPC(new(epaxosproto.Commit), r.commitChan) r.commitShortRPC = r.RegisterRPC(new(epaxosproto.CommitShort), r.commitShortChan) r.tryPreAcceptRPC = r.RegisterRPC(new(epaxosproto.TryPreAccept), r.tryPreAcceptChan) r.tryPreAcceptReplyRPC = r.RegisterRPC(new(epaxosproto.TryPreAcceptReply), r.tryPreAcceptReplyChan) r.timeoutMessageRPC = r.RegisterRPC(new(epaxosproto.TimeoutMessage), r.timeoutMessageChan) go r.run() return r } //append a log entry to stable storage func (r *Replica) recordInstanceMetadata(inst *Instance) { if !r.Durable { return } var b [9 + DS*4]byte binary.LittleEndian.PutUint32(b[0:4], uint32(inst.ballot)) b[4] = byte(inst.Status) binary.LittleEndian.PutUint32(b[5:9], uint32(inst.Seq)) l := 9 for _, dep := range inst.Deps { binary.LittleEndian.PutUint32(b[l:l+4], uint32(dep)) l += 4 } r.StableStore.Write(b[:]) } //write a sequence of commands to stable storage func (r *Replica) recordCommands(cmds []state.Command) { if !r.Durable { return } if cmds == nil { return } for i := 0; i < len(cmds); i++ { cmds[i].Marshal(io.Writer(r.StableStore)) } } //sync with the stable store func (r *Replica) sync() { if !r.Durable { return } r.StableStore.Sync() } /* Clock goroutine */ var fastClockChan chan bool var slowClockChan chan bool func (r *Replica) fastClock() { for !r.Shutdown { time.Sleep(5 * 1e6) // 5 ms fastClockChan <- true } } func (r *Replica) slowClock() { for !r.Shutdown { time.Sleep(150 * 1e6) // 150 ms slowClockChan <- true } } func (r *Replica) stopAdapting() { time.Sleep(1000 * 1000 * 1000 * ADAPT_TIME_SEC) r.Beacon = false time.Sleep(1000 * 1000 * 1000) for i := 0; i < r.N-1; i++ { min := i for j := i + 1; j < r.N-1; j++ { if r.Ewma[r.PreferredPeerOrder[j]] < r.Ewma[r.PreferredPeerOrder[min]] { min = j } } aux := r.PreferredPeerOrder[i] r.PreferredPeerOrder[i] = r.PreferredPeerOrder[min] r.PreferredPeerOrder[min] = aux } log.Println(r.PreferredPeerOrder) } // Just a one time thing. Used for PCT testing. func (r *Replica) sendTimeoutMessage() { if r.Slave { args := &epaxosproto.TimeoutMessage{} r.SendMsgMaster(r.Id, r.timeoutMessageRPC, args) } } var conflicted, weird, slow, happy int /* ============= */ /*********************************** Main event processing loop * ************************************/ func (r *Replica) run() { if r.Slave { r.ConnectToMaster() } r.ConnectToPeers() dlog.Println("Waiting for client connections") go r.WaitForClientConnections() if r.Exec { go r.executeCommands() } // Sending message after connecting to master and clients if r.Slave { r.sendTimeoutMessage() } if r.Id == 0 { //init quorum read lease quorum := make([]int32, r.N/2+1) for i := 0; i <= r.N/2; i++ { quorum[i] = int32(i) } r.UpdatePreferredPeerOrder(quorum) } slowClockChan = make(chan bool, 1) fastClockChan = make(chan bool, 1) go r.slowClock() //Enabled when batching for 5ms if MAX_BATCH > 100 { go r.fastClock() } if r.Beacon { go r.stopAdapting() } onOffProposeChan := r.ProposeChan for !r.Shutdown { select { case propose := <-onOffProposeChan: //got a Propose from a client dlog.Printf("Proposal with op %d\n", propose.Command.Op) r.handlePropose(propose) //deactivate new proposals channel to prioritize the handling of other protocol messages, //and to allow commands to accumulate for batching onOffProposeChan = nil break case <-fastClockChan: //activate new proposals channel onOffProposeChan = r.ProposeChan break case prepareS := <-r.prepareChan: prepare := prepareS.(*epaxosproto.Prepare) //got a Prepare message dlog.Printf("Received Prepare for instance %d.%d\n", prepare.Replica, prepare.Instance) r.handlePrepare(prepare) break case preAcceptS := <-r.preAcceptChan: preAccept := preAcceptS.(*epaxosproto.PreAccept) //got a PreAccept message dlog.Printf("Received PreAccept for instance %d.%d\n", preAccept.LeaderId, preAccept.Instance) r.handlePreAccept(preAccept) break case acceptS := <-r.acceptChan: accept := acceptS.(*epaxosproto.Accept) //got an Accept message dlog.Printf("Received Accept for instance %d.%d\n", accept.LeaderId, accept.Instance) r.handleAccept(accept) break case commitS := <-r.commitChan: commit := commitS.(*epaxosproto.Commit) //got a Commit message dlog.Printf("Received Commit for instance %d.%d\n", commit.LeaderId, commit.Instance) r.handleCommit(commit) break case commitS := <-r.commitShortChan: commit := commitS.(*epaxosproto.CommitShort) //got a Commit message dlog.Printf("Received Commit for instance %d.%d\n", commit.LeaderId, commit.Instance) r.handleCommitShort(commit) break case prepareReplyS := <-r.prepareReplyChan: prepareReply := prepareReplyS.(*epaxosproto.PrepareReply) //got a Prepare reply dlog.Printf("Received PrepareReply for instance %d.%d\n", prepareReply.Replica, prepareReply.Instance) r.handlePrepareReply(prepareReply) break case preAcceptReplyS := <-r.preAcceptReplyChan: preAcceptReply := preAcceptReplyS.(*epaxosproto.PreAcceptReply) //got a PreAccept reply dlog.Printf("Received PreAcceptReply for instance %d.%d\n", preAcceptReply.Replica, preAcceptReply.Instance) r.handlePreAcceptReply(preAcceptReply) break case preAcceptOKS := <-r.preAcceptOKChan: preAcceptOK := preAcceptOKS.(*epaxosproto.PreAcceptOK) //got a PreAccept reply dlog.Printf("Received PreAcceptOK for instance %d.%d\n", r.Id, preAcceptOK.Instance) r.handlePreAcceptOK(preAcceptOK) break case acceptReplyS := <-r.acceptReplyChan: acceptReply := acceptReplyS.(*epaxosproto.AcceptReply) //got an Accept reply dlog.Printf("Received AcceptReply for instance %d.%d\n", acceptReply.Replica, acceptReply.Instance) r.handleAcceptReply(acceptReply) break case tryPreAcceptS := <-r.tryPreAcceptChan: tryPreAccept := tryPreAcceptS.(*epaxosproto.TryPreAccept) dlog.Printf("Received TryPreAccept for instance %d.%d\n", tryPreAccept.Replica, tryPreAccept.Instance) r.handleTryPreAccept(tryPreAccept) break case tryPreAcceptReplyS := <-r.tryPreAcceptReplyChan: tryPreAcceptReply := tryPreAcceptReplyS.(*epaxosproto.TryPreAcceptReply) dlog.Printf("Received TryPreAcceptReply for instance %d.%d\n", tryPreAcceptReply.Replica, tryPreAcceptReply.Instance) r.handleTryPreAcceptReply(tryPreAcceptReply) break case beacon := <-r.BeaconChan: dlog.Printf("Received Beacon from replica %d with timestamp %d\n", beacon.Rid, beacon.Timestamp) r.ReplyBeacon(beacon) break case _ = <-r.timeoutMessageChan: dlog.Println("Recived timeout message from self") CommitGraceTimeout.EnableFlag() break case <-slowClockChan: if r.Beacon { for q := int32(0); q < int32(r.N); q++ { if q == r.Id { continue } r.SendBeacon(q) } } break case <-r.OnClientConnect: log.Printf("weird %d; conflicted %d; slow %d; happy %d\n", weird, conflicted, slow, happy) weird, conflicted, slow, happy = 0, 0, 0, 0 case iid := <-r.instancesToRecover: r.startRecoveryForInstance(iid.replica, iid.instance) } } } /*********************************** Command execution thread * ************************************/ func (r *Replica) executeCommands() { const SLEEP_TIME_NS = 1e6 problemInstance := make([]int32, r.N) timeout := make([]uint64, r.N) for q := 0; q < r.N; q++ { problemInstance[q] = -1 timeout[q] = 0 } for !r.Shutdown { executed := false for q := 0; q < r.N; q++ { inst := int32(0) for inst = r.ExecedUpTo[q] + 1; inst < r.crtInstance[q]; inst++ { if r.InstanceSpace[q][inst] != nil && r.InstanceSpace[q][inst].Status == epaxosproto.EXECUTED { if inst == r.ExecedUpTo[q]+1 { r.ExecedUpTo[q] = inst } continue } if r.InstanceSpace[q][inst] == nil || r.InstanceSpace[q][inst].Status != epaxosproto.COMMITTED { if inst == problemInstance[q] { timeout[q] += SLEEP_TIME_NS if CommitGraceTimeout.Check(timeout[q]) { dlog.Printf("Adding instance : (%d, %d) for recovery", int32(q), inst) r.instancesToRecover <- &instanceId{int32(q), inst} timeout[q] = 0 CommitGraceTimeout.DisableFlag() } } else { problemInstance[q] = inst timeout[q] = 0 } if r.InstanceSpace[q][inst] == nil { continue } break } if ok := r.exec.executeCommand(int32(q), inst); ok { executed = true if inst == r.ExecedUpTo[q]+1 { r.ExecedUpTo[q] = inst } } } } if !executed { time.Sleep(SLEEP_TIME_NS) } //log.Println(r.ExecedUpTo, " ", r.crtInstance) } } /* Ballot helper functions */ func (r *Replica) makeUniqueBallot(ballot int32) int32 { return (ballot << 4) | r.Id } func (r *Replica) makeBallotLargerThan(ballot int32) int32 { return r.makeUniqueBallot((ballot >> 4) + 1) } func isInitialBallot(ballot int32) bool { return (ballot >> 4) == 0 } func replicaIdFromBallot(ballot int32) int32 { return ballot & 15 } /********************************************************************** inter-replica communication ***********************************************************************/ func (r *Replica) replyPrepare(replicaId int32, reply *epaxosproto.PrepareReply) { r.SendMsgSlaveCheck(replicaId, r.prepareReplyRPC, reply) } func (r *Replica) replyPreAccept(replicaId int32, reply *epaxosproto.PreAcceptReply) { r.SendMsgSlaveCheck(replicaId, r.preAcceptReplyRPC, reply) } func (r *Replica) replyAccept(replicaId int32, reply *epaxosproto.AcceptReply) { r.SendMsgSlaveCheck(replicaId, r.acceptReplyRPC, reply) } func (r *Replica) replyTryPreAccept(replicaId int32, reply *epaxosproto.TryPreAcceptReply) { r.SendMsgSlaveCheck(replicaId, r.tryPreAcceptReplyRPC, reply) } func (r *Replica) bcastPrepare(replica int32, instance int32, ballot int32) { defer func() { if err := recover(); err != nil { dlog.Println("Prepare bcast failed:", err) } }() args := &epaxosproto.Prepare{r.Id, replica, instance, ballot} n := r.N - 1 if r.Thrifty { n = r.N / 2 } q := r.Id for sent := 0; sent < n; { q = (q + 1) % int32(r.N) if q == r.Id { dlog.Println("Not enough replicas alive!") break } if !r.Alive[q] { continue } r.SendMsgSlaveCheck(q, r.prepareRPC, args) sent++ } } var pa epaxosproto.PreAccept func (r *Replica) bcastPreAccept(replica int32, instance int32, ballot int32, cmds []state.Command, seq int32, deps [DS]int32) { defer func() { if err := recover(); err != nil { dlog.Println("PreAccept bcast failed:", err) } }() pa.LeaderId = r.Id pa.Replica = replica pa.Instance = instance pa.Ballot = ballot pa.Command = cmds pa.Seq = seq pa.Deps = deps args := &pa n := r.N - 1 if r.Thrifty { n = r.N / 2 } sent := 0 for q := 0; q < r.N-1; q++ { if !r.Alive[r.PreferredPeerOrder[q]] { continue } r.SendMsgSlaveCheck(r.PreferredPeerOrder[q], r.preAcceptRPC, args) sent++ if sent >= n { break } } } var tpa epaxosproto.TryPreAccept func (r *Replica) bcastTryPreAccept(replica int32, instance int32, ballot int32, cmds []state.Command, seq int32, deps [DS]int32) { defer func() { if err := recover(); err != nil { dlog.Println("PreAccept bcast failed:", err) } }() tpa.LeaderId = r.Id tpa.Replica = replica tpa.Instance = instance tpa.Ballot = ballot tpa.Command = cmds tpa.Seq = seq tpa.Deps = deps args := &pa for q := int32(0); q < int32(r.N); q++ { if q == r.Id { continue } if !r.Alive[q] { continue } r.SendMsgSlaveCheck(q, r.tryPreAcceptRPC, args) } } var ea epaxosproto.Accept func (r *Replica) bcastAccept(replica int32, instance int32, ballot int32, count int32, seq int32, deps [DS]int32) { defer func() { if err := recover(); err != nil { dlog.Println("Accept bcast failed:", err) } }() ea.LeaderId = r.Id ea.Replica = replica ea.Instance = instance ea.Ballot = ballot ea.Count = count ea.Seq = seq ea.Deps = deps args := &ea n := r.N - 1 if r.Thrifty { n = r.N / 2 } sent := 0 for q := 0; q < r.N-1; q++ { if !r.Alive[r.PreferredPeerOrder[q]] { continue } r.SendMsgSlaveCheck(r.PreferredPeerOrder[q], r.acceptRPC, args) sent++ if sent >= n { break } } } var ec epaxosproto.Commit var ecs epaxosproto.CommitShort func (r *Replica) bcastCommit(replica int32, instance int32, cmds []state.Command, seq int32, deps [DS]int32) { defer func() { if err := recover(); err != nil { dlog.Println("Commit bcast failed:", err) } }() ec.LeaderId = r.Id ec.Replica = replica ec.Instance = instance ec.Command = cmds ec.Seq = seq ec.Deps = deps args := &ec ecs.LeaderId = r.Id ecs.Replica = replica ecs.Instance = instance ecs.Count = int32(len(cmds)) ecs.Seq = seq ecs.Deps = deps argsShort := &ecs sent := 0 for q := 0; q < r.N-1; q++ { if !r.Alive[r.PreferredPeerOrder[q]] { continue } if r.Thrifty && sent >= r.N/2 { r.SendMsgSlaveCheck(r.PreferredPeerOrder[q], r.commitRPC, args) } else { r.SendMsgSlaveCheck(r.PreferredPeerOrder[q], r.commitShortRPC, argsShort) sent++ } } } /****************************************************************** Helper functions *******************************************************************/ func (r *Replica) clearHashtables() { for q := 0; q < r.N; q++ { r.conflicts[q] = make(map[state.Key]int32, HT_INIT_SIZE) } } func (r *Replica) updateCommitted(replica int32) { for r.InstanceSpace[replica][r.CommittedUpTo[replica]+1] != nil && (r.InstanceSpace[replica][r.CommittedUpTo[replica]+1].Status == epaxosproto.COMMITTED || r.InstanceSpace[replica][r.CommittedUpTo[replica]+1].Status == epaxosproto.EXECUTED) { r.CommittedUpTo[replica] = r.CommittedUpTo[replica] + 1 } } func (r *Replica) updateConflicts(cmds []state.Command, replica int32, instance int32, seq int32) { for i := 0; i < len(cmds); i++ { if d, present := r.conflicts[replica][cmds[i].K]; present { if d < instance { r.conflicts[replica][cmds[i].K] = instance } } else { r.conflicts[replica][cmds[i].K] = instance } if s, present := r.maxSeqPerKey[cmds[i].K]; present { if s < seq { r.maxSeqPerKey[cmds[i].K] = seq } } else { r.maxSeqPerKey[cmds[i].K] = seq } } } func (r *Replica) updateAttributes(cmds []state.Command, seq int32, deps [DS]int32, replica int32, instance int32) (int32, [DS]int32, bool) { changed := false for q := 0; q < r.N; q++ { if r.Id != replica && int32(q) == replica
for i := 0; i < len(cmds); i++ { if d, present := (r.conflicts[q])[cmds[i].K]; present { if d > deps[q] { deps[q] = d if seq <= r.InstanceSpace[q][d].Seq { seq = r.InstanceSpace[q][d].Seq + 1 } changed = true break } } } } for i := 0; i < len(cmds); i++ { if s, present := r.maxSeqPerKey[cmds[i].K]; present { if seq <= s { changed = true seq = s + 1 } } } return seq, deps, changed } func (r *Replica) mergeAttributes(seq1 int32, deps1 [DS]int32, seq2 int32, deps2 [DS]int32) (int32, [DS]int32, bool) { equal := true if seq1 != seq2 { equal = false if seq2 > seq1 { seq1 = seq2 } } for q := 0; q < r.N; q++ { if int32(q) == r.Id { continue } if deps1[q] != deps2[q] { equal = false if deps2[q] > deps1[q] { deps1[q] = deps2[q] } } } return seq1, deps1, equal } func equal(deps1 *[DS]int32, deps2 *[DS]int32) bool { for i := 0; i < len(deps1); i++ { if deps1[i] != deps2[i] { return false } } return true } func bfFromCommands(cmds []state.Command) *bloomfilter.Bloomfilter { if cmds == nil { return nil } bf := bloomfilter.NewPowTwo(bf_PT, BF_K) for i := 0; i < len(cmds); i++ { bf.AddUint64(uint64(cmds[i].K)) } return bf } /********************************************************************** PHASE 1 ***********************************************************************/ func (r *Replica) handlePropose(propose *genericsmr.Propose) { //TODO!! Handle client retries batchSize := len(r.ProposeChan) + 1 if batchSize > MAX_BATCH { batchSize = MAX_BATCH } instNo := r.crtInstance[r.Id] r.crtInstance[r.Id]++ dlog.Printf("Starting instance %d\n", instNo) dlog.Printf("Batching %d\n", batchSize) cmds := make([]state.Command, batchSize) proposals := make([]*genericsmr.Propose, batchSize) cmds[0] = propose.Command proposals[0] = propose for i := 1; i < batchSize; i++ { prop := <-r.ProposeChan cmds[i] = prop.Command proposals[i] = prop } r.startPhase1(r.Id, instNo, 0, proposals, cmds, batchSize) } func (r *Replica) startPhase1(replica int32, instance int32, ballot int32, proposals []*genericsmr.Propose, cmds []state.Command, batchSize int) { //init command attributes seq := int32(0) var deps [DS]int32 for q := 0; q < r.N; q++ { deps[q] = -1 } seq, deps, _ = r.updateAttributes(cmds, seq, deps, replica, instance) r.InstanceSpace[r.Id][instance] = &Instance{ cmds, ballot, epaxosproto.PREACCEPTED, seq, deps, &LeaderBookkeeping{proposals, 0, 0, true, 0, 0, 0, deps, []int32{-1, -1, -1, -1, -1}, nil, false, false, nil, 0}, 0, 0, nil} r.updateConflicts(cmds, r.Id, instance, seq) if seq >= r.maxSeq { r.maxSeq = seq + 1 } r.recordInstanceMetadata(r.InstanceSpace[r.Id][instance]) r.recordCommands(cmds) r.sync() r.bcastPreAccept(r.Id, instance, ballot, cmds, seq, deps) cpcounter += batchSize if r.Id == 0 && DO_CHECKPOINTING && cpcounter >= CHECKPOINT_PERIOD { cpcounter = 0 //Propose a checkpoint command to act like a barrier. //This allows replicas to discard their dependency hashtables. r.crtInstance[r.Id]++ instance++ r.maxSeq++ for q := 0; q < r.N; q++ { deps[q] = r.crtInstance[q] - 1 } r.InstanceSpace[r.Id][instance] = &Instance{ cpMarker, 0, epaxosproto.PREACCEPTED, r.maxSeq, deps, &LeaderBookkeeping{nil, 0, 0, true, 0, 0, 0, deps, nil, nil, false, false, nil, 0}, 0, 0, nil} r.latestCPReplica = r.Id r.latestCPInstance = instance //discard dependency hashtables r.clearHashtables() r.recordInstanceMetadata(r.InstanceSpace[r.Id][instance]) r.sync() r.bcastPreAccept(r.Id, instance, 0, cpMarker, r.maxSeq, deps) } } func (r *Replica) handlePreAccept(preAccept *epaxosproto.PreAccept) { inst := r.InstanceSpace[preAccept.LeaderId][preAccept.Instance] if preAccept.Seq >= r.maxSeq { r.maxSeq = preAccept.Seq + 1 } if inst != nil && (inst.Status == epaxosproto.COMMITTED || inst.Status == epaxosproto.ACCEPTED) { //reordered handling of commit/accept and pre-accept if inst.Cmds == nil { r.InstanceSpace[preAccept.LeaderId][preAccept.Instance].Cmds = preAccept.Command r.updateConflicts(preAccept.Command, preAccept.Replica, preAccept.Instance, preAccept.Seq) //r.InstanceSpace[preAccept.LeaderId][preAccept.Instance].bfilter = bfFromCommands(preAccept.Command) } r.recordCommands(preAccept.Command) r.sync() return } if preAccept.Instance >= r.crtInstance[preAccept.Replica] { r.crtInstance[preAccept.Replica] = preAccept.Instance + 1 } //update attributes for command seq, deps, changed := r.updateAttributes(preAccept.Command, preAccept.Seq, preAccept.Deps, preAccept.Replica, preAccept.Instance) uncommittedDeps := false for q := 0; q < r.N; q++ { if deps[q] > r.CommittedUpTo[q] { uncommittedDeps = true break } } status := epaxosproto.PREACCEPTED_EQ if changed { status = epaxosproto.PREACCEPTED } if inst != nil { if preAccept.Ballot < inst.ballot { r.replyPreAccept(preAccept.LeaderId, &epaxosproto.PreAcceptReply{ preAccept.Replica, preAccept.Instance, FALSE, inst.ballot, inst.Seq, inst.Deps, r.CommittedUpTo}) return } else { inst.Cmds = preAccept.Command inst.Seq = seq inst.Deps = deps inst.ballot = preAccept.Ballot inst.Status = status } } else { r.InstanceSpace[preAccept.Replica][preAccept.Instance] = &Instance{ preAccept.Command, preAccept.Ballot, status, seq, deps, nil, 0, 0, nil} } r.updateConflicts(preAccept.Command, preAccept.Replica, preAccept.Instance, preAccept.Seq) r.recordInstanceMetadata(r.InstanceSpace[preAccept.Replica][preAccept.Instance]) r.recordCommands(preAccept.Command) r.sync() if len(preAccept.Command) == 0 { //checkpoint //update latest checkpoint info r.latestCPReplica = preAccept.Replica r.latestCPInstance = preAccept.Instance //discard dependency hashtables r.clearHashtables() } if changed || uncommittedDeps || preAccept.Replica != preAccept.LeaderId || !isInitialBallot(preAccept.Ballot) { r.replyPreAccept(preAccept.LeaderId, &epaxosproto.PreAcceptReply{ preAccept.Replica, preAccept.Instance, TRUE, preAccept.Ballot, seq, deps, r.CommittedUpTo}) } else { pok := &epaxosproto.PreAcceptOK{preAccept.Instance} r.SendMsgSlaveCheck(preAccept.LeaderId, r.preAcceptOKRPC, pok) } dlog.Printf("I've replied to the PreAccept\n") } func (r *Replica) handlePreAcceptReply(pareply *epaxosproto.PreAcceptReply) { dlog.Printf("Handling PreAccept reply\n") inst := r.InstanceSpace[pareply.Replica][pareply.Instance] if inst.Status != epaxosproto.PREACCEPTED { // we've moved on, this is a delayed reply return } if inst.ballot != pareply.Ballot { return } if pareply.OK == FALSE { // TODO: there is probably another active leader inst.lb.nacks++ if pareply.Ballot > inst.lb.maxRecvBallot { inst.lb.maxRecvBallot = pareply.Ballot } if inst.lb.nacks >= r.N/2 { // TODO } return } inst.lb.preAcceptOKs++ var equal bool inst.Seq, inst.Deps, equal = r.mergeAttributes(inst.Seq, inst.Deps, pareply.Seq, pareply.Deps) if (r.N <= 3 && !r.Thrifty) || inst.lb.preAcceptOKs > 1 { inst.lb.allEqual = inst.lb.allEqual && equal if !equal { conflicted++ } } allCommitted := true for q := 0; q < r.N; q++ { if inst.lb.committedDeps[q] < pareply.CommittedDeps[q] { inst.lb.committedDeps[q] = pareply.CommittedDeps[q] } if inst.lb.committedDeps[q] < r.CommittedUpTo[q] { inst.lb.committedDeps[q] = r.CommittedUpTo[q] } if inst.lb.committedDeps[q] < inst.Deps[q] { allCommitted = false } } //can we commit on the fast path? if inst.lb.preAcceptOKs >= r.N/3 && inst.lb.allEqual && allCommitted && isInitialBallot(inst.ballot) { happy++ dlog.Printf("Fast path for instance %d.%d\n", pareply.Replica, pareply.Instance) r.InstanceSpace[pareply.Replica][pareply.Instance].Status = epaxosproto.COMMITTED r.updateCommitted(pareply.Replica) if inst.lb.clientProposals != nil && !r.Dreply { // give clients the all clear for i := 0; i < len(inst.lb.clientProposals); i++ { r.ReplyProposeTS( &genericsmrproto.ProposeReplyTS{ TRUE, inst.lb.clientProposals[i].CommandId, state.NIL, inst.lb.clientProposals[i].Timestamp}, inst.lb.clientProposals[i].Reply) } } r.recordInstanceMetadata(inst) r.sync() //is this necessary here? r.bcastCommit(pareply.Replica, pareply.Instance, inst.Cmds, inst.Seq, inst.Deps) } else if inst.lb.preAcceptOKs >= r.N/3 { if !allCommitted { weird++ } slow++ inst.Status = epaxosproto.ACCEPTED r.bcastAccept(pareply.Replica, pareply.Instance, inst.ballot, int32(len(inst.Cmds)), inst.Seq, inst.Deps) } dlog.Printf("Handled PreAccept Reply\n") //TODO: take the slow path if messages are slow to arrive } func (r *Replica) handlePreAcceptOK(pareply *epaxosproto.PreAcceptOK) { dlog.Printf("Handling PreAccept reply\n") inst := r.InstanceSpace[r.Id][pareply.Instance] if inst.Status != epaxosproto.PREACCEPTED { // we've moved on, this is a delayed reply return } if !isInitialBallot(inst.ballot) { return } inst.lb.preAcceptOKs++ allCommitted := true for q := 0; q < r.N; q++ { if inst.lb.committedDeps[q] < inst.lb.originalDeps[q] { inst.lb.committedDeps[q] = inst.lb.originalDeps[q] } if inst.lb.committedDeps[q] < r.CommittedUpTo[q] { inst.lb.committedDeps[q] = r.CommittedUpTo[q] } if inst.lb.committedDeps[q] < inst.Deps[q] { allCommitted = false } } //can we commit on the fast path? if inst.lb.preAcceptOKs >= r.N/3 && inst.lb.allEqual && allCommitted && isInitialBallot(inst.ballot) { happy++ r.InstanceSpace[r.Id][pareply.Instance].Status = epaxosproto.COMMITTED r.updateCommitted(r.Id) if inst.lb.clientProposals != nil && !r.Dreply { // give clients the all clear for i := 0; i < len(inst.lb.clientProposals); i++ { r.ReplyProposeTS( &genericsmrproto.ProposeReplyTS{ TRUE, inst.lb.clientProposals[i].CommandId, state.NIL, inst.lb.clientProposals[i].Timestamp}, inst.lb.clientProposals[i].Reply) } } r.recordInstanceMetadata(inst) r.sync() //is this necessary here? r.bcastCommit(r.Id, pareply.Instance, inst.Cmds, inst.Seq, inst.Deps) } else if inst.lb.preAcceptOKs >= r.N/3 { if !allCommitted { weird++ } slow++ inst.Status = epaxosproto.ACCEPTED r.bcastAccept(r.Id, pareply.Instance, inst.ballot, int32(len(inst.Cmds)), inst.Seq, inst.Deps) } dlog.Printf("Handled PreAcceptOK\n") //TODO: take the slow path if messages are slow to arrive } /********************************************************************** PHASE 2 ***********************************************************************/ func (r *Replica) handleAccept(accept *epaxosproto.Accept) { inst := r.InstanceSpace[accept.LeaderId][accept.Instance] if accept.Seq >= r.maxSeq { r.maxSeq = accept.Seq + 1 } if inst != nil && (inst.Status == epaxosproto.COMMITTED || inst.Status == epaxosproto.EXECUTED) { return } if accept.Instance >= r.crtInstance[accept.LeaderId] { r.crtInstance[accept.LeaderId] = accept.Instance + 1 } if inst != nil { if accept.Ballot < inst.ballot { r.replyAccept(accept.LeaderId, &epaxosproto.AcceptReply{accept.Replica, accept.Instance, FALSE, inst.ballot}) return } inst.Status = epaxosproto.ACCEPTED inst.Seq = accept.Seq inst.Deps = accept.Deps } else { r.InstanceSpace[accept.LeaderId][accept.Instance] = &Instance{ nil, accept.Ballot, epaxosproto.ACCEPTED, accept.Seq, accept.Deps, nil, 0, 0, nil} if accept.Count == 0 { //checkpoint //update latest checkpoint info r.latestCPReplica = accept.Replica r.latestCPInstance = accept.Instance //discard dependency hashtables r.clearHashtables() } } r.recordInstanceMetadata(r.InstanceSpace[accept.Replica][accept.Instance]) r.sync() r.replyAccept(accept.LeaderId, &epaxosproto.AcceptReply{ accept.Replica, accept.Instance, TRUE, accept.Ballot}) dlog.Printf("Handled Accept\n") } func (r *Replica) handleAcceptReply(areply *epaxosproto.AcceptReply) { inst := r.InstanceSpace[areply.Replica][areply.Instance] if inst.Status != epaxosproto.ACCEPTED { // we've move on, these are delayed replies, so just ignore return } if inst.ballot != areply.Ballot { return } if areply.OK == FALSE { // TODO: there is probably another active leader inst.lb.nacks++ if areply.Ballot > inst.lb.maxRecvBallot { inst.lb.maxRecvBallot = areply.Ballot } if inst.lb.nacks >= r.N/2 { // TODO } return } inst.lb.acceptOKs++ if inst.lb.acceptOKs+1 > r.N/3 { r.InstanceSpace[areply.Replica][areply.Instance].Status = epaxosproto.COMMITTED r.updateCommitted(areply.Replica) if inst.lb.clientProposals != nil && !r.Dreply { // give clients the all clear for i := 0; i < len(inst.lb.clientProposals); i++ { r.ReplyProposeTS( &genericsmrproto.ProposeReplyTS{ TRUE, inst.lb.clientProposals[i].CommandId, state.NIL, inst.lb.clientProposals[i].Timestamp}, inst.lb.clientProposals[i].Reply) } } r.recordInstanceMetadata(inst) r.sync() //is this necessary here? r.bcastCommit(areply.Replica, areply.Instance, inst.Cmds, inst.Seq, inst.Deps) } dlog.Printf("Handled AcceptReply\n") } /********************************************************************** COMMIT ***********************************************************************/ func (r *Replica) handleCommit(commit *epaxosproto.Commit) { inst := r.InstanceSpace[commit.Replica][commit.Instance] if commit.Seq >= r.maxSeq { r.maxSeq = commit.Seq + 1 } if commit.Instance >= r.crtInstance[commit.Replica] { r.crtInstance[commit.Replica] = commit.Instance + 1 } if inst != nil { if inst.lb != nil && inst.lb.clientProposals != nil && len(commit.Command) == 0 { //someone committed a NO-OP, but we have proposals for this instance //try in a different instance for _, p := range inst.lb.clientProposals { r.ProposeChan <- p } inst.lb = nil } inst.Seq = commit.Seq inst.Deps = commit.Deps inst.Status = epaxosproto.COMMITTED } else { r.InstanceSpace[commit.Replica][int(commit.Instance)] = &Instance{ commit.Command, 0, epaxosproto.COMMITTED, commit.Seq, commit.Deps, nil, 0, 0, nil} r.updateConflicts(commit.Command, commit.Replica, commit.Instance, commit.Seq) if len(commit.Command) == 0 { //checkpoint //update latest checkpoint info r.latestCPReplica = commit.Replica r.latestCPInstance = commit.Instance //discard dependency hashtables r.clearHashtables() } } r.updateCommitted(commit.Replica) r.recordInstanceMetadata(r.InstanceSpace[commit.Replica][commit.Instance]) r.recordCommands(commit.Command) dlog.Printf("Handled Commit\n") } func (r *Replica) handleCommitShort(commit *epaxosproto.CommitShort) { inst := r.InstanceSpace[commit.Replica][commit.Instance] if commit.Instance >= r.crtInstance[commit.Replica] { r.crtInstance[commit.Replica] = commit.Instance + 1 } if inst != nil { if inst.lb != nil && inst.lb.clientProposals != nil { //try command in a different instance for _, p := range inst.lb.clientProposals { r.ProposeChan <- p } inst.lb = nil } inst.Seq = commit.Seq inst.Deps = commit.Deps inst.Status = epaxosproto.COMMITTED } else { r.InstanceSpace[commit.Replica][commit.Instance] = &Instance{ nil, 0, epaxosproto.COMMITTED, commit.Seq, commit.Deps, nil, 0, 0, nil} if commit.Count == 0 { //checkpoint //update latest checkpoint info r.latestCPReplica = commit.Replica r.latestCPInstance = commit.Instance //discard dependency hashtables r.clearHashtables() } } r.updateCommitted(commit.Replica) r.recordInstanceMetadata(r.InstanceSpace[commit.Replica][commit.Instance]) dlog.Printf("Handled CommitShort\n") } /********************************************************************** RECOVERY ACTIONS ***********************************************************************/ func (r *Replica) startRecoveryForInstance(replica int32, instance int32) { dlog.Printf("Starting recovery for instance : (%d, %d)", replica, instance) var nildeps [DS]int32 if r.InstanceSpace[replica][instance] == nil { r.InstanceSpace[replica][instance] = &Instance{nil, 0, epaxosproto.NONE, 0, nildeps, nil, 0, 0, nil} } inst := r.InstanceSpace[replica][instance] if inst.lb == nil { inst.lb = &LeaderBookkeeping{nil, -1, 0, false, 0, 0, 0, nildeps, nil, nil, true, false, nil, 0} } else { inst.lb = &LeaderBookkeeping{inst.lb.clientProposals, -1, 0, false, 0, 0, 0, nildeps, nil, nil, true, false, nil, 0} } if inst.Status == epaxosproto.ACCEPTED { inst.lb.recoveryInst = &RecoveryInstance{inst.Cmds, inst.Status, inst.Seq, inst.Deps, 0, false} inst.lb.maxRecvBallot = inst.ballot } else if inst.Status >= epaxosproto.PREACCEPTED { inst.lb.recoveryInst = &RecoveryInstance{inst.Cmds, inst.Status, inst.Seq, inst.Deps, 1, (r.Id == replica)} } //compute larger ballot inst.ballot = r.makeBallotLargerThan(inst.ballot) r.bcastPrepare(replica, instance, inst.ballot) } func (r *Replica) handlePrepare(prepare *epaxosproto.Prepare) { inst := r.InstanceSpace[prepare.Replica][prepare.Instance] var preply *epaxosproto.PrepareReply var nildeps [DS]int32 if inst == nil { r.InstanceSpace[prepare.Replica][prepare.Instance] = &Instance{ nil, prepare.Ballot, epaxosproto.NONE, 0, nildeps, nil, 0, 0, nil} preply = &epaxosproto.PrepareReply{ r.Id, prepare.Replica, prepare.Instance, TRUE, -1, epaxosproto.NONE, nil, -1, nildeps} } else { ok := TRUE if prepare.Ballot < inst.ballot { ok = FALSE } else { inst.ballot = prepare.Ballot } preply = &epaxosproto.PrepareReply{ r.Id, prepare.Replica, prepare.Instance, ok, inst.ballot, inst.Status, inst.Cmds, inst.Seq, inst.Deps} } r.replyPrepare(prepare.LeaderId, preply) dlog.Printf("Handled Prepare\n") } func (r *Replica) handlePrepareReply(preply *epaxosproto.PrepareReply) { inst := r.InstanceSpace[preply.Replica][preply.Instance] if inst.lb == nil || !inst.lb.preparing { // we've moved on -- these are delayed replies, so just ignore // TODO: should replies for non-current ballots be ignored? return } if preply.OK == FALSE { // TODO: there is probably another active leader, back off and retry later inst.lb.nacks++ return } //Got an ACK (preply.OK == TRUE) inst.lb.prepareOKs++ if preply.Status == epaxosproto.COMMITTED || preply.Status == epaxosproto.EXECUTED { r.InstanceSpace[preply.Replica][preply.Instance] = &Instance{ preply.Command, inst.ballot, epaxosproto.COMMITTED, preply.Seq, preply.Deps, nil, 0, 0, nil} r.bcastCommit(preply.Replica, preply.Instance, inst.Cmds, preply.Seq, preply.Deps) //TODO: check if we should send notifications to clients return } if preply.Status == epaxosproto.ACCEPTED { if inst.lb.recoveryInst == nil || inst.lb.maxRecvBallot < preply.Ballot { inst.lb.recoveryInst = &RecoveryInstance{preply.Command, preply.Status, preply.Seq, preply.Deps, 0, false} inst.lb.maxRecvBallot = preply.Ballot } } if (preply.Status == epaxosproto.PREACCEPTED || preply.Status == epaxosproto.PREACCEPTED_EQ) && (inst.lb.recoveryInst == nil || inst.lb.recoveryInst.status < epaxosproto.ACCEPTED) { if inst.lb.recoveryInst == nil { inst.lb.recoveryInst = &RecoveryInstance{preply.Command, preply.Status, preply.Seq, preply.Deps, 1, false} } else if preply.Seq == inst.Seq && equal(&preply.Deps, &inst.Deps) { inst.lb.recoveryInst.preAcceptCount++ } else if preply.Status == epaxosproto.PREACCEPTED_EQ { // If we get different ordering attributes from pre-acceptors, we must go with the ones // that agreed with the initial command leader (in case we do not use Thrifty). // This is safe if we use thrifty, although we can also safely start phase 1 in that case. inst.lb.recoveryInst = &RecoveryInstance{preply.Command, preply.Status, preply.Seq, preply.Deps, 1, false} } if preply.AcceptorId == preply.Replica { //if the reply is from the initial command leader, then it's safe to restart phase 1 inst.lb.recoveryInst.leaderResponded = true return } } if inst.lb.prepareOKs < r.N/2 { return } //Received Prepare replies from a majority ir := inst.lb.recoveryInst if ir != nil { //at least one replica has (pre-)accepted this instance if ir.status == epaxosproto.ACCEPTED || (!ir.leaderResponded && ir.preAcceptCount >= r.N/2 && (r.Thrifty || ir.status == epaxosproto.PREACCEPTED_EQ)) { //safe to go to Accept phase inst.Cmds = ir.cmds inst.Seq = ir.seq inst.Deps = ir.deps inst.Status = epaxosproto.ACCEPTED inst.lb.preparing = false r.bcastAccept(preply.Replica, preply.Instance, inst.ballot, int32(len(inst.Cmds)), inst.Seq, inst.Deps) } else if !ir.leaderResponded && ir.preAcceptCount >= (r.N/2+1)/2 { //send TryPreAccepts //but first try to pre-accept on the local replica inst.lb.preAcceptOKs = 0 inst.lb.nacks = 0 inst.lb.possibleQuorum = make([]bool, r.N) for q := 0; q < r.N; q++ { inst.lb.possibleQuorum[q] = true } if conf, q, i := r.findPreAcceptConflicts(ir.cmds, preply.Replica, preply.Instance, ir.seq, ir.deps); conf { if r.InstanceSpace[q][i].Status >= epaxosproto.COMMITTED { //start Phase1 in the initial leader's instance r.startPhase1(preply.Replica, preply.Instance, inst.ballot, inst.lb.clientProposals, ir.cmds, len(ir.cmds)) return } else { inst.lb.nacks = 1 inst.lb.possibleQuorum[r.Id] = false } } else { inst.Cmds = ir.cmds inst.Seq = ir.seq inst.Deps = ir.deps inst.Status = epaxosproto.PREACCEPTED inst.lb.preAcceptOKs = 1 } inst.lb.preparing = false inst.lb.tryingToPreAccept = true r.bcastTryPreAccept(preply.Replica, preply.Instance, inst.ballot, inst.Cmds, inst.Seq, inst.Deps) } else { //start Phase1 in the initial leader's instance inst.lb.preparing = false r.startPhase1(preply.Replica, preply.Instance, inst.ballot, inst.lb.clientProposals, ir.cmds, len(ir.cmds)) } } else { //try to finalize instance by proposing NO-OP var noop_deps [DS]int32 // commands that depended on this instance must look at all previous instances noop_deps[preply.Replica] = preply.Instance - 1 inst.lb.preparing = false r.InstanceSpace[preply.Replica][preply.Instance] = &Instance{ nil, inst.ballot, epaxosproto.ACCEPTED, 0, noop_deps, inst.lb, 0, 0, nil} r.bcastAccept(preply.Replica, preply.Instance, inst.ballot, 0, 0, noop_deps) } dlog.Printf("Handled PrepareReply\n") } func (r *Replica) handleTryPreAccept(tpa *epaxosproto.TryPreAccept) { inst := r.InstanceSpace[tpa.Replica][tpa.Instance] if inst != nil && inst.ballot > tpa.Ballot { // ballot number too small r.replyTryPreAccept(tpa.LeaderId, &epaxosproto.TryPreAcceptReply{ r.Id, tpa.Replica, tpa.Instance, FALSE, inst.ballot, tpa.Replica, tpa.Instance, inst.Status}) } if conflict, confRep, confInst := r.findPreAcceptConflicts(tpa.Command, tpa.Replica, tpa.Instance, tpa.Seq, tpa.Deps); conflict { // there is a conflict, can't pre-accept r.replyTryPreAccept(tpa.LeaderId, &epaxosproto.TryPreAcceptReply{ r.Id, tpa.Replica, tpa.Instance, FALSE, inst.ballot, confRep, confInst, r.InstanceSpace[confRep][confInst].Status}) } else { // can pre-accept if tpa.Instance >= r.crtInstance[tpa.Replica] { r.crtInstance[tpa.Replica] = tpa.Instance + 1 } if inst != nil { inst.Cmds = tpa.Command inst.Deps = tpa.Deps inst.Seq = tpa.Seq inst.Status = epaxosproto.PREACCEPTED inst.ballot = tpa.Ballot } else { r.InstanceSpace[tpa.Replica][tpa.Instance] = &Instance{ tpa.Command, tpa.Ballot, epaxosproto.PREACCEPTED, tpa.Seq, tpa.Deps, nil, 0, 0, nil} } r.replyTryPreAccept(tpa.LeaderId, &epaxosproto.TryPreAcceptReply{r.Id, tpa.Replica, tpa.Instance, TRUE, inst.ballot, 0, 0, 0}) } dlog.Printf("Handled TryPreAccept\n") } func (r *Replica) findPreAcceptConflicts(cmds []state.Command, replica int32, instance int32, seq int32, deps [DS]int32) (bool, int32, int32) { inst := r.InstanceSpace[replica][instance] if inst != nil && len(inst.Cmds) > 0 { if inst.Status >= epaxosproto.ACCEPTED { // already ACCEPTED or COMMITTED // we consider this a conflict because we shouldn't regress to PRE-ACCEPTED return true, replica, instance } if inst.Seq == tpa.Seq && equal(&inst.Deps, &tpa.Deps) { // already PRE-ACCEPTED, no point looking for conflicts again return false, replica, instance } } for q := int32(0); q < int32(r.N); q++ { for i := r.ExecedUpTo[q]; i < r.crtInstance[q]; i++ { if replica == q && instance == i { // no point checking past instance in replica's row, since replica would have // set the dependencies correctly for anything started after instance break } if i == deps[q] { //the instance cannot be a dependency for itself continue } inst := r.InstanceSpace[q][i] if inst == nil || inst.Cmds == nil || len(inst.Cmds) == 0 { continue } if inst.Deps[replica] >= instance { // instance q.i depends on instance replica.instance, it is not a conflict continue } if state.ConflictBatch(inst.Cmds, cmds) { if i > deps[q] || (i < deps[q] && inst.Seq >= seq && (q != replica || inst.Status > epaxosproto.PREACCEPTED_EQ)) { // this is a conflict return true, q, i } } } } return false, -1, -1 } func (r *Replica) handleTryPreAcceptReply(tpar *epaxosproto.TryPreAcceptReply) { inst := r.InstanceSpace[tpar.Replica][tpar.Instance] if inst == nil || inst.lb == nil || !inst.lb.tryingToPreAccept || inst.lb.recoveryInst == nil { return } ir := inst.lb.recoveryInst if tpar.OK == TRUE { inst.lb.preAcceptOKs++ inst.lb.tpaOKs++ if inst.lb.preAcceptOKs >= r.N/3 { //it's safe to start Accept phase inst.Cmds = ir.cmds inst.Seq = ir.seq inst.Deps = ir.deps inst.Status = epaxosproto.ACCEPTED inst.lb.tryingToPreAccept = false inst.lb.acceptOKs = 0 r.bcastAccept(tpar.Replica, tpar.Instance, inst.ballot, int32(len(inst.Cmds)), inst.Seq, inst.Deps) return } } else { inst.lb.nacks++ if tpar.Ballot > inst.ballot { //TODO: retry with higher ballot return } inst.lb.tpaOKs++ if tpar.ConflictReplica == tpar.Replica && tpar.ConflictInstance == tpar.Instance { //TODO: re-run prepare inst.lb.tryingToPreAccept = false return } inst.lb.possibleQuorum[tpar.AcceptorId] = false inst.lb.possibleQuorum[tpar.ConflictReplica] = false notInQuorum := 0 for q := 0; q < r.N; q++ { if !inst.lb.possibleQuorum[tpar.AcceptorId] { notInQuorum++ } } if tpar.ConflictStatus >= epaxosproto.COMMITTED || notInQuorum > r.N/2 { //abandon recovery, restart from phase 1 inst.lb.tryingToPreAccept = false r.startPhase1(tpar.Replica, tpar.Instance, inst.ballot, inst.lb.clientProposals, ir.cmds, len(ir.cmds)) } if notInQuorum == r.N/3 { //this is to prevent defer cycles if present, dq, _ := deferredByInstance(tpar.Replica, tpar.Instance); present { if inst.lb.possibleQuorum[dq] { //an instance whose leader must have been in this instance's quorum has been deferred for this instance => contradiction //abandon recovery, restart from phase 1 inst.lb.tryingToPreAccept = false r.startPhase1(tpar.Replica, tpar.Instance, inst.ballot, inst.lb.clientProposals, ir.cmds, len(ir.cmds)) } } } if inst.lb.tpaOKs >= r.N/3 { //defer recovery and update deferred information updateDeferred(tpar.Replica, tpar.Instance, tpar.ConflictReplica, tpar.ConflictInstance) inst.lb.tryingToPreAccept = false } } dlog.Printf("Handled TryPreAcceptReply\n") } //helper functions and structures to prevent defer cycles while recovering var deferMap map[uint64]uint64 = make(map[uint64]uint64) func updateDeferred(dr int32, di int32, r int32, i int32) { daux := (uint64(dr) << 32) | uint64(di) aux := (uint64(r) << 32) | uint64(i) deferMap[aux] = daux } func deferredByInstance(q int32, i int32) (bool, int32, int32) { aux := (uint64(q) << 32) | uint64(i) daux, present := deferMap[aux] if !present { return false, 0, 0 } dq := int32(daux >> 32) di := int32(daux) return true, dq, di }
{ continue }
lsp_nova_conversions.ts
import { lsp } from "../deps.ts"; // this could really use some tests export function rangeToLspRange( document: TextDocument, range: Range, ): lsp.Range | null { const fullContents = document.getTextInRange(new Range(0, document.length)); let chars = 0; let startLspRange: lsp.Position | undefined; const lines = fullContents.split(document.eol); for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { const lineLength = lines[lineIndex].length + document.eol.length; if (!startLspRange && chars + lineLength >= range.start) { const character = range.start - chars; startLspRange = { line: lineIndex, character }; } if (startLspRange && chars + lineLength >= range.end) { const character = range.end - chars; return { start: startLspRange, end: { line: lineIndex, character } }; } chars += lineLength; } return null; } // this could really use some tests export function
( document: TextDocument, range: lsp.Range, ): Range { const fullContents = document.getTextInRange(new Range(0, document.length)); let rangeStart = 0; let rangeEnd = 0; let chars = 0; const lines = fullContents.split(document.eol); for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { const lineLength = lines[lineIndex].length + document.eol.length; if (range.start.line === lineIndex) { rangeStart = chars + range.start.character; } if (range.end.line === lineIndex) { rangeEnd = chars + range.end.character; break; } chars += lineLength; } return new Range(rangeStart, rangeEnd); }
lspRangeToRange
endpoints.go
// Code generated by smithy-go-codegen DO NOT EDIT. package endpoints import ( "github.com/aws/aws-sdk-go-v2/aws" endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" "github.com/aws/smithy-go/logging" "regexp" ) // Options is the endpoint resolver configuration options type Options struct { // Logger is a logging implementation that log events should be sent to. Logger logging.Logger // LogDeprecated indicates that deprecated endpoints should be logged to the // provided logger. LogDeprecated bool // ResolvedRegion is used to override the region to be resolved, rather then the // using the value passed to the ResolveEndpoint method. This value is used by the // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative // name. You must not set this value directly in your application. ResolvedRegion string // DisableHTTPS informs the resolver to return an endpoint that does not use the // HTTPS scheme. DisableHTTPS bool // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. UseDualStackEndpoint aws.DualStackEndpointState // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. UseFIPSEndpoint aws.FIPSEndpointState } func (o Options) GetResolvedRegion() string { return o.ResolvedRegion } func (o Options) GetDisableHTTPS() bool { return o.DisableHTTPS } func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { return o.UseDualStackEndpoint } func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { return o.UseFIPSEndpoint } func
(options Options) endpoints.Options { return endpoints.Options{ Logger: options.Logger, LogDeprecated: options.LogDeprecated, ResolvedRegion: options.ResolvedRegion, DisableHTTPS: options.DisableHTTPS, UseDualStackEndpoint: options.UseDualStackEndpoint, UseFIPSEndpoint: options.UseFIPSEndpoint, } } // Resolver CodeCommit endpoint resolver type Resolver struct { partitions endpoints.Partitions } // ResolveEndpoint resolves the service endpoint for the given region and options func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { if len(region) == 0 { return endpoint, &aws.MissingRegionError{} } opt := transformToSharedOptions(options) return r.partitions.ResolveEndpoint(region, opt) } // New returns a new Resolver func New() *Resolver { return &Resolver{ partitions: defaultPartitions, } } var partitionRegexp = struct { Aws *regexp.Regexp AwsCn *regexp.Regexp AwsIso *regexp.Regexp AwsIsoB *regexp.Regexp AwsUsGov *regexp.Regexp }{ Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$"), AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), } var defaultPartitions = endpoints.Partitions{ { ID: "aws", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ { Variant: endpoints.DualStackVariant, }: { Hostname: "codecommit.{region}.api.aws", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.{region}.amazonaws.com", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, }: { Hostname: "codecommit-fips.{region}.api.aws", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: 0, }: { Hostname: "codecommit.{region}.amazonaws.com", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, }, RegionRegex: partitionRegexp.Aws, IsRegionalized: true, Endpoints: endpoints.Endpoints{ endpoints.EndpointKey{ Region: "af-south-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-east-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-northeast-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-northeast-2", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-northeast-3", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-south-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-southeast-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-southeast-2", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ca-central-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ca-central-1", Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.ca-central-1.amazonaws.com", }, endpoints.EndpointKey{ Region: "ca-central-1-fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.ca-central-1.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "ca-central-1", }, Deprecated: aws.TrueTernary, }, endpoints.EndpointKey{ Region: "eu-central-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "eu-north-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "eu-south-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "eu-west-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "eu-west-2", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "eu-west-3", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.ca-central-1.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "ca-central-1", }, Deprecated: aws.TrueTernary, }, endpoints.EndpointKey{ Region: "me-south-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "sa-east-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "us-east-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "us-east-1", Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.us-east-1.amazonaws.com", }, endpoints.EndpointKey{ Region: "us-east-1-fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.us-east-1.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "us-east-1", }, Deprecated: aws.TrueTernary, }, endpoints.EndpointKey{ Region: "us-east-2", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "us-east-2", Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.us-east-2.amazonaws.com", }, endpoints.EndpointKey{ Region: "us-east-2-fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.us-east-2.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "us-east-2", }, Deprecated: aws.TrueTernary, }, endpoints.EndpointKey{ Region: "us-west-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "us-west-1", Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.us-west-1.amazonaws.com", }, endpoints.EndpointKey{ Region: "us-west-1-fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.us-west-1.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "us-west-1", }, Deprecated: aws.TrueTernary, }, endpoints.EndpointKey{ Region: "us-west-2", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "us-west-2", Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.us-west-2.amazonaws.com", }, endpoints.EndpointKey{ Region: "us-west-2-fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.us-west-2.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "us-west-2", }, Deprecated: aws.TrueTernary, }, }, }, { ID: "aws-cn", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ { Variant: endpoints.DualStackVariant, }: { Hostname: "codecommit.{region}.api.amazonwebservices.com.cn", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.{region}.amazonaws.com.cn", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, }: { Hostname: "codecommit-fips.{region}.api.amazonwebservices.com.cn", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: 0, }: { Hostname: "codecommit.{region}.amazonaws.com.cn", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, }, RegionRegex: partitionRegexp.AwsCn, IsRegionalized: true, Endpoints: endpoints.Endpoints{ endpoints.EndpointKey{ Region: "cn-north-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "cn-northwest-1", }: endpoints.Endpoint{}, }, }, { ID: "aws-iso", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ { Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.{region}.c2s.ic.gov", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: 0, }: { Hostname: "codecommit.{region}.c2s.ic.gov", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, }, RegionRegex: partitionRegexp.AwsIso, IsRegionalized: true, }, { ID: "aws-iso-b", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ { Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.{region}.sc2s.sgov.gov", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: 0, }: { Hostname: "codecommit.{region}.sc2s.sgov.gov", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, }, RegionRegex: partitionRegexp.AwsIsoB, IsRegionalized: true, }, { ID: "aws-us-gov", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ { Variant: endpoints.DualStackVariant, }: { Hostname: "codecommit.{region}.api.aws", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.{region}.amazonaws.com", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, }: { Hostname: "codecommit-fips.{region}.api.aws", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, { Variant: 0, }: { Hostname: "codecommit.{region}.amazonaws.com", Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, }, RegionRegex: partitionRegexp.AwsUsGov, IsRegionalized: true, Endpoints: endpoints.Endpoints{ endpoints.EndpointKey{ Region: "fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.us-gov-west-1.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "us-gov-west-1", }, Deprecated: aws.TrueTernary, }, endpoints.EndpointKey{ Region: "us-gov-east-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "us-gov-east-1", Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.us-gov-east-1.amazonaws.com", }, endpoints.EndpointKey{ Region: "us-gov-east-1-fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.us-gov-east-1.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "us-gov-east-1", }, Deprecated: aws.TrueTernary, }, endpoints.EndpointKey{ Region: "us-gov-west-1", }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "us-gov-west-1", Variant: endpoints.FIPSVariant, }: { Hostname: "codecommit-fips.us-gov-west-1.amazonaws.com", }, endpoints.EndpointKey{ Region: "us-gov-west-1-fips", }: endpoints.Endpoint{ Hostname: "codecommit-fips.us-gov-west-1.amazonaws.com", CredentialScope: endpoints.CredentialScope{ Region: "us-gov-west-1", }, Deprecated: aws.TrueTernary, }, }, }, }
transformToSharedOptions
main.go
// Code generated by go-swagger; DO NOT EDIT. package main import ( "log" "os" "github.com/go-openapi/loads" flags "github.com/jessevdk/go-flags" "github.com/apiclarity/apiclarity/plugins/api/server/restapi" "github.com/apiclarity/apiclarity/plugins/api/server/restapi/operations" ) // This file was generated by the swagger tool. // Make sure not to overwrite this file after you generated it because all your edits would be lost! func
() { swaggerSpec, err := loads.Embedded(restapi.SwaggerJSON, restapi.FlatSwaggerJSON) if err != nil { log.Fatalln(err) } api := operations.NewAPIClarityPluginsTelemetriesAPIAPI(swaggerSpec) server := restapi.NewServer(api) defer server.Shutdown() parser := flags.NewParser(server, flags.Default) parser.ShortDescription = "APIClarity Plugins telemetries API" parser.LongDescription = swaggerSpec.Spec().Info.Description server.ConfigureFlags() for _, optsGroup := range api.CommandLineOptionsGroups { _, err := parser.AddGroup(optsGroup.ShortDescription, optsGroup.LongDescription, optsGroup.Options) if err != nil { log.Fatalln(err) } } if _, err := parser.Parse(); err != nil { code := 1 if fe, ok := err.(*flags.Error); ok { if fe.Type == flags.ErrHelp { code = 0 } } os.Exit(code) } server.ConfigureAPI() if err := server.Serve(); err != nil { log.Fatalln(err) } }
main
kc87.rs
#![allow(unused)] extern crate rz80; extern crate time; extern crate minifb; extern crate rand; use rz80::{CPU,PIO,CTC,Daisychain,Bus,RegT,PIO_A,PIO_B,CTC_0,CTC_1,CTC_2,CTC_3}; use minifb::{Key, Window, Scale, WindowOptions}; use time::PreciseTime; use std::cell::RefCell; // binary dumps for OS, font and BASIC interpreter static OS: &'static [u8] = include_bytes!("dumps/kc87_os_2.bin"); static FONT: &'static [u8] = include_bytes!("dumps/kc87_font_2.bin"); static BASIC: &'static [u8] = include_bytes!("dumps/z9001_basic.bin"); // framebuffer dimensions (40x24 characters at 8x8 pixels) const WIDTH: usize = 320; const HEIGHT: usize = 192; // number of keys in key mapping tables const MAX_KEYS: usize = 128; // CPU frequency in kHZ const FREQ_KHZ: i64 = 2458; struct KC87 { key_mask: u64, kbd_column_mask: u8, kbd_line_mask: u8, key_map: [u64; MAX_KEYS], blink_flip_flop: bool, } struct System { pub cpu: RefCell<CPU>, pub pio1: RefCell<PIO>, pub pio2: RefCell<PIO>, pub ctc: RefCell<CTC>, pub daisy: RefCell<Daisychain>, } impl System { pub fn new() -> System { System { cpu: RefCell::new(CPU::new()), pio1: RefCell::new(PIO::new(0)), pio2: RefCell::new(PIO::new(1)), ctc: RefCell::new(CTC::new(0)), daisy: RefCell::new(Daisychain::new(8)) } } pub fn poweron(&mut self) { let mut cpu = self.cpu.borrow_mut(); // map 48 KByte RAM cpu.mem.map(0, 0x00000, 0x0000, true, 0xC000); // 2 KByte video RAM (1 KByte colors, 1 KByte ASCII) cpu.mem.map(0, 0x0E800, 0xE800, true, 0x0800); // BASIC and OS ROMs cpu.mem.map_bytes(1, 0x10000, 0xC000, false, &BASIC); cpu.mem.map_bytes(1, 0x12000, 0xE000, false, &OS); // fill video and color RAM with randomness for b in &mut cpu.mem.heap[0x0E800..0xF000] { *b = rand::random(); } // set PC to ROM start cpu.reg.set_pc(0xF000); } // run the emulator for one frame pub fn step_frame(&self, micro_seconds: i64) { let num_cycles = (FREQ_KHZ * micro_seconds) / 1000; let mut cur_cycles = 0; while cur_cycles < num_cycles { let op_cycles = self.cpu.borrow_mut().step(self); self.ctc.borrow_mut().update_timers(self, op_cycles); cur_cycles += op_cycles; } } #[inline(always)] fn rgba8(color: u8) -> u32 { match color { 0 => 0xFF000000, // black 1 => 0xFFFF0000, // red 2 => 0xFF00FF00, // green 3 => 0xFFFFFF00, // yellow 4 => 0xFF0000FF, // blue 5 => 0xFFFF00FF, // purple 6 => 0xFF00FFFF, // cyan _ => 0xFFFFFFFF, // white } } pub fn decode_framebuffer(&self, fb: &mut [u32]) { let mut fb_iter = fb.iter_mut(); let cpu = self.cpu.borrow(); let blinking = true; // FIXME let video_mem = &cpu.mem.heap[0xEC00..0xF000]; let color_mem = &cpu.mem.heap[0xE800..0xEC00]; let mut off = 0; for y in 0..24 { for py in 0..8 { for x in 0..40 { let chr = video_mem[off+x] as usize; let bits = FONT[(chr<<3)|py]; let color = color_mem[off+x]; let b = (color & 0x80) != 0 && blinking; let fg_bits = if b {color & 7} else {(color>>4) & 7}; let bg_bits = if b {(color>>4) & 7} else {color & 7}; let fg = System::rgba8(fg_bits); let bg = System::rgba8(bg_bits); for px in 0..8 { let pixel = if (bits & (0x80>>px)) != 0 {fg} else {bg}; *fb_iter.next().unwrap() = pixel; } } } off += 40; } } } impl Bus for System { fn cpu_outp(&self, port: RegT, val: RegT) { println!("cpu_outp: port={:x} val={:x}", port & 0xFF, val); match port & 0xFF { 0x80|0x84 => self.ctc.borrow_mut().write(self, CTC_0, val), 0x81|0x85 => self.ctc.borrow_mut().write(self, CTC_1, val), 0x82|0x86 => self.ctc.borrow_mut().write(self, CTC_2, val), 0x83|0x87 => self.ctc.borrow_mut().write(self, CTC_3, val), 0x88|0x8C => self.pio1.borrow_mut().write_data(self, PIO_A, val), 0x89|0x8D => self.pio1.borrow_mut().write_data(self, PIO_B, val), 0x8A|0x8E => self.pio1.borrow_mut().write_control(PIO_A, val), 0x8B|0x8F => self.pio1.borrow_mut().write_control(PIO_B, val), 0x90|0x94 => self.pio2.borrow_mut().write_data(self, PIO_A, val), 0x91|0x95 => self.pio2.borrow_mut().write_data(self, PIO_B, val), 0x92|0x96 => self.pio2.borrow_mut().write_control(PIO_A, val), 0x93|0x97 => self.pio2.borrow_mut().write_control(PIO_B, val), _ => (), } } fn cpu_inp(&self, port: RegT) -> RegT { println!("cpu_inp: port={:x}", port & 0xFF); match port & 0xFF { 0x80|0x84 => self.ctc.borrow().read(CTC_0), 0x81|0x85 => self.ctc.borrow().read(CTC_1), 0x82|0x86 => self.ctc.borrow().read(CTC_2), 0x83|0x87 => self.ctc.borrow().read(CTC_3), 0x88|0x8C => self.pio1.borrow_mut().read_data(self, PIO_A), 0x89|0x8D => self.pio1.borrow_mut().read_data(self, PIO_B), 0x8A|0x8E|0x8B|0x8F => self.pio1.borrow().read_control(), 0x90|0x94 => self.pio2.borrow_mut().read_data(self, PIO_A), 0x91|0x95 => self.pio2.borrow_mut().read_data(self, PIO_B), 0x92|0x96|0x93|0x97 => self.pio2.borrow().read_control(), _ => 0xFF, } } fn
(&self, ctrl_id: usize, vec: u8) { println!("irq: ctrl_id={:x} vec={:x}", ctrl_id, vec); } fn irq_cpu(&self) { println!("irq_cpu") } fn irq_ack(&self) -> RegT { println!("irq_ack"); 0 } fn irq_reti(&self) { println!("irq_reti"); } fn pio_outp(&self, pio: usize, chn: usize, data: RegT) { println!("pio_outp: pio={:x} chn={:x} data={:x}", pio, chn, data); } fn pio_inp(&self, pio: usize, chn: usize) -> RegT { println!("pio_in: pio={:x} chn={:x}", pio, chn); 0 } fn pio_rdy(&self, pio: usize, chn: usize, rdy: bool) { println!("pio_rdy: pio={:x} chn={:x} rdy={:}", pio, chn, rdy); } fn pio_irq(&self, pio: usize, chn: usize, int_vector: RegT) { println!("pio_irq: pio={:x} chn={:x} int_vector{:x}", pio, chn, int_vector); } fn ctc_write(&self, chn: usize, ctc: &CTC) { println!("ctc_write: chn={:x}", chn); } fn ctc_zero(&self, chn: usize, ctc: &CTC) { // blargh, and here we are stuck... CTC2 output trigger is connected // CTC3 input trigger, and here the snake baits its tail... // ...back to the drawing board... println!("ctc_zero: chn={:x}", chn); } fn ctc_irq(&self, ctc: usize, chn: usize, int_vector: RegT) { println!("ctc_irq: ctc={:x}, chn={:x}, int_vector={:x}", ctc, chn, int_vector); } } fn main() { // create a window via minifb let mut window = match Window::new("rz80 KC87 example (WIP)", WIDTH, HEIGHT, WindowOptions { resize: false, scale: Scale::X2, ..WindowOptions::default() }) { Ok(win) => win, Err(err) => panic!("Unable to create minifb window: {}", err) }; // the pixel frame buffer, written by System::decode_framebuffer() // and transfered to the minifb window let mut frame_buffer = vec![0u32; WIDTH*HEIGHT]; let mut system = System::new(); system.poweron(); let mut micro_seconds_per_frame: i64 = 0; while window.is_open() { let start = PreciseTime::now(); // run the emulator for the current frame system.step_frame(micro_seconds_per_frame); // update the window content system.decode_framebuffer(&mut frame_buffer); window.update_with_buffer(&frame_buffer); // measure the elapsed time to run emulator at the correct speed let frame_time = start.to(PreciseTime::now()); micro_seconds_per_frame = frame_time.num_microseconds().unwrap(); } }
irq
15.5.4.9-1.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** File Name: 15.5.4.9-1.js ECMA Section: 15.5.4.9 String.prototype.substring( start ) Description: 15.5.4.9 String.prototype.substring(start) Returns a substring of the result of converting this object to a string, starting from character position start and running to the end of the string. The result is a string value, not a String object. If the argument is NaN or negative, it is replaced with zero; if the argument is larger than the length of the string, it is replaced with the length of the string. When the substring method is called with one argument start, the following steps are taken: 1.Call ToString, giving it the this value as its argument. 2.Call ToInteger(start). 3.Compute the number of characters in Result(1). 4.Compute min(max(Result(2), 0), Result(3)). 5.Return a string whose length is the difference between Result(3) and Result(4), containing characters from Result(1), namely the characters with indices Result(4) through Result(3)1, in ascending order. Author: [email protected] Date: 12 november 1997 */ var SECTION = "15.5.4.9-1"; var VERSION = "ECMA_1"; startTest(); var TITLE = "String.prototype.substring( start )"; writeHeaderToLog( SECTION + " "+ TITLE); new TestCase( SECTION, "String.prototype.substring.length", 2, String.prototype.substring.length ); new TestCase( SECTION, "delete String.prototype.substring.length", false, delete String.prototype.substring.length ); new TestCase( SECTION, "delete String.prototype.substring.length; String.prototype.substring.length", 2, eval("delete String.prototype.substring.length; String.prototype.substring.length") ); // test cases for when substring is called with no arguments. // this is a string object new TestCase( SECTION, "var s = new String('this is a string object'); typeof s.substring()", "string", eval("var s = new String('this is a string object'); typeof s.substring()") ); new TestCase( SECTION, "var s = new String(''); s.substring()", "", eval("var s = new String(''); s.substring()") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.substring()", "this is a string object", eval("var s = new String('this is a string object'); s.substring()") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(NaN)", "this is a string object", eval("var s = new String('this is a string object'); s.substring(NaN)") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(-0.01)", "this is a string object", eval("var s = new String('this is a string object'); s.substring(-0.01)") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(s.length)", "", eval("var s = new String('this is a string object'); s.substring(s.length)") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(s.length+1)", "", eval("var s = new String('this is a string object'); s.substring(s.length+1)") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(Infinity)", "", eval("var s = new String('this is a string object'); s.substring(Infinity)") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.substring(-Infinity)", "this is a string object", eval("var s = new String('this is a string object'); s.substring(-Infinity)") ); // this is not a String object, start is not an integer new TestCase( SECTION, "var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring()", "1,2,3,4,5", eval("var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring()") ); new TestCase( SECTION, "var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring(true)", ",2,3,4,5", eval("var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring(true)") ); new TestCase( SECTION, "var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring('4')", "3,4,5", eval("var s = new Array(1,2,3,4,5); s.substring = String.prototype.substring; s.substring('4')") ); new TestCase( SECTION, "var s = new Array(); s.substring = String.prototype.substring; s.substring('4')", "", eval("var s = new Array(); s.substring = String.prototype.substring; s.substring('4')") ); // this is an object object new TestCase( SECTION, "var obj = new Object(); obj.substring = String.prototype.substring; obj.substring(8)", "Object]", eval("var obj = new Object(); obj.substring = String.prototype.substring; obj.substring(8)") ); // this is a function object new TestCase( SECTION, "var obj = new Function(); obj.substring = String.prototype.substring; obj.toString = Object.prototype.toString; obj.substring(8)", "Function]", eval("var obj = new Function(); obj.substring = String.prototype.substring; obj.toString = Object.prototype.toString; obj.substring(8)") ); // this is a number object new TestCase( SECTION, "var obj = new Number(NaN); obj.substring = String.prototype.substring; obj.substring(false)", "NaN", eval("var obj = new Number(NaN); obj.substring = String.prototype.substring; obj.substring(false)") ); // this is the Math object new TestCase( SECTION, "var obj = Math; obj.substring = String.prototype.substring; obj.substring(Math.PI)", "ject Math]",
new TestCase( SECTION, "var obj = new Boolean(); obj.substring = String.prototype.substring; obj.substring(new Array())", "false", eval("var obj = new Boolean(); obj.substring = String.prototype.substring; obj.substring(new Array())") ); // this is a user defined object new TestCase( SECTION, "var obj = new MyObject( null ); obj.substring(0)", "null", eval( "var obj = new MyObject( null ); obj.substring(0)") ); test(); function MyObject( value ) { this.value = value; this.substring = String.prototype.substring; this.toString = new Function ( "return this.value+''" ); }
eval("var obj = Math; obj.substring = String.prototype.substring; obj.substring(Math.PI)") ); // this is a Boolean object
bucket.go
/* Copyright (c) 2016 Jason Mansfield 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. */ // bucket captures objects below a certain age, decides which ones should be deleted, and deletes them. package bucket import ( "sort" "time" "github.com/AgentZombie/agerotate" ) // bucket is a container for Object(s) and is intended to hold those objects younger than the Age of the Range but older than younger buckets. type bucket struct { agerotate.Range objects []agerotate.Object } func newBucket(r agerotate.Range) *bucket { return &bucket{ r, []agerotate.Object{}, } } func (b *bucket) Add(o agerotate.Object) { b.objects = append(b.objects, o) } func (b bucket) Age() time.Duration { return b.Range.Age } // Cleanup sorts the objects in the bucket by Age then deletes objects according to the Interval. The first object in the bucket is always retained. For each object thereafter, if the age of the object is less than the age of the last retained object plus Interval, the newer object is deleted. If the next object is older than the age of the last retained object plus Interval, the newer object is retained and processing continues. func (b *bucket) Cleanup() error { if len(b.objects) < 2 { return nil } sort.Sort(agerotate.ObjectsByAge{b.objects}) baseAge := b.objects[0].Age() for _, o := range b.objects[1:] { oAge := o.Age() if oAge-baseAge < b.Range.Interval { err := o.Delete() if err != nil
} else { baseAge = oAge } } return nil }
{ return err }
wazuh.go
/* go client for the wazuh [rest api](https://documentation.wazuh.com/4.0/user-manual/api/reference.html) it is generated from the OpenAPI 3.0 specifications. Thus it is not the most elegant API. Some effort has been put into an more go friendly interface by wrapping non successful results into errors and returning the `Data` objects instead of the raw result. There are a few With... option functions that can be used to customize the API client: - `WithBaseURL` custom base url - `WithLogin` (username, password) - `WithContext` (custom Context) - `WithInsecure` allow insecure certificates - `WithUserAgent` to set custom user agent go-wazuh supports following environment variables for easy construction of a client: - `WAZUH_URL` - `WAZUH_USER` - `WAZUH_PASSWORD` - `WAZUH_INSECURE` Construct a new Wazuh client, then use the various service on the client to access different parts of the wazuh API. For example, to list all agents: c := NewAPIClient("https://localhost:55000", WithLogin("wazuh", "wazuh"), WithInsecure(true)) c.Authenticate() agents := c.AgentsController.GetAgents(&AgentsControllerGetAgentsParams{}) fmt.Printf("Get Agents TotalAffectedItems %d\n", agents.AllItemsResponse.TotalAffectedItems) for i, agent := range agents.AffectedItems { fmt.Printf(" %d: %s on %s\n", i, *agent.Id, *agent.NodeName) } Or use the environment to construct the client to get the server basic information: c, err := NewClientFromEnvironment(WithInsecure(true)) if err != nil { panic(err) } // authenticate err = c.Authenticate() if err != nil { panic(err) } // call the DefaultInfo on the status, err := c.Default.DefaultInfo(&DefaultControllerDefaultInfoParams{}) if err != nil { panic(err) } fmt.Printf("Connected to %s on %s\n", *status.Title, *status.Hostname) */ package rest import ( "context" "crypto/tls" "encoding/base64" "errors" "fmt" "log" "net/http" "net/http/httputil" "net/url" "os" "reflect" "strings" ) // The Client for the wazuh REST API type Client struct { // The endpoint of the server conforming to this interface, with scheme, // https://api.deepmap.com for example. This can contain a path relative // to the server, such as https://api.deepmap.com/dev-test, and all the // paths in the swagger spec will be appended to the server. Server string // Doer for performing requests, typically a *http.Client with any // customized settings, such as certificate chains. Client HTTPRequestDoer innerClient HTTPRequestDoer // A callback for modifying requests which are generated before sending over // the network. RequestEditor RequestEditorFn ctx context.Context userAgent string token string user string password string insecure bool trace bool } // HTTPRequestDoer performs HTTP requests. // // The standard http.Client implements this interface. type HTTPRequestDoer interface { Do(req *http.Request) (*http.Response, error) } // WithLogin specifies the credentials for func WithLogin(user string, password string) ClientOption { return func(c *Client) error { c.user = user c.password = password return nil } } // WithContext specifies the credentials for func WithContext(ctx context.Context) ClientOption { return func(c *Client) error { c.ctx = ctx return nil } } // WithInsecure accept all certificates func WithInsecure(insecure bool) ClientOption { return func(c *Client) error { c.insecure = insecure return nil } } // WithTrace write all requests to the log func WithTrace(trace bool) ClientOption { return func(c *Client) error { c.trace = trace return nil } } // WithUserAgent specify a user agent string to identify the client func WithUserAgent(userAgent string) ClientOption { return func(c *Client) error { c.userAgent = userAgent return nil } } // do execute and evaluate the request func (c *Client) do(ctx context.Context, req *http.Request) error { // Headers for all request req.Header.Set("User-Agent", c.userAgent) if c.token == "" { encoded := base64.StdEncoding.EncodeToString([]byte(c.user + ":" + c.password)) req.Header.Set("Authorization", "Basic "+encoded) } else { req.Header.Set("Authorization", "Bearer "+c.token) } return nil } // APIClient extended client with less abstract api access type APIClient struct { *ClientWithResponses ExperimentalController ExperimentalControllerInterface SyscheckController SyscheckControllerInterface AgentsController AgentsControllerInterface CiscatController CiscatControllerInterface ListsController ListsControllerInterface ManagerController ManagerControllerInterface MitreController MitreControllerInterface ScaController ScaControllerInterface DefaultController DefaultControllerInterface OverviewController OverviewControllerInterface RulesController RulesControllerInterface SecurityController SecurityControllerInterface SyscollectorController SyscollectorControllerInterface ActiveResponseController ActiveResponseControllerInterface ClusterController ClusterControllerInterface DecodersController DecodersControllerInterface } // NewClientFromEnvironment creates a new client from default environment variables func NewClientFromEnvironment(opts ...ClientOption) (*APIClient, error) { baseURL := os.Getenv("WAZUH_URL") user := os.Getenv("WAZUH_USER") password := os.Getenv("WAZUH_PASSWORD") opts = append(opts, WithLogin(user, password)) if os.Getenv("WAZUH_INSECURE") == "true" { opts = append(opts, WithInsecure(true)) } c, err := NewAPIClient(baseURL, opts...) if err != nil { return nil, err } return c, nil } // NewAPIClient Create a new API (yes, naming is awkward) func NewAPIClient(baseURL string, opts ...ClientOption) (*APIClient, error) { cl, err := NewClient(baseURL, opts...) cl.RequestEditor = cl.do if err != nil { return nil, err } clientWithResponses := &ClientWithResponses{cl, false} return &APIClient{ ClientWithResponses: clientWithResponses, ExperimentalController: &ExperimentalController{clientWithResponses}, SyscheckController: &SyscheckController{clientWithResponses}, ListsController: &ListsController{clientWithResponses}, ManagerController: &ManagerController{clientWithResponses}, MitreController: &MitreController{clientWithResponses}, ScaController: &ScaController{clientWithResponses}, AgentsController: &AgentsController{clientWithResponses}, CiscatController: &CiscatController{clientWithResponses}, RulesController: &RulesController{clientWithResponses}, SecurityController: &SecurityController{clientWithResponses}, SyscollectorController: &SyscollectorController{clientWithResponses}, DefaultController: &DefaultController{clientWithResponses}, OverviewController: &OverviewController{clientWithResponses}, DecodersController: &DecodersController{clientWithResponses}, ActiveResponseController: &ActiveResponseController{clientWithResponses}, ClusterController: &ClusterController{clientWithResponses}, }, nil } // ServerAddress return the Wazuh server address func (c *APIClient) ServerAddress() string { u, err := url.Parse(c.ClientInterface.(*Client).Server) if err != nil { return "127.0.0.1" } lastSep := strings.LastIndex(u.Host, ":") if lastSep > 0 { return u.Host[:lastSep] } return u.Host } // NewClient returns a new wazuh API client func NewClient(baseURL string, opts ...ClientOption) (*Client, error) { // remove trailing slash (if any) from base URL baseURL = strings.TrimRight(baseURL, "/") c := &Client{ Server: baseURL, userAgent: "go-wazuh", } // mutate client and add all optional params for _, o := range opts { if err := o(c); err != nil { return nil, err } } if c.ctx == nil { c.ctx = context.Background() } // ensure the server URL always has a trailing slash if !strings.HasSuffix(c.Server, "/") { c.Server += "/" } // create httpClient, if not already present c.Client = c c.innerClient = &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: c.insecure, // test server certificate is not trusted. }, }, } return c, nil } // Do wrap the doer for tracing func (c *Client) Do(req *http.Request) (*http.Response, error) { r, e := c.innerClient.Do(req) if c.trace { var reqStr = "" dump, err := httputil.DumpRequestOut(req, true) if err == nil { reqStr = strings.ReplaceAll(strings.TrimRight(string(dump), "\r\n"), "\n", "\n ") } if r == nil { dump = nil err = nil } else { dump, err = httputil.DumpResponse(r, true) } if err == nil { c.Tracef("%s\n\n %s\n", reqStr, strings.ReplaceAll(strings.TrimRight(string(dump), "\r\n"), "\n", "\n ")) } } return r, e } // Errorf logs errors func (c *Client) Errorf(format string, v ...interface{}) { log.Printf("[ERROR] %s", fmt.Sprintf(format, v...)) } // Warnf logs warings func (c *Client) Warnf(format string, v ...interface{}) { log.Printf("[WARN] %s", fmt.Sprintf(format, v...)) } // Debugf logs debug info func (c *Client) Debugf(format string, v ...interface{}) { log.Printf("[DEBUG] %s", fmt.Sprintf(format, v...)) } // Tracef logs trace info func (c *Client) Tracef(format string, v ...interface{}) { log.Printf("[TRACE] %s", fmt.Sprintf(format, v...)) } // RawAPIResponse generic response wrapper type RawAPIResponse interface { Status() string StatusCode() int } func getResponseObject(sr RawAPIResponse) (interface{}, error)
func (c *ClientWithResponses) Authenticated() bool { return c.ClientInterface.(*Client).token != "" } //Authenticate login using basic auth to optain a token func (c *ClientWithResponses) Authenticate() error { // Authenticate c.ClientInterface.(*Client).token = "" var raw Raw = false params := &SecurityControllerLoginUserParams{Raw: &raw} sr, err := c.SecurityControllerLoginUserWithResponse(c.ClientInterface.(*Client).ctx, params) if err != nil { return err } if sr == nil { return fmt.Errorf("Authentication failed") } if sr.StatusCode() > 399 { if sr != nil { _, err = getResponseObject(sr) } if err != nil { return err } return fmt.Errorf("%s returned %s", c.ClientInterface.(*Client).Server, sr.Status()) } if sr.JSON200.Data.Token == nil { return errors.New("Nil token!?") } c.ClientInterface.(*Client).token = *sr.JSON200.Data.Token return nil } func (c *ClientWithResponses) evaluateResponse(response RawAPIResponse, err error) (interface{}, error) { if err != nil { return nil, err } // log.Printf("[TRACE] %s %v", response.Request.URL, reflect.ValueOf(response.Request.Result).Elem().FieldByName("Data").Interface()) return getResponseObject(response) }
{ fldForCode := fmt.Sprintf("JSON%d", sr.StatusCode()) v := reflect.ValueOf(sr).Elem() if _, ok := v.Type().FieldByName(fldForCode); ok { s := v.FieldByName(fldForCode).Interface() if apiError, ok := s.(*ApiError); ok && (apiError.ApiCode != nil && *apiError.ApiCode != 0) { return nil, apiError } else if requestError, ok := s.(*RequestError); ok && (requestError.RequestError != nil && *requestError.RequestError != 0) { return nil, requestError } else if apiResponse, ok := s.(*ApiResponse); ok && (apiResponse.Code() > 0) { return nil, apiResponse } else { v := reflect.ValueOf(s).Elem() if _, ok := v.Type().FieldByName("Data"); ok { d := v.FieldByName("Data").Interface() return d, nil } if _, ok := s.(ApiResponse); ok { fmt.Println("do") } if sr.StatusCode() > 399 { return s, errors.New(sr.Status()) } return s, nil } } if sr.StatusCode() > 399 { return sr, errors.New(sr.Status()) } return sr, nil }
server.go
import ( "net/http" "github.com/maxmoehl/tt" ) var StatusCodeMapping = map[tt.Error]int{ tt.ErrInvalidData: http.StatusBadRequest, tt.ErrInternalError: http.StatusInternalServerError, tt.ErrNotFound: http.StatusNotFound, }
package server
test_convert_pandas.py
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless 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. import decimal import json from collections import OrderedDict from datetime import date, datetime, time, timedelta import numpy as np import numpy.testing as npt import pandas as pd import pandas.util.testing as tm import pytest import pyarrow as pa import pyarrow.types as patypes from pyarrow.compat import PY2 from .pandas_examples import dataframe_with_arrays, dataframe_with_lists def _alltypes_example(size=100): return pd.DataFrame({ 'uint8': np.arange(size, dtype=np.uint8), 'uint16': np.arange(size, dtype=np.uint16), 'uint32': np.arange(size, dtype=np.uint32), 'uint64': np.arange(size, dtype=np.uint64), 'int8': np.arange(size, dtype=np.int16), 'int16': np.arange(size, dtype=np.int16), 'int32': np.arange(size, dtype=np.int32), 'int64': np.arange(size, dtype=np.int64), 'float32': np.arange(size, dtype=np.float32), 'float64': np.arange(size, dtype=np.float64), 'bool': np.random.randn(size) > 0, # TODO(wesm): Pandas only support ns resolution, Arrow supports s, ms, # us, ns 'datetime': np.arange("2016-01-01T00:00:00.001", size, dtype='datetime64[ms]'), 'str': [str(x) for x in range(size)], 'str_with_nulls': [None] + [str(x) for x in range(size - 2)] + [None], 'empty_str': [''] * size }) def _check_pandas_roundtrip(df, expected=None, use_threads=False, expected_schema=None, check_dtype=True, schema=None, preserve_index=False, as_batch=False): klass = pa.RecordBatch if as_batch else pa.Table table = klass.from_pandas(df, schema=schema, preserve_index=preserve_index, nthreads=2 if use_threads else 1) result = table.to_pandas(use_threads=use_threads) if expected_schema: # all occurences of _check_pandas_roundtrip passes expected_schema # without the pandas generated key-value metadata, so we need to # add it before checking schema equality expected_schema = expected_schema.add_metadata(table.schema.metadata) assert table.schema.equals(expected_schema) if expected is None: expected = df tm.assert_frame_equal(result, expected, check_dtype=check_dtype, check_index_type=('equiv' if preserve_index else False)) def _check_series_roundtrip(s, type_=None, expected_pa_type=None): arr = pa.array(s, from_pandas=True, type=type_) if type_ is not None and expected_pa_type is None: expected_pa_type = type_ if expected_pa_type is not None: assert arr.type == expected_pa_type result = pd.Series(arr.to_pandas(), name=s.name) if patypes.is_timestamp(arr.type) and arr.type.tz is not None: result = (result.dt.tz_localize('utc') .dt.tz_convert(arr.type.tz)) tm.assert_series_equal(s, result) def _check_array_roundtrip(values, expected=None, mask=None, type=None): arr = pa.array(values, from_pandas=True, mask=mask, type=type) result = arr.to_pandas() values_nulls = pd.isnull(values) if mask is None: assert arr.null_count == values_nulls.sum() else: assert arr.null_count == (mask | values_nulls).sum() if mask is None: tm.assert_series_equal(pd.Series(result), pd.Series(values), check_names=False) else: expected = pd.Series(np.ma.masked_array(values, mask=mask)) tm.assert_series_equal(pd.Series(result), expected, check_names=False) def _check_array_from_pandas_roundtrip(np_array): arr = pa.array(np_array, from_pandas=True) result = arr.to_pandas() npt.assert_array_equal(result, np_array) class TestConvertMetadata(object): """ Conversion tests for Pandas metadata & indices. """ def test_non_string_columns(self): df = pd.DataFrame({0: [1, 2, 3]}) table = pa.Table.from_pandas(df) assert table.column(0).name == '0' def test_from_pandas_with_columns(self): df = pd.DataFrame({0: [1, 2, 3], 1: [1, 3, 3], 2: [2, 4, 5]}) table = pa.Table.from_pandas(df, columns=[0, 1]) expected = pa.Table.from_pandas(df[[0, 1]]) assert expected.equals(table) record_batch_table = pa.RecordBatch.from_pandas(df, columns=[0, 1]) record_batch_expected = pa.RecordBatch.from_pandas(df[[0, 1]]) assert record_batch_expected.equals(record_batch_table) def test_column_index_names_are_preserved(self): df = pd.DataFrame({'data': [1, 2, 3]}) df.columns.names = ['a'] _check_pandas_roundtrip(df, preserve_index=True) def test_multiindex_columns(self): columns = pd.MultiIndex.from_arrays([ ['one', 'two'], ['X', 'Y'] ]) df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns) _check_pandas_roundtrip(df, preserve_index=True) def test_multiindex_columns_with_dtypes(self): columns = pd.MultiIndex.from_arrays( [ ['one', 'two'], pd.DatetimeIndex(['2017-08-01', '2017-08-02']), ], names=['level_1', 'level_2'], ) df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns) _check_pandas_roundtrip(df, preserve_index=True) def test_multiindex_columns_unicode(self): columns = pd.MultiIndex.from_arrays([[u'あ', u'い'], ['X', 'Y']]) df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns) _check_pandas_roundtrip(df, preserve_index=True) def test_integer_index_column(self): df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')]) _check_pandas_roundtrip(df, preserve_index=True) def test_index_metadata_field_name(self): # test None case, and strangely named non-index columns df = pd.DataFrame( [(1, 'a', 3.1), (2, 'b', 2.2), (3, 'c', 1.3)], index=pd.MultiIndex.from_arrays( [['c', 'b', 'a'], [3, 2, 1]], names=[None, 'foo'] ), columns=['a', None, '__index_level_0__'], ) t = pa.Table.from_pandas(df, preserve_index=True) raw_metadata = t.schema.metadata js = json.loads(raw_metadata[b'pandas'].decode('utf8')) col1, col2, col3, idx0, foo = js['columns'] assert col1['name'] == 'a' assert col1['name'] == col1['field_name'] assert col2['name'] is None assert col2['field_name'] == 'None' assert col3['name'] == '__index_level_0__' assert col3['name'] == col3['field_name'] idx0_name, foo_name = js['index_columns'] assert idx0_name == '__index_level_0__' assert idx0['field_name'] == idx0_name assert idx0['name'] is None assert foo_name == 'foo' assert foo['field_name'] == foo_name assert foo['name'] == foo_name def test_categorical_column_index(self): df = pd.DataFrame( [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)], columns=pd.Index(list('def'), dtype='category') ) t = pa.Table.from_pandas(df, preserve_index=True) raw_metadata = t.schema.metadata js = json.loads(raw_metadata[b'pandas'].decode('utf8')) column_indexes, = js['column_indexes'] assert column_indexes['name'] is None assert column_indexes['pandas_type'] == 'categorical' assert column_indexes['numpy_type'] == 'int8' md = column_indexes['metadata'] assert md['num_categories'] == 3 assert md['ordered'] is False def test_string_column_index(self): df = pd.DataFrame( [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)], columns=pd.Index(list('def'), name='stringz') ) t = pa.Table.from_pandas(df, preserve_index=True) raw_metadata = t.schema.metadata js = json.loads(raw_metadata[b'pandas'].decode('utf8')) column_indexes, = js['column_indexes'] assert column_indexes['name'] == 'stringz' assert column_indexes['name'] == column_indexes['field_name'] assert column_indexes['pandas_type'] == ('bytes' if PY2 else 'unicode') assert column_indexes['numpy_type'] == 'object' md = column_indexes['metadata'] if not PY2: assert len(md) == 1 assert md['encoding'] == 'UTF-8' else: assert md is None or 'encoding' not in md def test_datetimetz_column_index(self): df = pd.DataFrame( [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)], columns=pd.date_range( start='2017-01-01', periods=3, tz='America/New_York' ) ) t = pa.Table.from_pandas(df, preserve_index=True) raw_metadata = t.schema.metadata js = json.loads(raw_metadata[b'pandas'].decode('utf8')) column_indexes, = js['column_indexes'] assert column_indexes['name'] is None assert column_indexes['pandas_type'] == 'datetimetz' assert column_indexes['numpy_type'] == 'datetime64[ns]' md = column_indexes['metadata'] assert md['timezone'] == 'America/New_York' def test_datetimetz_row_index(self): df = pd.DataFrame({ 'a': pd.date_range( start='2017-01-01', periods=3, tz='America/New_York' ) }) df = df.set_index('a') _check_pandas_roundtrip(df, preserve_index=True) def test_categorical_row_index(self): df = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3]}) df['a'] = df.a.astype('category') df = df.set_index('a') _check_pandas_roundtrip(df, preserve_index=True) def test_duplicate_column_names_does_not_crash(self): df = pd.DataFrame([(1, 'a'), (2, 'b')], columns=list('aa')) with pytest.raises(ValueError): pa.Table.from_pandas(df) def test_dictionary_indices_boundscheck(self): # ARROW-1658. No validation of indices leads to segfaults in pandas indices = [[0, 1], [0, -1]] for inds in indices: arr = pa.DictionaryArray.from_arrays(inds, ['a'], safe=False) batch = pa.RecordBatch.from_arrays([arr], ['foo']) table = pa.Table.from_batches([batch, batch, batch]) with pytest.raises(pa.ArrowInvalid): arr.to_pandas() with pytest.raises(pa.ArrowInvalid): table.to_pandas() def test_unicode_with_unicode_column_and_index(self): df = pd.DataFrame({u'あ': [u'い']}, index=[u'う']) _check_pandas_roundtrip(df, preserve_index=True) def test_mixed_unicode_column_names(self): df = pd.Da
inary_column_name(self): column_data = [u'い'] key = u'あ'.encode('utf8') data = {key: column_data} df = pd.DataFrame(data) # we can't use _check_pandas_roundtrip here because our metdata # is always decoded as utf8: even if binary goes in, utf8 comes out t = pa.Table.from_pandas(df, preserve_index=True) df2 = t.to_pandas() assert df.values[0] == df2.values[0] assert df.index.values[0] == df2.index.values[0] assert df.columns[0] == key def test_multiindex_duplicate_values(self): num_rows = 3 numbers = list(range(num_rows)) index = pd.MultiIndex.from_arrays( [['foo', 'foo', 'bar'], numbers], names=['foobar', 'some_numbers'], ) df = pd.DataFrame({'numbers': numbers}, index=index) table = pa.Table.from_pandas(df) result_df = table.to_pandas() tm.assert_frame_equal(result_df, df) def test_metadata_with_mixed_types(self): df = pd.DataFrame({'data': [b'some_bytes', u'some_unicode']}) table = pa.Table.from_pandas(df) metadata = table.schema.metadata assert b'mixed' not in metadata[b'pandas'] js = json.loads(metadata[b'pandas'].decode('utf8')) data_column = js['columns'][0] assert data_column['pandas_type'] == 'bytes' assert data_column['numpy_type'] == 'object' def test_list_metadata(self): df = pd.DataFrame({'data': [[1], [2, 3, 4], [5] * 7]}) schema = pa.schema([pa.field('data', type=pa.list_(pa.int64()))]) table = pa.Table.from_pandas(df, schema=schema) metadata = table.schema.metadata assert b'mixed' not in metadata[b'pandas'] js = json.loads(metadata[b'pandas'].decode('utf8')) data_column = js['columns'][0] assert data_column['pandas_type'] == 'list[int64]' assert data_column['numpy_type'] == 'object' def test_decimal_metadata(self): expected = pd.DataFrame({ 'decimals': [ decimal.Decimal('394092382910493.12341234678'), -decimal.Decimal('314292388910493.12343437128'), ] }) table = pa.Table.from_pandas(expected) metadata = table.schema.metadata assert b'mixed' not in metadata[b'pandas'] js = json.loads(metadata[b'pandas'].decode('utf8')) data_column = js['columns'][0] assert data_column['pandas_type'] == 'decimal' assert data_column['numpy_type'] == 'object' assert data_column['metadata'] == {'precision': 26, 'scale': 11} def test_table_column_subset_metadata(self): # ARROW-1883 df = pd.DataFrame({ 'a': [1, 2, 3], 'b': pd.date_range("2017-01-01", periods=3, tz='Europe/Brussels')}) table = pa.Table.from_pandas(df) table_subset = table.remove_column(1) result = table_subset.to_pandas() tm.assert_frame_equal(result, df[['a']]) table_subset2 = table_subset.remove_column(1) result = table_subset2.to_pandas() tm.assert_frame_equal(result, df[['a']]) # non-default index for index in [ pd.Index(['a', 'b', 'c'], name='index'), pd.date_range("2017-01-01", periods=3, tz='Europe/Brussels')]: df = pd.DataFrame({'a': [1, 2, 3], 'b': [.1, .2, .3]}, index=index) table = pa.Table.from_pandas(df) table_subset = table.remove_column(1) result = table_subset.to_pandas() tm.assert_frame_equal(result, df[['a']]) table_subset2 = table_subset.remove_column(1) result = table_subset2.to_pandas() tm.assert_frame_equal(result, df[['a']].reset_index(drop=True)) def test_empty_list_metadata(self): # Create table with array of empty lists, forced to have type # list(string) in pyarrow c1 = [["test"], ["a", "b"], None] c2 = [[], [], []] arrays = OrderedDict([ ('c1', pa.array(c1, type=pa.list_(pa.string()))), ('c2', pa.array(c2, type=pa.list_(pa.string()))), ]) rb = pa.RecordBatch.from_arrays( list(arrays.values()), list(arrays.keys()) ) tbl = pa.Table.from_batches([rb]) # First roundtrip changes schema, because pandas cannot preserve the # type of empty lists df = tbl.to_pandas() tbl2 = pa.Table.from_pandas(df, preserve_index=True) md2 = json.loads(tbl2.schema.metadata[b'pandas'].decode('utf8')) # Second roundtrip df2 = tbl2.to_pandas() expected = pd.DataFrame(OrderedDict([('c1', c1), ('c2', c2)])) tm.assert_frame_equal(df2, expected) assert md2['columns'] == [ { 'name': 'c1', 'field_name': 'c1', 'metadata': None, 'numpy_type': 'object', 'pandas_type': 'list[unicode]', }, { 'name': 'c2', 'field_name': 'c2', 'metadata': None, 'numpy_type': 'object', 'pandas_type': 'list[empty]', }, { 'name': None, 'field_name': '__index_level_0__', 'metadata': None, 'numpy_type': 'int64', 'pandas_type': 'int64', } ] class TestConvertPrimitiveTypes(object): """ Conversion tests for primitive (e.g. numeric) types. """ def test_float_no_nulls(self): data = {} fields = [] dtypes = [('f2', pa.float16()), ('f4', pa.float32()), ('f8', pa.float64())] num_values = 100 for numpy_dtype, arrow_dtype in dtypes: values = np.random.randn(num_values) data[numpy_dtype] = values.astype(numpy_dtype) fields.append(pa.field(numpy_dtype, arrow_dtype)) df = pd.DataFrame(data) schema = pa.schema(fields) _check_pandas_roundtrip(df, expected_schema=schema) def test_float_nulls(self): num_values = 100 null_mask = np.random.randint(0, 10, size=num_values) < 3 dtypes = [('f2', pa.float16()), ('f4', pa.float32()), ('f8', pa.float64())] names = ['f2', 'f4', 'f8'] expected_cols = [] arrays = [] fields = [] for name, arrow_dtype in dtypes: values = np.random.randn(num_values).astype(name) arr = pa.array(values, from_pandas=True, mask=null_mask) arrays.append(arr) fields.append(pa.field(name, arrow_dtype)) values[null_mask] = np.nan expected_cols.append(values) ex_frame = pd.DataFrame(dict(zip(names, expected_cols)), columns=names) table = pa.Table.from_arrays(arrays, names) assert table.schema.equals(pa.schema(fields)) result = table.to_pandas() tm.assert_frame_equal(result, ex_frame) def test_float_nulls_to_ints(self): # ARROW-2135 df = pd.DataFrame({"a": [1.0, 2.0, pd.np.NaN]}) schema = pa.schema([pa.field("a", pa.int16(), nullable=True)]) table = pa.Table.from_pandas(df, schema=schema) assert table[0].to_pylist() == [1, 2, None] tm.assert_frame_equal(df, table.to_pandas()) def test_integer_no_nulls(self): data = OrderedDict() fields = [] numpy_dtypes = [ ('i1', pa.int8()), ('i2', pa.int16()), ('i4', pa.int32()), ('i8', pa.int64()), ('u1', pa.uint8()), ('u2', pa.uint16()), ('u4', pa.uint32()), ('u8', pa.uint64()), ('longlong', pa.int64()), ('ulonglong', pa.uint64()) ] num_values = 100 for dtype, arrow_dtype in numpy_dtypes: info = np.iinfo(dtype) values = np.random.randint(max(info.min, np.iinfo(np.int_).min), min(info.max, np.iinfo(np.int_).max), size=num_values) data[dtype] = values.astype(dtype) fields.append(pa.field(dtype, arrow_dtype)) df = pd.DataFrame(data) schema = pa.schema(fields) _check_pandas_roundtrip(df, expected_schema=schema) def test_all_integer_types(self): # Test all Numpy integer aliases data = OrderedDict() numpy_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8', 'byte', 'ubyte', 'short', 'ushort', 'intc', 'uintc', 'int_', 'uint', 'longlong', 'ulonglong'] for dtype in numpy_dtypes: data[dtype] = np.arange(12, dtype=dtype) df = pd.DataFrame(data) _check_pandas_roundtrip(df) def test_integer_with_nulls(self): # pandas requires upcast to float dtype int_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'] num_values = 100 null_mask = np.random.randint(0, 10, size=num_values) < 3 expected_cols = [] arrays = [] for name in int_dtypes: values = np.random.randint(0, 100, size=num_values) arr = pa.array(values, mask=null_mask) arrays.append(arr) expected = values.astype('f8') expected[null_mask] = np.nan expected_cols.append(expected) ex_frame = pd.DataFrame(dict(zip(int_dtypes, expected_cols)), columns=int_dtypes) table = pa.Table.from_arrays(arrays, int_dtypes) result = table.to_pandas() tm.assert_frame_equal(result, ex_frame) def test_array_from_pandas_type_cast(self): arr = np.arange(10, dtype='int64') target_type = pa.int8() result = pa.array(arr, type=target_type) expected = pa.array(arr.astype('int8')) assert result.equals(expected) def test_boolean_no_nulls(self): num_values = 100 np.random.seed(0) df = pd.DataFrame({'bools': np.random.randn(num_values) > 0}) field = pa.field('bools', pa.bool_()) schema = pa.schema([field]) _check_pandas_roundtrip(df, expected_schema=schema) def test_boolean_nulls(self): # pandas requires upcast to object dtype num_values = 100 np.random.seed(0) mask = np.random.randint(0, 10, size=num_values) < 3 values = np.random.randint(0, 10, size=num_values) < 5 arr = pa.array(values, mask=mask) expected = values.astype(object) expected[mask] = None field = pa.field('bools', pa.bool_()) schema = pa.schema([field]) ex_frame = pd.DataFrame({'bools': expected}) table = pa.Table.from_arrays([arr], ['bools']) assert table.schema.equals(schema) result = table.to_pandas() tm.assert_frame_equal(result, ex_frame) def test_float_object_nulls(self): arr = np.array([None, 1.5, np.float64(3.5)] * 5, dtype=object) df = pd.DataFrame({'floats': arr}) expected = pd.DataFrame({'floats': pd.to_numeric(arr)}) field = pa.field('floats', pa.float64()) schema = pa.schema([field]) _check_pandas_roundtrip(df, expected=expected, expected_schema=schema) def test_int_object_nulls(self): arr = np.array([None, 1, np.int64(3)] * 5, dtype=object) df = pd.DataFrame({'ints': arr}) expected = pd.DataFrame({'ints': pd.to_numeric(arr)}) field = pa.field('ints', pa.int64()) schema = pa.schema([field]) _check_pandas_roundtrip(df, expected=expected, expected_schema=schema) def test_boolean_object_nulls(self): arr = np.array([False, None, True] * 100, dtype=object) df = pd.DataFrame({'bools': arr}) field = pa.field('bools', pa.bool_()) schema = pa.schema([field]) _check_pandas_roundtrip(df, expected_schema=schema) def test_all_nulls_cast_numeric(self): arr = np.array([None], dtype=object) def _check_type(t): a2 = pa.array(arr, type=t) assert a2.type == t assert a2[0].as_py() is None _check_type(pa.int32()) _check_type(pa.float64()) def test_half_floats_from_numpy(self): arr = np.array([1.5, np.nan], dtype=np.float16) a = pa.array(arr, type=pa.float16()) x, y = a.to_pylist() assert isinstance(x, np.float16) assert x == 1.5 assert isinstance(y, np.float16) assert np.isnan(y) a = pa.array(arr, type=pa.float16(), from_pandas=True) x, y = a.to_pylist() assert isinstance(x, np.float16) assert x == 1.5 assert y is None @pytest.mark.parametrize('dtype', ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8']) def test_array_integer_object_nulls_option(dtype): num_values = 100 null_mask = np.random.randint(0, 10, size=num_values) < 3 values = np.random.randint(0, 100, size=num_values, dtype=dtype) array = pa.array(values, mask=null_mask) if null_mask.any(): expected = values.astype('O') expected[null_mask] = None else: expected = values result = array.to_pandas(integer_object_nulls=True) np.testing.assert_equal(result, expected) @pytest.mark.parametrize('dtype', ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8']) def test_table_integer_object_nulls_option(dtype): num_values = 100 null_mask = np.random.randint(0, 10, size=num_values) < 3 values = np.random.randint(0, 100, size=num_values, dtype=dtype) array = pa.array(values, mask=null_mask) if null_mask.any(): expected = values.astype('O') expected[null_mask] = None else: expected = values expected = pd.DataFrame({dtype: expected}) table = pa.Table.from_arrays([array], [dtype]) result = table.to_pandas(integer_object_nulls=True) tm.assert_frame_equal(result, expected) class TestConvertDateTimeLikeTypes(object): """ Conversion tests for datetime- and timestamp-like types (date64, etc.). """ def test_timestamps_notimezone_no_nulls(self): df = pd.DataFrame({ 'datetime64': np.array([ '2007-07-13T01:23:34.123456789', '2006-01-13T12:34:56.432539784', '2010-08-13T05:46:57.437699912'], dtype='datetime64[ns]') }) field = pa.field('datetime64', pa.timestamp('ns')) schema = pa.schema([field]) _check_pandas_roundtrip( df, expected_schema=schema, ) def test_timestamps_notimezone_nulls(self): df = pd.DataFrame({ 'datetime64': np.array([ '2007-07-13T01:23:34.123456789', None, '2010-08-13T05:46:57.437699912'], dtype='datetime64[ns]') }) field = pa.field('datetime64', pa.timestamp('ns')) schema = pa.schema([field]) _check_pandas_roundtrip( df, expected_schema=schema, ) def test_timestamps_with_timezone(self): df = pd.DataFrame({ 'datetime64': np.array([ '2007-07-13T01:23:34.123', '2006-01-13T12:34:56.432', '2010-08-13T05:46:57.437'], dtype='datetime64[ms]') }) df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern') .to_frame()) _check_pandas_roundtrip(df) _check_series_roundtrip(df['datetime64']) # drop-in a null and ns instead of ms df = pd.DataFrame({ 'datetime64': np.array([ '2007-07-13T01:23:34.123456789', None, '2006-01-13T12:34:56.432539784', '2010-08-13T05:46:57.437699912'], dtype='datetime64[ns]') }) df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern') .to_frame()) _check_pandas_roundtrip(df) def test_python_datetime(self): # ARROW-2106 date_array = [datetime.today() + timedelta(days=x) for x in range(10)] df = pd.DataFrame({ 'datetime': pd.Series(date_array, dtype=object) }) table = pa.Table.from_pandas(df) assert isinstance(table[0].data.chunk(0), pa.TimestampArray) result = table.to_pandas() expected_df = pd.DataFrame({ 'datetime': date_array }) tm.assert_frame_equal(expected_df, result) def test_python_datetime_subclass(self): class MyDatetime(datetime): # see https://github.com/pandas-dev/pandas/issues/21142 nanosecond = 0.0 date_array = [MyDatetime(2000, 1, 1, 1, 1, 1)] df = pd.DataFrame({"datetime": pd.Series(date_array, dtype=object)}) table = pa.Table.from_pandas(df) assert isinstance(table[0].data.chunk(0), pa.TimestampArray) result = table.to_pandas() expected_df = pd.DataFrame({"datetime": date_array}) # https://github.com/pandas-dev/pandas/issues/21142 expected_df["datetime"] = pd.to_datetime(expected_df["datetime"]) tm.assert_frame_equal(expected_df, result) def test_python_date_subclass(self): class MyDate(date): pass date_array = [MyDate(2000, 1, 1)] df = pd.DataFrame({"date": pd.Series(date_array, dtype=object)}) table = pa.Table.from_pandas(df) assert isinstance(table[0].data.chunk(0), pa.Date32Array) result = table.to_pandas() expected_df = pd.DataFrame( {"date": np.array(["2000-01-01"], dtype="datetime64[ns]")} ) tm.assert_frame_equal(expected_df, result) def test_datetime64_to_date32(self): # ARROW-1718 arr = pa.array([date(2017, 10, 23), None]) c = pa.Column.from_array("d", arr) s = c.to_pandas() arr2 = pa.Array.from_pandas(s, type=pa.date32()) assert arr2.equals(arr.cast('date32')) @pytest.mark.parametrize('mask', [ None, np.ones(3), np.array([True, False, False]), ]) def test_pandas_datetime_to_date64(self, mask): s = pd.to_datetime([ '2018-05-10T00:00:00', '2018-05-11T00:00:00', '2018-05-12T00:00:00', ]) arr = pa.Array.from_pandas(s, type=pa.date64(), mask=mask) data = np.array([ date(2018, 5, 10), date(2018, 5, 11), date(2018, 5, 12) ]) expected = pa.array(data, mask=mask, type=pa.date64()) assert arr.equals(expected) @pytest.mark.parametrize('mask', [ None, np.ones(3), np.array([True, False, False]) ]) def test_pandas_datetime_to_date64_failures(self, mask): s = pd.to_datetime([ '2018-05-10T10:24:01', '2018-05-11T10:24:01', '2018-05-12T10:24:01', ]) expected_msg = 'Timestamp value had non-zero intraday milliseconds' with pytest.raises(pa.ArrowInvalid, match=expected_msg): pa.Array.from_pandas(s, type=pa.date64(), mask=mask) def test_date_infer(self): df = pd.DataFrame({ 'date': [date(2000, 1, 1), None, date(1970, 1, 1), date(2040, 2, 26)]}) table = pa.Table.from_pandas(df, preserve_index=False) field = pa.field('date', pa.date32()) # schema's metadata is generated by from_pandas conversion expected_schema = pa.schema([field], metadata=table.schema.metadata) assert table.schema.equals(expected_schema) result = table.to_pandas() expected = df.copy() expected['date'] = pd.to_datetime(df['date']) tm.assert_frame_equal(result, expected) def test_date_mask(self): arr = np.array([date(2017, 4, 3), date(2017, 4, 4)], dtype='datetime64[D]') mask = [True, False] result = pa.array(arr, mask=np.array(mask)) expected = np.array([None, date(2017, 4, 4)], dtype='datetime64[D]') expected = pa.array(expected, from_pandas=True) assert expected.equals(result) def test_date_objects_typed(self): arr = np.array([ date(2017, 4, 3), None, date(2017, 4, 4), date(2017, 4, 5)], dtype=object) arr_i4 = np.array([17259, -1, 17260, 17261], dtype='int32') arr_i8 = arr_i4.astype('int64') * 86400000 mask = np.array([False, True, False, False]) t32 = pa.date32() t64 = pa.date64() a32 = pa.array(arr, type=t32) a64 = pa.array(arr, type=t64) a32_expected = pa.array(arr_i4, mask=mask, type=t32) a64_expected = pa.array(arr_i8, mask=mask, type=t64) assert a32.equals(a32_expected) assert a64.equals(a64_expected) # Test converting back to pandas colnames = ['date32', 'date64'] table = pa.Table.from_arrays([a32, a64], colnames) table_pandas = table.to_pandas() ex_values = (np.array(['2017-04-03', '2017-04-04', '2017-04-04', '2017-04-05'], dtype='datetime64[D]') .astype('datetime64[ns]')) ex_values[1] = pd.NaT.value expected_pandas = pd.DataFrame({'date32': ex_values, 'date64': ex_values}, columns=colnames) tm.assert_frame_equal(table_pandas, expected_pandas) def test_dates_from_integers(self): t1 = pa.date32() t2 = pa.date64() arr = np.array([17259, 17260, 17261], dtype='int32') arr2 = arr.astype('int64') * 86400000 a1 = pa.array(arr, type=t1) a2 = pa.array(arr2, type=t2) expected = date(2017, 4, 3) assert a1[0].as_py() == expected assert a2[0].as_py() == expected @pytest.mark.xfail(reason="not supported ATM", raises=NotImplementedError) def test_timedelta(self): # TODO(jreback): Pandas only support ns resolution # Arrow supports ??? for resolution df = pd.DataFrame({ 'timedelta': np.arange(start=0, stop=3 * 86400000, step=86400000, dtype='timedelta64[ms]') }) pa.Table.from_pandas(df) def test_pytime_from_pandas(self): pytimes = [time(1, 2, 3, 1356), time(4, 5, 6, 1356)] # microseconds t1 = pa.time64('us') aobjs = np.array(pytimes + [None], dtype=object) parr = pa.array(aobjs) assert parr.type == t1 assert parr[0].as_py() == pytimes[0] assert parr[1].as_py() == pytimes[1] assert parr[2] is pa.NA # DataFrame df = pd.DataFrame({'times': aobjs}) batch = pa.RecordBatch.from_pandas(df) assert batch[0].equals(parr) # Test ndarray of int64 values arr = np.array([_pytime_to_micros(v) for v in pytimes], dtype='int64') a1 = pa.array(arr, type=pa.time64('us')) assert a1[0].as_py() == pytimes[0] a2 = pa.array(arr * 1000, type=pa.time64('ns')) assert a2[0].as_py() == pytimes[0] a3 = pa.array((arr / 1000).astype('i4'), type=pa.time32('ms')) assert a3[0].as_py() == pytimes[0].replace(microsecond=1000) a4 = pa.array((arr / 1000000).astype('i4'), type=pa.time32('s')) assert a4[0].as_py() == pytimes[0].replace(microsecond=0) def test_arrow_time_to_pandas(self): pytimes = [time(1, 2, 3, 1356), time(4, 5, 6, 1356), time(0, 0, 0)] expected = np.array(pytimes[:2] + [None]) expected_ms = np.array([x.replace(microsecond=1000) for x in pytimes[:2]] + [None]) expected_s = np.array([x.replace(microsecond=0) for x in pytimes[:2]] + [None]) arr = np.array([_pytime_to_micros(v) for v in pytimes], dtype='int64') arr = np.array([_pytime_to_micros(v) for v in pytimes], dtype='int64') null_mask = np.array([False, False, True], dtype=bool) a1 = pa.array(arr, mask=null_mask, type=pa.time64('us')) a2 = pa.array(arr * 1000, mask=null_mask, type=pa.time64('ns')) a3 = pa.array((arr / 1000).astype('i4'), mask=null_mask, type=pa.time32('ms')) a4 = pa.array((arr / 1000000).astype('i4'), mask=null_mask, type=pa.time32('s')) names = ['time64[us]', 'time64[ns]', 'time32[ms]', 'time32[s]'] batch = pa.RecordBatch.from_arrays([a1, a2, a3, a4], names) arr = a1.to_pandas() assert (arr == expected).all() arr = a2.to_pandas() assert (arr == expected).all() arr = a3.to_pandas() assert (arr == expected_ms).all() arr = a4.to_pandas() assert (arr == expected_s).all() df = batch.to_pandas() expected_df = pd.DataFrame({'time64[us]': expected, 'time64[ns]': expected, 'time32[ms]': expected_ms, 'time32[s]': expected_s}, columns=names) tm.assert_frame_equal(df, expected_df) def test_numpy_datetime64_columns(self): datetime64_ns = np.array([ '2007-07-13T01:23:34.123456789', None, '2006-01-13T12:34:56.432539784', '2010-08-13T05:46:57.437699912'], dtype='datetime64[ns]') _check_array_from_pandas_roundtrip(datetime64_ns) datetime64_us = np.array([ '2007-07-13T01:23:34.123456', None, '2006-01-13T12:34:56.432539', '2010-08-13T05:46:57.437699'], dtype='datetime64[us]') _check_array_from_pandas_roundtrip(datetime64_us) datetime64_ms = np.array([ '2007-07-13T01:23:34.123', None, '2006-01-13T12:34:56.432', '2010-08-13T05:46:57.437'], dtype='datetime64[ms]') _check_array_from_pandas_roundtrip(datetime64_ms) datetime64_s = np.array([ '2007-07-13T01:23:34', None, '2006-01-13T12:34:56', '2010-08-13T05:46:57'], dtype='datetime64[s]') _check_array_from_pandas_roundtrip(datetime64_s) def test_numpy_datetime64_day_unit(self): datetime64_d = np.array([ '2007-07-13', None, '2006-01-15', '2010-08-19'], dtype='datetime64[D]') _check_array_from_pandas_roundtrip(datetime64_d) def test_array_from_pandas_date_with_mask(self): m = np.array([True, False, True]) data = pd.Series([ date(1990, 1, 1), date(1991, 1, 1), date(1992, 1, 1) ]) result = pa.Array.from_pandas(data, mask=m) expected = pd.Series([None, date(1991, 1, 1), None]) assert pa.Array.from_pandas(expected).equals(result) def test_fixed_offset_timezone(self): df = pd.DataFrame({ 'a': [ pd.Timestamp('2012-11-11 00:00:00+01:00'), pd.NaT ] }) _check_pandas_roundtrip(df) _check_serialize_components_roundtrip(df) class TestConvertStringLikeTypes(object): """ Conversion tests for string and binary types. """ def test_unicode(self): repeats = 1000 values = [u'foo', None, u'bar', u'mañana', np.nan] df = pd.DataFrame({'strings': values * repeats}) field = pa.field('strings', pa.string()) schema = pa.schema([field]) _check_pandas_roundtrip(df, expected_schema=schema) def test_bytes_to_binary(self): values = [u'qux', b'foo', None, bytearray(b'barz'), 'qux', np.nan] df = pd.DataFrame({'strings': values}) table = pa.Table.from_pandas(df) assert table[0].type == pa.binary() values2 = [b'qux', b'foo', None, b'barz', b'qux', np.nan] expected = pd.DataFrame({'strings': values2}) _check_pandas_roundtrip(df, expected) @pytest.mark.large_memory def test_bytes_exceed_2gb(self): v1 = b'x' * 100000000 v2 = b'x' * 147483646 # ARROW-2227, hit exactly 2GB on the nose df = pd.DataFrame({ 'strings': [v1] * 20 + [v2] + ['x'] * 20 }) arr = pa.array(df['strings']) assert isinstance(arr, pa.ChunkedArray) assert arr.num_chunks == 2 arr = None table = pa.Table.from_pandas(df) assert table[0].data.num_chunks == 2 def test_fixed_size_bytes(self): values = [b'foo', None, bytearray(b'bar'), None, None, b'hey'] df = pd.DataFrame({'strings': values}) schema = pa.schema([pa.field('strings', pa.binary(3))]) table = pa.Table.from_pandas(df, schema=schema) assert table.schema[0].type == schema[0].type assert table.schema[0].name == schema[0].name result = table.to_pandas() tm.assert_frame_equal(result, df) def test_fixed_size_bytes_does_not_accept_varying_lengths(self): values = [b'foo', None, b'ba', None, None, b'hey'] df = pd.DataFrame({'strings': values}) schema = pa.schema([pa.field('strings', pa.binary(3))]) with pytest.raises(pa.ArrowInvalid): pa.Table.from_pandas(df, schema=schema) def test_variable_size_bytes(self): s = pd.Series([b'123', b'', b'a', None]) _check_series_roundtrip(s, type_=pa.binary()) def test_binary_from_bytearray(self): s = pd.Series([bytearray(b'123'), bytearray(b''), bytearray(b'a'), None]) # Explicitly set type _check_series_roundtrip(s, type_=pa.binary()) # Infer type from bytearrays _check_series_roundtrip(s, expected_pa_type=pa.binary()) def test_table_empty_str(self): values = ['', '', '', '', ''] df = pd.DataFrame({'strings': values}) field = pa.field('strings', pa.string()) schema = pa.schema([field]) table = pa.Table.from_pandas(df, schema=schema) result1 = table.to_pandas(strings_to_categorical=False) expected1 = pd.DataFrame({'strings': values}) tm.assert_frame_equal(result1, expected1, check_dtype=True) result2 = table.to_pandas(strings_to_categorical=True) expected2 = pd.DataFrame({'strings': pd.Categorical(values)}) tm.assert_frame_equal(result2, expected2, check_dtype=True) def test_selective_categoricals(self): values = ['', '', '', '', ''] df = pd.DataFrame({'strings': values}) field = pa.field('strings', pa.string()) schema = pa.schema([field]) table = pa.Table.from_pandas(df, schema=schema) expected_str = pd.DataFrame({'strings': values}) expected_cat = pd.DataFrame({'strings': pd.Categorical(values)}) result1 = table.to_pandas(categories=['strings']) tm.assert_frame_equal(result1, expected_cat, check_dtype=True) result2 = table.to_pandas(categories=[]) tm.assert_frame_equal(result2, expected_str, check_dtype=True) result3 = table.to_pandas(categories=('strings',)) tm.assert_frame_equal(result3, expected_cat, check_dtype=True) result4 = table.to_pandas(categories=tuple()) tm.assert_frame_equal(result4, expected_str, check_dtype=True) def test_table_str_to_categorical_without_na(self): values = ['a', 'a', 'b', 'b', 'c'] df = pd.DataFrame({'strings': values}) field = pa.field('strings', pa.string()) schema = pa.schema([field]) table = pa.Table.from_pandas(df, schema=schema) result = table.to_pandas(strings_to_categorical=True) expected = pd.DataFrame({'strings': pd.Categorical(values)}) tm.assert_frame_equal(result, expected, check_dtype=True) with pytest.raises(pa.ArrowInvalid): table.to_pandas(strings_to_categorical=True, zero_copy_only=True) def test_table_str_to_categorical_with_na(self): values = [None, 'a', 'b', np.nan] df = pd.DataFrame({'strings': values}) field = pa.field('strings', pa.string()) schema = pa.schema([field]) table = pa.Table.from_pandas(df, schema=schema) result = table.to_pandas(strings_to_categorical=True) expected = pd.DataFrame({'strings': pd.Categorical(values)}) tm.assert_frame_equal(result, expected, check_dtype=True) with pytest.raises(pa.ArrowInvalid): table.to_pandas(strings_to_categorical=True, zero_copy_only=True) # Regression test for ARROW-2101 def test_array_of_bytes_to_strings(self): converted = pa.array(np.array([b'x'], dtype=object), pa.string()) assert converted.type == pa.string() # Make sure that if an ndarray of bytes is passed to the array # constructor and the type is string, it will fail if those bytes # cannot be converted to utf-8 def test_array_of_bytes_to_strings_bad_data(self): with pytest.raises( pa.lib.ArrowInvalid, match=("'(utf8|utf-8)' codec can't decode byte 0x80 " "in position 0: invalid start byte")): pa.array(np.array([b'\x80\x81'], dtype=object), pa.string()) def test_numpy_string_array_to_fixed_size_binary(self): arr = np.array([b'foo', b'bar', b'baz'], dtype='|S3') converted = pa.array(arr, type=pa.binary(3)) expected = pa.array(list(arr), type=pa.binary(3)) assert converted.equals(expected) mask = np.array([True, False, True]) converted = pa.array(arr, type=pa.binary(3), mask=mask) expected = pa.array([b'foo', None, b'baz'], type=pa.binary(3)) assert converted.equals(expected) with pytest.raises(pa.lib.ArrowInvalid, match='Got bytestring of length 3 \(expected 4\)'): arr = np.array([b'foo', b'bar', b'baz'], dtype='|S3') pa.array(arr, type=pa.binary(4)) with pytest.raises(pa.lib.ArrowInvalid, match='Got bytestring of length 12 \(expected 3\)'): arr = np.array([b'foo', b'bar', b'baz'], dtype='|U3') pa.array(arr, type=pa.binary(3)) class TestConvertDecimalTypes(object): """ Conversion test for decimal types. """ decimal32 = [ decimal.Decimal('-1234.123'), decimal.Decimal('1234.439') ] decimal64 = [ decimal.Decimal('-129934.123331'), decimal.Decimal('129534.123731') ] decimal128 = [ decimal.Decimal('394092382910493.12341234678'), decimal.Decimal('-314292388910493.12343437128') ] @pytest.mark.parametrize(('values', 'expected_type'), [ pytest.param(decimal32, pa.decimal128(7, 3), id='decimal32'), pytest.param(decimal64, pa.decimal128(12, 6), id='decimal64'), pytest.param(decimal128, pa.decimal128(26, 11), id='decimal128') ]) def test_decimal_from_pandas(self, values, expected_type): expected = pd.DataFrame({'decimals': values}) table = pa.Table.from_pandas(expected, preserve_index=False) field = pa.field('decimals', expected_type) # schema's metadata is generated by from_pandas conversion expected_schema = pa.schema([field], metadata=table.schema.metadata) assert table.schema.equals(expected_schema) @pytest.mark.parametrize('values', [ pytest.param(decimal32, id='decimal32'), pytest.param(decimal64, id='decimal64'), pytest.param(decimal128, id='decimal128') ]) def test_decimal_to_pandas(self, values): expected = pd.DataFrame({'decimals': values}) converted = pa.Table.from_pandas(expected) df = converted.to_pandas() tm.assert_frame_equal(df, expected) def test_decimal_fails_with_truncation(self): data1 = [decimal.Decimal('1.234')] type1 = pa.decimal128(10, 2) with pytest.raises(pa.ArrowInvalid): pa.array(data1, type=type1) data2 = [decimal.Decimal('1.2345')] type2 = pa.decimal128(10, 3) with pytest.raises(pa.ArrowInvalid): pa.array(data2, type=type2) def test_decimal_with_different_precisions(self): data = [ decimal.Decimal('0.01'), decimal.Decimal('0.001'), ] series = pd.Series(data) array = pa.array(series) assert array.to_pylist() == data assert array.type == pa.decimal128(3, 3) array = pa.array(data, type=pa.decimal128(12, 5)) expected = [decimal.Decimal('0.01000'), decimal.Decimal('0.00100')] assert array.to_pylist() == expected def test_decimal_with_None_explicit_type(self): series = pd.Series([decimal.Decimal('3.14'), None]) _check_series_roundtrip(series, type_=pa.decimal128(12, 5)) # Test that having all None values still produces decimal array series = pd.Series([None] * 2) _check_series_roundtrip(series, type_=pa.decimal128(12, 5)) def test_decimal_with_None_infer_type(self): series = pd.Series([decimal.Decimal('3.14'), None]) _check_series_roundtrip(series, expected_pa_type=pa.decimal128(3, 2)) class TestListTypes(object): """ Conversion tests for list<> types. """ def test_column_of_arrays(self): df, schema = dataframe_with_arrays() _check_pandas_roundtrip(df, schema=schema, expected_schema=schema) table = pa.Table.from_pandas(df, schema=schema, preserve_index=False) # schema's metadata is generated by from_pandas conversion expected_schema = schema.add_metadata(table.schema.metadata) assert table.schema.equals(expected_schema) for column in df.columns: field = schema.field_by_name(column) _check_array_roundtrip(df[column], type=field.type) def test_column_of_arrays_to_py(self): # Test regression in ARROW-1199 not caught in above test dtype = 'i1' arr = np.array([ np.arange(10, dtype=dtype), np.arange(5, dtype=dtype), None, np.arange(1, dtype=dtype) ]) type_ = pa.list_(pa.int8()) parr = pa.array(arr, type=type_) assert parr[0].as_py() == list(range(10)) assert parr[1].as_py() == list(range(5)) assert parr[2].as_py() is None assert parr[3].as_py() == [0] def test_column_of_lists(self): df, schema = dataframe_with_lists() _check_pandas_roundtrip(df, schema=schema, expected_schema=schema) table = pa.Table.from_pandas(df, schema=schema, preserve_index=False) # schema's metadata is generated by from_pandas conversion expected_schema = schema.add_metadata(table.schema.metadata) assert table.schema.equals(expected_schema) for column in df.columns: field = schema.field_by_name(column) _check_array_roundtrip(df[column], type=field.type) def test_column_of_lists_first_empty(self): # ARROW-2124 num_lists = [[], [2, 3, 4], [3, 6, 7, 8], [], [2]] series = pd.Series([np.array(s, dtype=float) for s in num_lists]) arr = pa.array(series) result = pd.Series(arr.to_pandas()) tm.assert_series_equal(result, series) def test_column_of_lists_chunked(self): # ARROW-1357 df = pd.DataFrame({ 'lists': np.array([ [1, 2], None, [2, 3], [4, 5], [6, 7], [8, 9] ], dtype=object) }) schema = pa.schema([ pa.field('lists', pa.list_(pa.int64())) ]) t1 = pa.Table.from_pandas(df[:2], schema=schema) t2 = pa.Table.from_pandas(df[2:], schema=schema) table = pa.concat_tables([t1, t2]) result = table.to_pandas() tm.assert_frame_equal(result, df) def test_column_of_lists_chunked2(self): data1 = [[0, 1], [2, 3], [4, 5], [6, 7], [10, 11], [12, 13], [14, 15], [16, 17]] data2 = [[8, 9], [18, 19]] a1 = pa.array(data1) a2 = pa.array(data2) t1 = pa.Table.from_arrays([a1], names=['a']) t2 = pa.Table.from_arrays([a2], names=['a']) concatenated = pa.concat_tables([t1, t2]) result = concatenated.to_pandas() expected = pd.DataFrame({'a': data1 + data2}) tm.assert_frame_equal(result, expected) def test_column_of_lists_strided(self): df, schema = dataframe_with_lists() df = pd.concat([df] * 6, ignore_index=True) arr = df['int64'].values[::3] assert arr.strides[0] != 8 _check_array_roundtrip(arr) def test_nested_lists_all_none(self): data = np.array([[None, None], None], dtype=object) arr = pa.array(data) expected = pa.array(list(data)) assert arr.equals(expected) assert arr.type == pa.list_(pa.null()) data2 = np.array([None, None, [None, None], np.array([None, None], dtype=object)], dtype=object) arr = pa.array(data2) expected = pa.array([None, None, [None, None], [None, None]]) assert arr.equals(expected) def test_nested_lists_all_empty(self): # ARROW-2128 data = pd.Series([[], [], []]) arr = pa.array(data) expected = pa.array(list(data)) assert arr.equals(expected) assert arr.type == pa.list_(pa.null()) def test_nested_smaller_ints(self): # ARROW-1345, ARROW-2008, there were some type inference bugs happening # before data = pd.Series([np.array([1, 2, 3], dtype='i1'), None]) result = pa.array(data) result2 = pa.array(data.values) expected = pa.array([[1, 2, 3], None], type=pa.list_(pa.int8())) assert result.equals(expected) assert result2.equals(expected) data3 = pd.Series([np.array([1, 2, 3], dtype='f4'), None]) result3 = pa.array(data3) expected3 = pa.array([[1, 2, 3], None], type=pa.list_(pa.float32())) assert result3.equals(expected3) def test_infer_lists(self): data = OrderedDict([ ('nan_ints', [[None, 1], [2, 3]]), ('ints', [[0, 1], [2, 3]]), ('strs', [[None, u'b'], [u'c', u'd']]), ('nested_strs', [[[None, u'b'], [u'c', u'd']], None]) ]) df = pd.DataFrame(data) expected_schema = pa.schema([ pa.field('nan_ints', pa.list_(pa.int64())), pa.field('ints', pa.list_(pa.int64())), pa.field('strs', pa.list_(pa.string())), pa.field('nested_strs', pa.list_(pa.list_(pa.string()))) ]) _check_pandas_roundtrip(df, expected_schema=expected_schema) def test_infer_numpy_array(self): data = OrderedDict([ ('ints', [ np.array([0, 1], dtype=np.int64), np.array([2, 3], dtype=np.int64) ]) ]) df = pd.DataFrame(data) expected_schema = pa.schema([ pa.field('ints', pa.list_(pa.int64())) ]) _check_pandas_roundtrip(df, expected_schema=expected_schema) @pytest.mark.parametrize('t,data,expected', [ ( pa.int64, [[1, 2], [3], None], [None, [3], None] ), ( pa.string, [[u'aaa', u'bb'], [u'c'], None], [None, [u'c'], None] ), ( pa.null, [[None, None], [None], None], [None, [None], None] ) ]) def test_array_from_pandas_typed_array_with_mask(self, t, data, expected): m = np.array([True, False, True]) s = pd.Series(data) result = pa.Array.from_pandas(s, mask=m, type=pa.list_(t())) assert pa.Array.from_pandas(expected, type=pa.list_(t())).equals(result) def test_empty_list_roundtrip(self): empty_list_array = np.empty((3,), dtype=object) empty_list_array.fill([]) df = pd.DataFrame({'a': np.array(['1', '2', '3']), 'b': empty_list_array}) tbl = pa.Table.from_pandas(df) result = tbl.to_pandas() tm.assert_frame_equal(result, df) def test_array_from_nested_arrays(self): df, schema = dataframe_with_arrays() for field in schema: arr = df[field.name].values expected = pa.array(list(arr), type=field.type) result = pa.array(arr) assert result.type == field.type # == list<scalar> assert result.equals(expected) class TestConvertStructTypes(object): """ Conversion tests for struct types. """ def test_to_pandas(self): ints = pa.array([None, 2, 3], type=pa.int64()) strs = pa.array([u'a', None, u'c'], type=pa.string()) bools = pa.array([True, False, None], type=pa.bool_()) arr = pa.StructArray.from_arrays( [ints, strs, bools], ['ints', 'strs', 'bools']) expected = pd.Series([ {'ints': None, 'strs': u'a', 'bools': True}, {'ints': 2, 'strs': None, 'bools': False}, {'ints': 3, 'strs': u'c', 'bools': None}, ]) series = pd.Series(arr.to_pandas()) tm.assert_series_equal(series, expected) def test_from_numpy(self): dt = np.dtype([('x', np.int32), (('y_title', 'y'), np.bool_)]) ty = pa.struct([pa.field('x', pa.int32()), pa.field('y', pa.bool_())]) data = np.array([], dtype=dt) arr = pa.array(data, type=ty) assert arr.to_pylist() == [] data = np.array([(42, True), (43, False)], dtype=dt) arr = pa.array(data, type=ty) assert arr.to_pylist() == [{'x': 42, 'y': True}, {'x': 43, 'y': False}] # With mask arr = pa.array(data, mask=np.bool_([False, True]), type=ty) assert arr.to_pylist() == [{'x': 42, 'y': True}, None] # Trivial struct type dt = np.dtype([]) ty = pa.struct([]) data = np.array([], dtype=dt) arr = pa.array(data, type=ty) assert arr.to_pylist() == [] data = np.array([(), ()], dtype=dt) arr = pa.array(data, type=ty) assert arr.to_pylist() == [{}, {}] def test_from_numpy_nested(self): dt = np.dtype([('x', np.dtype([('xx', np.int8), ('yy', np.bool_)])), ('y', np.int16)]) ty = pa.struct([pa.field('x', pa.struct([pa.field('xx', pa.int8()), pa.field('yy', pa.bool_())])), pa.field('y', pa.int16())]) data = np.array([], dtype=dt) arr = pa.array(data, type=ty) assert arr.to_pylist() == [] data = np.array([((1, True), 2), ((3, False), 4)], dtype=dt) arr = pa.array(data, type=ty) assert arr.to_pylist() == [{'x': {'xx': 1, 'yy': True}, 'y': 2}, {'x': {'xx': 3, 'yy': False}, 'y': 4}] @pytest.mark.large_memory def test_from_numpy_large(self): # Exercise rechunking + nulls target_size = 3 * 1024**3 # 4GB dt = np.dtype([('x', np.float64), ('y', 'object')]) bs = 65536 - dt.itemsize block = b'.' * bs n = target_size // (bs + dt.itemsize) data = np.zeros(n, dtype=dt) data['x'] = np.random.random_sample(n) data['y'] = block # Add implicit nulls data['x'][data['x'] < 0.2] = np.nan ty = pa.struct([pa.field('x', pa.float64()), pa.field('y', pa.binary(bs))]) arr = pa.array(data, type=ty, from_pandas=True) assert arr.num_chunks == 2 def iter_chunked_array(arr): for chunk in arr.iterchunks(): for item in chunk: yield item def check(arr, data, mask=None): assert len(arr) == len(data) xs = data['x'] ys = data['y'] for i, obj in enumerate(iter_chunked_array(arr)): try: d = obj.as_py() if mask is not None and mask[i]: assert d is None else: x = xs[i] if np.isnan(x): assert d['x'] is None else: assert d['x'] == x assert d['y'] == ys[i] except Exception: print("Failed at index", i) raise check(arr, data) del arr # Now with explicit mask mask = np.random.random_sample(n) < 0.2 arr = pa.array(data, type=ty, mask=mask, from_pandas=True) assert arr.num_chunks == 2 check(arr, data, mask) del arr def test_from_numpy_bad_input(self): ty = pa.struct([pa.field('x', pa.int32()), pa.field('y', pa.bool_())]) dt = np.dtype([('x', np.int32), ('z', np.bool_)]) data = np.array([], dtype=dt) with pytest.raises(TypeError, match="Missing field 'y'"): pa.array(data, type=ty) data = np.int32([]) with pytest.raises(TypeError, match="Expected struct array"): pa.array(data, type=ty) class TestZeroCopyConversion(object): """ Tests that zero-copy conversion works with some types. """ def test_zero_copy_success(self): result = pa.array([0, 1, 2]).to_pandas(zero_copy_only=True) npt.assert_array_equal(result, [0, 1, 2]) def test_zero_copy_dictionaries(self): arr = pa.DictionaryArray.from_arrays( np.array([0, 0]), np.array([5])) result = arr.to_pandas(zero_copy_only=True) values = pd.Categorical([5, 5]) tm.assert_series_equal(pd.Series(result), pd.Series(values), check_names=False) def check_zero_copy_failure(self, arr): with pytest.raises(pa.ArrowInvalid): arr.to_pandas(zero_copy_only=True) def test_zero_copy_failure_on_object_types(self): self.check_zero_copy_failure(pa.array(['A', 'B', 'C'])) def test_zero_copy_failure_with_int_when_nulls(self): self.check_zero_copy_failure(pa.array([0, 1, None])) def test_zero_copy_failure_with_float_when_nulls(self): self.check_zero_copy_failure(pa.array([0.0, 1.0, None])) def test_zero_copy_failure_on_bool_types(self): self.check_zero_copy_failure(pa.array([True, False])) def test_zero_copy_failure_on_list_types(self): arr = pa.array([[1, 2], [8, 9]], type=pa.list_(pa.int64())) self.check_zero_copy_failure(arr) def test_zero_copy_failure_on_timestamp_types(self): arr = np.array(['2007-07-13'], dtype='datetime64[ns]') self.check_zero_copy_failure(pa.array(arr)) class TestConvertMisc(object): """ Miscellaneous conversion tests. """ type_pairs = [ (np.int8, pa.int8()), (np.int16, pa.int16()), (np.int32, pa.int32()), (np.int64, pa.int64()), (np.uint8, pa.uint8()), (np.uint16, pa.uint16()), (np.uint32, pa.uint32()), (np.uint64, pa.uint64()), (np.float16, pa.float16()), (np.float32, pa.float32()), (np.float64, pa.float64()), # XXX unsupported # (np.dtype([('a', 'i2')]), pa.struct([pa.field('a', pa.int16())])), (np.object, pa.string()), (np.object, pa.binary()), (np.object, pa.binary(10)), (np.object, pa.list_(pa.int64())), ] def test_all_none_objects(self): df = pd.DataFrame({'a': [None, None, None]}) _check_pandas_roundtrip(df) def test_all_none_category(self): df = pd.DataFrame({'a': [None, None, None]}) df['a'] = df['a'].astype('category') _check_pandas_roundtrip(df) def test_empty_arrays(self): for dtype, pa_type in self.type_pairs: arr = np.array([], dtype=dtype) _check_array_roundtrip(arr, type=pa_type) def test_threaded_conversion(self): df = _alltypes_example() _check_pandas_roundtrip(df, use_threads=True) _check_pandas_roundtrip(df, use_threads=True, as_batch=True) def test_category(self): repeats = 5 v1 = ['foo', None, 'bar', 'qux', np.nan] v2 = [4, 5, 6, 7, 8] v3 = [b'foo', None, b'bar', b'qux', np.nan] df = pd.DataFrame({'cat_strings': pd.Categorical(v1 * repeats), 'cat_ints': pd.Categorical(v2 * repeats), 'cat_binary': pd.Categorical(v3 * repeats), 'cat_strings_ordered': pd.Categorical( v1 * repeats, categories=['bar', 'qux', 'foo'], ordered=True), 'ints': v2 * repeats, 'ints2': v2 * repeats, 'strings': v1 * repeats, 'strings2': v1 * repeats, 'strings3': v3 * repeats}) _check_pandas_roundtrip(df) arrays = [ pd.Categorical(v1 * repeats), pd.Categorical(v2 * repeats), pd.Categorical(v3 * repeats) ] for values in arrays: _check_array_roundtrip(values) def test_empty_category(self): # ARROW-2443 df = pd.DataFrame({'cat': pd.Categorical([])}) _check_pandas_roundtrip(df) def test_mixed_types_fails(self): data = pd.DataFrame({'a': ['a', 1, 2.0]}) with pytest.raises(pa.ArrowTypeError): pa.Table.from_pandas(data) data = pd.DataFrame({'a': [1, True]}) with pytest.raises(pa.ArrowTypeError): pa.Table.from_pandas(data) def test_strided_data_import(self): cases = [] columns = ['a', 'b', 'c'] N, K = 100, 3 random_numbers = np.random.randn(N, K).copy() * 100 numeric_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8', 'f4', 'f8'] for type_name in numeric_dtypes: cases.append(random_numbers.astype(type_name)) # strings cases.append(np.array([tm.rands(10) for i in range(N * K)], dtype=object) .reshape(N, K).copy()) # booleans boolean_objects = (np.array([True, False, True] * N, dtype=object) .reshape(N, K).copy()) # add some nulls, so dtype comes back as objects boolean_objects[5] = None cases.append(boolean_objects) cases.append(np.arange("2016-01-01T00:00:00.001", N * K, dtype='datetime64[ms]') .reshape(N, K).copy()) strided_mask = (random_numbers > 0).astype(bool)[:, 0] for case in cases: df = pd.DataFrame(case, columns=columns) col = df['a'] _check_pandas_roundtrip(df) _check_array_roundtrip(col) _check_array_roundtrip(col, mask=strided_mask) def test_all_nones(self): def _check_series(s): converted = pa.array(s) assert isinstance(converted, pa.NullArray) assert len(converted) == 3 assert converted.null_count == 3 assert converted[0] is pa.NA _check_series(pd.Series([None] * 3, dtype=object)) _check_series(pd.Series([np.nan] * 3, dtype=object)) _check_series(pd.Series([np.sqrt(-1)] * 3, dtype=object)) def test_partial_schema(self): data = OrderedDict([ ('a', [0, 1, 2, 3, 4]), ('b', np.array([-10, -5, 0, 5, 10], dtype=np.int32)), ('c', [-10, -5, 0, 5, 10]) ]) df = pd.DataFrame(data) partial_schema = pa.schema([ pa.field('a', pa.int64()), pa.field('b', pa.int32()) ]) expected_schema = pa.schema([ pa.field('a', pa.int64()), pa.field('b', pa.int32()), pa.field('c', pa.int64()) ]) _check_pandas_roundtrip(df, schema=partial_schema, expected_schema=expected_schema) def test_table_batch_empty_dataframe(self): df = pd.DataFrame({}) _check_pandas_roundtrip(df) _check_pandas_roundtrip(df, as_batch=True) df2 = pd.DataFrame({}, index=[0, 1, 2]) _check_pandas_roundtrip(df2, preserve_index=True) _check_pandas_roundtrip(df2, as_batch=True, preserve_index=True) def test_convert_empty_table(self): arr = pa.array([], type=pa.int64()) tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=np.int64)) arr = pa.array([], type=pa.string()) tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object)) arr = pa.array([], type=pa.list_(pa.int64())) tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object)) arr = pa.array([], type=pa.struct([pa.field('a', pa.int64())])) tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object)) def test_non_natural_stride(self): """ ARROW-2172: converting from a Numpy array with a stride that's not a multiple of itemsize. """ dtype = np.dtype([('x', np.int32), ('y', np.int16)]) data = np.array([(42, -1), (-43, 2)], dtype=dtype) assert data.strides == (6,) arr = pa.array(data['x'], type=pa.int32()) assert arr.to_pylist() == [42, -43] arr = pa.array(data['y'], type=pa.int16()) assert arr.to_pylist() == [-1, 2] def test_mixed_integer_columns(self): row = [[], []] df = pd.DataFrame(data=[row], columns=['foo', 123]) expected_df = pd.DataFrame(data=[row], columns=['foo', '123']) _check_pandas_roundtrip(df, expected=expected_df, preserve_index=True) def _fully_loaded_dataframe_example(): from distutils.version import LooseVersion index = pd.MultiIndex.from_arrays([ pd.date_range('2000-01-01', periods=5).repeat(2), np.tile(np.array(['foo', 'bar'], dtype=object), 5) ]) c1 = pd.date_range('2000-01-01', periods=10) data = { 0: c1, 1: c1.tz_localize('utc'), 2: c1.tz_localize('US/Eastern'), 3: c1[::2].tz_localize('utc').repeat(2).astype('category'), 4: ['foo', 'bar'] * 5, 5: pd.Series(['foo', 'bar'] * 5).astype('category').values, 6: [True, False] * 5, 7: np.random.randn(10), 8: np.random.randint(0, 100, size=10), 9: pd.period_range('2013', periods=10, freq='M') } if LooseVersion(pd.__version__) >= '0.21': # There is an issue with pickling IntervalIndex in pandas 0.20.x data[10] = pd.interval_range(start=1, freq=1, periods=10) return pd.DataFrame(data, index=index) @pytest.mark.parametrize('columns', ([b'foo'], ['foo'])) def test_roundtrip_with_bytes_unicode(columns): df = pd.DataFrame(columns=columns) table1 = pa.Table.from_pandas(df) table2 = pa.Table.from_pandas(table1.to_pandas()) assert table1.equals(table2) assert table1.schema.equals(table2.schema) assert table1.schema.metadata == table2.schema.metadata def _check_serialize_components_roundtrip(df): ctx = pa.default_serialization_context() components = ctx.serialize(df).to_components() deserialized = ctx.deserialize_components(components) tm.assert_frame_equal(df, deserialized) def test_serialize_deserialize_pandas(): # ARROW-1784, serialize and deserialize DataFrame by decomposing # BlockManager df = _fully_loaded_dataframe_example() _check_serialize_components_roundtrip(df) def _pytime_from_micros(val): microseconds = val % 1000000 val //= 1000000 seconds = val % 60 val //= 60 minutes = val % 60 hours = val // 60 return time(hours, minutes, seconds, microseconds) def _pytime_to_micros(pytime): return (pytime.hour * 3600000000 + pytime.minute * 60000000 + pytime.second * 1000000 + pytime.microsecond)
taFrame({u'あ': [u'い'], b'a': 1}, index=[u'う']) # TODO(phillipc): Should this raise? with pytest.raises(AssertionError): _check_pandas_roundtrip(df, preserve_index=True) def test_b
HorizontalTimelineContent.js
import React from "react"; import PropTypes from "prop-types"; // import SwipeableViews from "react-swipeable-views"; import HorizontalTimeline from "../../src/Components/HorizontalTimeline"; // import HorizontalTimelineConfigurator from "./HorizontalTimelineConfigurator"; export default class HorizontalTimelineContent extends React.Component { values = []; constructor(props) { super(props); this.createArray(); this.state = { value: this.props.valueArray.length - 1, previous: this.props.valueArray.length - 2, showConfigurator: false, // timelineConfig minEventPadding: 20, maxEventPadding: 20, linePadding: 50, labelWidth: 50, fillingMotionStiffness: 150, fillingMotionDamping: 25, slidingMotionStiffness: 150, slidingMotionDamping: 25, stylesBackground: "#f8f8f8", stylesForeground: "#7b9d6f", stylesOutline: "#dfdfdf", isTouchEnabled: true, isKeyboardEnabled: true, isOpenEnding: true, isOpenBeginning: true
createArray() { console.log(this.props.valueArray); this.valueArray = this.props.valueArray; if (this.valueArray != null) { for (var i = 0; i < this.valueArray.length; i++) { this.values[i] = "" + (i + 1); } } } // static propTypes = { // content: PropTypes.arrayOf(PropTypes.object).isRequired // }; // componentWillMount() { // this.dates = this.props.content.map(entry => entry.date); // } // componentWillReceiveProps(nextProps) { // this.dates = nextProps.content.map(entry => entry.date); // } render() { const state = this.state; // const views = this.props.content.map((entry, index) => { // return ( // <div className="container" key={index}> // {entry.component} // </div> // ); // }); // let configurator = <div></div>; // if (this.state.showConfigurator) { // configurator = ( // <HorizontalTimelineConfigurator // setConfig={(key, value) => { // this.setState({ [key]: value }); // }} // {...this.state} // /> // ); // } return ( <div> <div style={{ width: "60%", height: "100px", margin: "0 auto" }}> <HorizontalTimeline fillingMotion={{ stiffness: state.fillingMotionStiffness, damping: state.fillingMotionDamping }} index={this.state.value} indexClick={index => { this.setState({ value: index, previous: this.state.value }); this.valueArray = this.props.valueArray; // if (this.valueArray != null) { // for (var i = 0; i < this.valueArray.length; i++) { // console.log(">>", this.valueArray[i]); // } // } console.log("index", index); console.log( "id", this.valueArray[this.valueArray.length - index - 1] ); this.props.onRevertCode( this.props.repo, this.valueArray[this.valueArray.length - index - 1] ); }} isKeyboardEnabled={state.isKeyboardEnabled} isTouchEnabled={state.isTouchEnabled} labelWidth={state.labelWidth} linePadding={state.linePadding} maxEventPadding={state.maxEventPadding} minEventPadding={state.minEventPadding} slidingMotion={{ stiffness: state.slidingMotionStiffness, damping: state.slidingMotionDamping }} styles={{ background: state.stylesBackground, foreground: state.stylesForeground, outline: state.stylesOutline }} // values={this.dates} values={this.values} isOpenEnding={state.isOpenEnding} isOpenBeginning={state.isOpenBeginning} /> </div> {/* <div className="text-center"> <SwipeableViews index={this.state.value} onChangeIndex={(value, previous) => { this.setState({ value: value, previous: previous }); }} resistance > {views} </SwipeableViews> </div> */} {/* <div className="checkbox text-center"> <label> <input onChange={() => { this.setState({ showConfigurator: !this.state.showConfigurator }); }} type="checkbox" /> Configure the Timeline </label> </div> {configurator} */} </div> ); } }
}; }
lib.rs
//! # Watt //! //! Watt<sup>*</sup> is a runtime for executing Rust procedural macros compiled //! as WebAssembly. //! //! <sub><b>*</b><i>optional but entertaining pronunciation: //! <u>wahteetee</u></i></sub> //! //! <br> //! //! # Rationale //! //! - **Faster compilation.**&emsp;By compiling macros ahead-of-time to Wasm, we //! save all downstream users of the macro from having to compile the macro //! logic or its dependencies themselves. //! //! Instead, what they compile is a small self-contained Wasm runtime (~3 //! seconds, shared by all macros) and a tiny proc macro shim for each macro //! crate to hand off Wasm bytecode into the Watt runtime (~0.3 seconds per //! proc-macro crate you depend on). This is much less than the 20+ seconds it //! can take to compile complex procedural macros and their dependencies. //! //! - **Isolation.**&emsp;The Watt runtime is 100% safe code with zero //! dependencies. While running in this environment, a macro's *only possible //! interaction with the world* is limited to consuming tokens and producing //! tokens. This is true regardless of how much unsafe code the macro itself //! might contain! Modulo bugs in the Rust compiler or standard library, it is //! impossible for a macro to do anything other than shuffle tokens around. //! //! - **Determinism.**&emsp;From a build system point of view, a macro backed by //! Wasm has the advantage that it can be treated as a purely deterministic //! function from input to output. There is no possibility of implicit //! dependencies, such as via the filesystem, which aren't visible to or take //! into account by the build system. //! //! <br> //! //! # Getting started //! //! Start by implementing and testing your proc macro as you normally would, //! using whatever dependencies you want (syn, quote, etc). You will end up with //! something that looks like: //! //! ``` //! # const IGNORE: &str = stringify! { //! extern crate proc_macro; //! //! use proc_macro::TokenStream; //! //! #[proc_macro] //! pub fn my_macro(input: TokenStream) -> TokenStream { //! /* ... */ //! } //! # }; //! ``` //! //! `#[proc_macro_derive]` and `#[proc_macro_attribute]` are supported as well; //! everything is analogous to what will be shown here for `#[proc_macro]`. //! //! When your macro is ready, there are just a few changes we need to make to //! the signature and the Cargo.toml. In your lib.rs, change each of your macro //! entry points to a no\_mangle extern "C" function, and change the TokenStream //! in the signature from proc\_macro to proc\_macro2. Finally, add a call to //! `proc_macro2::set_wasm_panic_hook()` at the top of your macro to ensure //! panics get printed to the console; this is optional but helpful! //! //! It will look like: //! //! ``` //! # const IGNORE: &str = stringify! { //! use proc_macro2::TokenStream; //! //! #[no_mangle] //! pub extern "C" fn my_macro(input: TokenStream) -> TokenStream { //! proc_macro2::set_wasm_panic_hook(); //! //! /* same as before */ //! } //! # }; //! ``` //! //! Now in your macro's Cargo.toml which used to contain this: //! //! ```toml //! [lib] //! proc-macro = true //! ``` //! //! change it instead to say: //! //! ```toml //! [lib] //! crate-type = ["cdylib", "rlib"] //! //! [patch.crates-io] //! proc-macro2 = { git = "https://github.com/dtolnay/watt" } //! ``` //! //! This crate will be the binary that we compile to Wasm. Compile it by //! running: //! //! ```console //! $ cargo build --release --target wasm32-unknown-unknown //! ``` //! //! Next we need to make a small proc-macro shim crate to hand off the compiled //! Wasm bytes into the Watt runtime. In a new Cargo.toml, put: //! //! ```toml //! [lib] //! proc-macro = true //! //! [dependencies] //! watt = "0.1" //! ``` //! //! And in its src/lib.rs put: //! //! ``` //! # const IGNORE: &str = stringify! { //! extern crate proc_macro; //! //! use proc_macro::TokenStream; //! //! static WASM: &[u8] = include_bytes!("my_macro.wasm"); //! //! #[proc_macro] //! pub fn (input: TokenStream) -> TokenStream { //! watt::proc_macro("my_macro", input, WASM) //! } //! # }; //! ``` //! //! Finally, copy the compiled Wasm binary from //! target/wasm32-unknown-unknown/release/my_macro.wasm under your //! implementation crate, to the src directory of your shim crate, and it's //! ready to publish! //! //! <br> //! //! # Remaining work //! //! - **Performance.**&emsp;Watt compiles pretty fast, but so far I have not put //! any effort toward optimizing the runtime. That means macro expansion can //! potentially take longer than with a natively compiled proc macro. //! //! Note that the performance overhead of the Wasm environment is partially //! offset by the fact that our proc macros are compiled to Wasm in release //! mode, so downstream `cargo build` will be running a release-mode macro //! when it would have been running debug-mode for a traditional proc macro. //! //! There is a great deal of low-hanging fruit in the runtime; as I said, it //! hasn't been optimized. In particular I am doing something silly with how //! strings are handed off one character at a time instead of in bulk in //! memory. I would love contributions from people who have a better idea of //! how this stuff is intended to work in Wasm in general. //! //! As another idea, maybe there could be some kind of `cargo install //! watt-runtime` which installs an optimized Wasm runtime locally, which the //! Watt crate can detect and hand off code to if available. That way we avoid //! running things in a debug-mode runtime altogether. //! //! - **Tooling.**&emsp;The getting started section shows there are a lot of //! steps to building a macro for Watt, and a pretty hacky patching in of //! proc-macro2. Ideally this would all be more straightforward, including //! easy tooling for doing reproducible builds of the Wasm artifact for //! confirming that it was indeed compiled from the publicly available //! sources. //! //! - **RFCs.**&emsp;The advantages of fast compile time, isolation, and //! determinism may make it worthwhile to build first-class support for Wasm //! proc macros into rustc and Cargo. The toolchain could ship its own high //! performance Wasm runtime, which is an even better outcome than Watt //! because that runtime can be heavily optimized and consumers of macros //! don't need to compile it. //! //! <br> //! //! # Acknowledgements //! //! The current underlying Wasm runtime is a fork of the [Rust-WASM] project by //! Yoann Blein and Hugo Guiroux, a simple and spec-compliant WebAssembly //! interpreter. //! //! [Rust-WASM]: https://github.com/yblein/rust-wasm extern crate proc_macro; #[path = "../runtime/src/lib.rs"] mod watt; mod data; mod debug; mod exec; mod import; mod sym; use crate::watt::*; use proc_macro::TokenStream; /// A #\[proc_macro\] implemented in wasm! /// /// # Canonical macro implementation: /// /// ``` /// # const IGNORE: &str = stringify! { /// use proc_macro2::TokenStream; /// /// #[no_mangle] /// pub extern "C" fn my_macro(input: TokenStream) -> TokenStream { /// proc_macro2::set_wasm_panic_hook(); /// /// ... /// } /// # }; /// ``` /// /// # Canonical entry point: /// /// ``` /// # const IGNORE: &str = stringify! { /// extern crate proc_macro; /// /// use proc_macro::TokenStream; /// /// static WASM: &[u8] = include_bytes!("my_macro.wasm"); /// /// #[proc_macro] /// pub fn my_macro(input: TokenStream) -> TokenStream { /// watt::proc_macro("my_macro", input, WASM) /// } /// # }; /// ``` pub fn proc_macro(fun: &str, input: TokenStream, wasm: &[u8]) -> TokenStream { exec::proc_macro(fun, vec![input], wasm) } /// A #\[proc_macro_derive\] implemented in wasm! /// /// # Canonical macro implementation: /// /// ``` /// # const IGNORE: &str = stringify! { /// use proc_macro2::TokenStream; /// /// #[no_mangle] /// pub extern "C" fn my_macro(input: TokenStream) -> TokenStream { /// proc_macro2::set_wasm_panic_hook(); /// /// ... /// } /// # }; /// ``` /// /// # Canonical entry point: /// /// ``` /// # const IGNORE: &str = stringify! { /// extern crate proc_macro; /// /// use proc_macro::TokenStream; /// /// static WASM: &[u8] = include_bytes!("my_macro.wasm"); /// /// #[proc_macro_derive(MyDerive)] /// pub fn my_macro(input: TokenStream) -> TokenStream { /// watt::proc_macro_derive("my_macro", input, WASM) /// } /// # }; /// ``` pub fn proc_macro_derive(fun: &str, input: TokenStream, wasm: &[u8]) -> TokenStream { exec::proc_macro(fun, vec![input], wasm) } /// A #\[proc_macro_attribute\] implemented in wasm! /// /// # Canonical macro implementation: /// /// ``` /// # const IGNORE: &str = stringify! { /// use proc_macro2::TokenStream; /// /// #[no_mangle] /// pub extern "C" fn my_macro(args: TokenStream, input: TokenStream) -> TokenStream { /// proc_macro2::set_wasm_panic_hook(); /// /// ... /// } /// # }; /// ``` /// /// # Canonical entry point: /// /// ``` /// # const IGNORE: &str = stringify! { /// extern crate proc_macro; /// /// use proc_macro::TokenStream; /// /// static WASM: &[u8] = include_bytes!("my_macro.wasm"); /// /// #[proc_macro_attribute] /// pub fn my_macro(args: TokenStream, input: TokenStream) -> TokenStream { /// watt::proc_macro_attribute("my_macro", args, input, WASM) /// } /// # }; /// ``` pub fn
( fun: &str, args: TokenStream, input: TokenStream, wasm: &[u8], ) -> TokenStream { exec::proc_macro(fun, vec![args, input], wasm) }
proc_macro_attribute
client.py
"""Class client for atome protocol.""" import json import logging import requests import simplejson from fake_useragent import UserAgent # export const DAILY_PERIOD_TYPE = "day" WEEKLY_PERIOD_TYPE = "week" MONTHLY_PERIOD_TYPE = "month" YEARLY_PERIOD_TYPE = "year" # internal const COOKIE_NAME = "PHPSESSID" API_BASE_URI = "https://esoftlink.esoftthings.com" API_ENDPOINT_LOGIN = "/api/user/login.json" API_ENDPOINT_LIVE = "/measure/live.json" API_ENDPOINT_CONSUMPTION = "/consumption.json" LOGIN_URL = API_BASE_URI + API_ENDPOINT_LOGIN DEFAULT_TIMEOUT = 10 MAX_RETRIES = 3 _LOGGER = logging.getLogger(__name__) class PyAtomeError(Exception): """Exception class.""" pass class AtomeClient(object): """The client class.""" def __init__( self, username, password, atome_linky_number=1, session=None, timeout=None ): """Initialize the client object.""" self.username = username self.password = password self._user_id = None self._user_reference = None self._session = session self._data = {} self._timeout = timeout # internal array start from 0 and not 1. Shift by 1. self._atome_linky_number = int(atome_linky_number) - 1 def login(self): """Set http session.""" if self._session is None: self._session = requests.session() # adding fake user-agent header self._session.headers.update({"User-agent": str(UserAgent().random)}) return self._login() def _login(self): """Login to Atome's API.""" error_flag = False payload = {"email": self.username, "plainPassword": self.password} try: req = self._session.post( LOGIN_URL, json=payload, headers={"content-type": "application/json"}, timeout=self._timeout, ) except OSError: _LOGGER.debug("Can not login to API") error_flag = True if error_flag: return None try: response_json = req.json() user_id = str(response_json["id"]) user_reference = response_json["subscriptions"][self._atome_linky_number][ "reference" ]
self._user_id = user_id self._user_reference = user_reference except ( KeyError, OSError, json.decoder.JSONDecodeError, simplejson.errors.JSONDecodeError, ) as e: _LOGGER.debug( "Impossible to decode response: \nResponse was: [%s] %s", str(e), str(req.status_code), str(req.text), ) error_flag = True if error_flag: return None return response_json def get_user_reference(self): """Get user reference respect to linky number.""" return self._user_reference def _get_info_from_server(self, url, max_retries=0): error_flag = False if max_retries > MAX_RETRIES: _LOGGER.debug("Can't gather proper data. Max retries exceeded.") error_flag = True return None try: req = self._session.get(url, timeout=self._timeout) except OSError as e: _LOGGER.debug("Could not access Atome's API: " + str(e)) error_flag = True if error_flag: return None if req.status_code == 403: # session is wrong, need to relogin self.login() logging.info("Got error %s, relogging (max retries: %s)", str(req.status_code), str(max_retries)) return self._get_info_from_server(url, max_retries + 1) if req.text == "": _LOGGER.debug("No data") error_flag = True return None try: json_output = req.json() except ( OSError, json.decoder.JSONDecodeError, simplejson.errors.JSONDecodeError, ) as e: _LOGGER.debug( "Impossible to decode response: " + str(e) + "\nResponse was: " + str(req.text) ) error_flag = True if error_flag: return None return json_output def get_live(self): """Get current data.""" live_url = ( API_BASE_URI + "/api/subscription/" + self._user_id + "/" + self._user_reference + API_ENDPOINT_LIVE ) return self._get_info_from_server(live_url) def get_consumption(self, period): """Get current data.""" if period not in [ DAILY_PERIOD_TYPE, WEEKLY_PERIOD_TYPE, MONTHLY_PERIOD_TYPE, YEARLY_PERIOD_TYPE, ]: raise ValueError( "Period %s out of range. Shall be either 'day', 'week', 'month' or 'year'.", str(period), ) consumption_url = ( API_BASE_URI + "/api/subscription/" + self._user_id + "/" + self._user_reference + API_ENDPOINT_CONSUMPTION + "?period=so" + period[:1] ) return self._get_info_from_server(consumption_url) def close_session(self): """Close current session.""" self._session.close() self._session = None
issue-20343.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
struct B { b: u32 } struct C; struct D; trait T<A> {} impl<A> T<A> for () {} impl B { // test for unused code in arguments fn foo(B { b }: B) -> u32 { b } // test for unused code in return type fn bar() -> C { unsafe { ::std::mem::transmute(()) } } // test for unused code in generics fn baz<A: T<D>>() {} } pub fn main() { let b = B { b: 3 }; B::foo(b); B::bar(); B::baz::<()>(); }
// Regression test for Issue #20343. #![deny(dead_code)]
models.py
from typing import Any, Dict, Optional from django.contrib.postgres.fields import JSONField from django.core.validators import RegexValidator from django.db import models from django.utils.timezone import datetime from django.utils.translation import gettext_lazy as _ from core.fields import IntegerChoicesField # Validators def CountryCodeValidator() -> RegexValidator: return RegexValidator(r'^[a-z]{2}$') # Enums CHART_TYPE_API = ['top-free', 'top-paid'] class ChartType(models.IntegerChoices): FREE = 0, _("Top Free Apps") PAID = 1, _("Top Paid Apps") @classmethod def from_api(cls, value: str) -> 'ChartType': if value not in CHART_TYPE_API: raise ValueError(f"Unknown chart type: {value}") return cls(CHART_TYPE_API.index(value)) def to_api(self) -> str: return CHART_TYPE_API[int(self)] # Models class Application(models.Model): itunes_id = models.PositiveIntegerField(primary_key=True) @property def latest_metadata(self) -> Optional['Metadata']: metadata = Metadata.objects.filter( application=self, data__isnull=False, ).order_by('-timestamp') if not metadata.exists(): return None return metadata.first() @property def is_known(self) -> bool: metadata = self.latest_metadata if metadata is None: return False return 'attributes' in metadata.data @property def is_bundle(self) -> bool:
@property def timestamp(self) -> Optional[datetime]: metadata = self.latest_metadata if metadata is None: return None return metadata.timestamp @property def attributes(self) -> Dict[str, Any]: metadata = self.latest_metadata if metadata is None: return {} return metadata.data.get('attributes', {}) def platform_attributes(self, platform: str = 'osx') -> Dict[str, Any]: return self.attributes.get('platformAttributes', {}).get(platform, {}) @property def name(self) -> Optional[str]: return self.attributes.get('name', None) @property def bundle_identifier(self) -> Optional[str]: return self.platform_attributes().get('bundleId', None) def __str__(self) -> str: if self.name is None: return str(self.itunes_id) return self.name class Genre(models.Model): itunes_id = models.PositiveSmallIntegerField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True, default=None) parent = models.ForeignKey( 'Genre', on_delete=models.CASCADE, related_name='children', blank=True, null=True, default=None, ) def __str__(self) -> str: if self.name is None: return str(self.itunes_id) return self.name class AppStore(models.Model): country = models.CharField( max_length=2, primary_key=True, validators=[CountryCodeValidator], ) applications = models.ManyToManyField( Application, related_name='stores', through='Metadata', through_fields=('store', 'application'), ) def __str__(self) -> str: return f"{self.country}" class Metadata(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) store = models.ForeignKey(AppStore, on_delete=models.CASCADE) source = models.URLField(max_length=4096) timestamp = models.DateTimeField() data = JSONField() class Meta: unique_together = (('application', 'store', 'source', 'timestamp'),) class Chart(models.Model): genre = models.ForeignKey( Genre, on_delete=models.CASCADE, related_name='charts', ) store = models.ForeignKey( AppStore, on_delete=models.CASCADE, related_name='charts', ) chart_type = IntegerChoicesField(ChartType) timestamp = models.DateTimeField() class Meta: unique_together = (('genre', 'store', 'chart_type', 'timestamp'),) class ChartEntry(models.Model): chart = models.ForeignKey( Chart, on_delete=models.CASCADE, related_name='entries', ) application = models.ForeignKey(Application, on_delete=models.CASCADE) position = models.PositiveSmallIntegerField() class Meta: unique_together = ( ('chart', 'application'), ('chart', 'position'), ('chart', 'application', 'position'), )
metadata = self.latest_metadata if metadata is None: return False return metadata.data.get('type', None) == 'app-bundles'
models.py
from __future__ import unicode_literals import re from itertools import cycle import six import datetime import time import uuid import logging import docker import threading import dateutil.parser from boto3 import Session from moto.core import BaseBackend, BaseModel, CloudFormationModel from moto.iam import iam_backends from moto.ec2 import ec2_backends from moto.ecs import ecs_backends from moto.logs import logs_backends from .exceptions import InvalidParameterValueException, InternalFailure, ClientException from .utils import ( make_arn_for_compute_env, make_arn_for_job_queue, make_arn_for_task_def, lowercase_first_key, ) from moto.ec2.exceptions import InvalidSubnetIdError from moto.ec2.models import INSTANCE_TYPES as EC2_INSTANCE_TYPES from moto.iam.exceptions import IAMNotFoundException from moto.core import ACCOUNT_ID as DEFAULT_ACCOUNT_ID from moto.utilities.docker_utilities import DockerModel logger = logging.getLogger(__name__) COMPUTE_ENVIRONMENT_NAME_REGEX = re.compile( r"^[A-Za-z0-9][A-Za-z0-9_-]{1,126}[A-Za-z0-9]$" ) def datetime2int(date): return int(time.mktime(date.timetuple())) class ComputeEnvironment(CloudFormationModel): def __init__( self, compute_environment_name, _type, state, compute_resources, service_role, region_name, ): self.name = compute_environment_name self.env_type = _type self.state = state self.compute_resources = compute_resources self.service_role = service_role self.arn = make_arn_for_compute_env( DEFAULT_ACCOUNT_ID, compute_environment_name, region_name ) self.instances = [] self.ecs_arn = None self.ecs_name = None def add_instance(self, instance): self.instances.append(instance) def set_ecs(self, arn, name): self.ecs_arn = arn self.ecs_name = name @property def physical_resource_id(self): return self.arn @staticmethod def cloudformation_name_type(): return "ComputeEnvironmentName" @staticmethod def cloudformation_type(): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html return "AWS::Batch::ComputeEnvironment" @classmethod def create_from_cloudformation_json( cls, resource_name, cloudformation_json, region_name ): backend = batch_backends[region_name] properties = cloudformation_json["Properties"] env = backend.create_compute_environment( resource_name, properties["Type"], properties.get("State", "ENABLED"), lowercase_first_key(properties["ComputeResources"]), properties["ServiceRole"], ) arn = env[1] return backend.get_compute_environment_by_arn(arn) class JobQueue(CloudFormationModel): def __init__( self, name, priority, state, environments, env_order_json, region_name ): """ :param name: Job queue name :type name: str :param priority: Job queue priority :type priority: int :param state: Either ENABLED or DISABLED :type state: str :param environments: Compute Environments :type environments: list of ComputeEnvironment :param env_order_json: Compute Environments JSON for use when describing :type env_order_json: list of dict :param region_name: Region name :type region_name: str """ self.name = name self.priority = priority self.state = state self.environments = environments self.env_order_json = env_order_json self.arn = make_arn_for_job_queue(DEFAULT_ACCOUNT_ID, name, region_name) self.status = "VALID" self.jobs = [] def describe(self): result = { "computeEnvironmentOrder": self.env_order_json, "jobQueueArn": self.arn, "jobQueueName": self.name, "priority": self.priority, "state": self.state, "status": self.status, } return result @property def physical_resource_id(self): return self.arn @staticmethod def cloudformation_name_type(): return "JobQueueName" @staticmethod def cloudformation_type(): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html return "AWS::Batch::JobQueue" @classmethod def create_from_cloudformation_json( cls, resource_name, cloudformation_json, region_name ): backend = batch_backends[region_name] properties = cloudformation_json["Properties"] # Need to deal with difference case from cloudformation compute_resources, e.g. instanceRole vs InstanceRole # Hacky fix to normalise keys, is making me think I want to start spamming cAsEiNsEnSiTiVe dictionaries compute_envs = [ lowercase_first_key(dict_item) for dict_item in properties["ComputeEnvironmentOrder"] ] queue = backend.create_job_queue( queue_name=resource_name, priority=properties["Priority"], state=properties.get("State", "ENABLED"), compute_env_order=compute_envs, ) arn = queue[1] return backend.get_job_queue_by_arn(arn) class JobDefinition(CloudFormationModel): def __init__( self, name, parameters, _type, container_properties, region_name, revision=0, retry_strategy=0, ): self.name = name self.retries = retry_strategy self.type = _type self.revision = revision self._region = region_name self.container_properties = container_properties self.arn = None self.status = "ACTIVE" if parameters is None: parameters = {} self.parameters = parameters self._validate() self._update_arn() def
(self): self.revision += 1 self.arn = make_arn_for_task_def( DEFAULT_ACCOUNT_ID, self.name, self.revision, self._region ) def _validate(self): if self.type not in ("container",): raise ClientException('type must be one of "container"') # For future use when containers arnt the only thing in batch if self.type != "container": raise NotImplementedError() if not isinstance(self.parameters, dict): raise ClientException("parameters must be a string to string map") if "image" not in self.container_properties: raise ClientException("containerProperties must contain image") if "memory" not in self.container_properties: raise ClientException("containerProperties must contain memory") if self.container_properties["memory"] < 4: raise ClientException("container memory limit must be greater than 4") if "vcpus" not in self.container_properties: raise ClientException("containerProperties must contain vcpus") if self.container_properties["vcpus"] < 1: raise ClientException("container vcpus limit must be greater than 0") def update(self, parameters, _type, container_properties, retry_strategy): if parameters is None: parameters = self.parameters if _type is None: _type = self.type if container_properties is None: container_properties = self.container_properties if retry_strategy is None: retry_strategy = self.retries return JobDefinition( self.name, parameters, _type, container_properties, region_name=self._region, revision=self.revision, retry_strategy=retry_strategy, ) def describe(self): result = { "jobDefinitionArn": self.arn, "jobDefinitionName": self.name, "parameters": self.parameters, "revision": self.revision, "status": self.status, "type": self.type, } if self.container_properties is not None: result["containerProperties"] = self.container_properties if self.retries is not None and self.retries > 0: result["retryStrategy"] = {"attempts": self.retries} return result @property def physical_resource_id(self): return self.arn @staticmethod def cloudformation_name_type(): return "JobDefinitionName" @staticmethod def cloudformation_type(): # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html return "AWS::Batch::JobDefinition" @classmethod def create_from_cloudformation_json( cls, resource_name, cloudformation_json, region_name ): backend = batch_backends[region_name] properties = cloudformation_json["Properties"] res = backend.register_job_definition( def_name=resource_name, parameters=lowercase_first_key(properties.get("Parameters", {})), _type="container", retry_strategy=lowercase_first_key(properties["RetryStrategy"]), container_properties=lowercase_first_key(properties["ContainerProperties"]), ) arn = res[1] return backend.get_job_definition_by_arn(arn) class Job(threading.Thread, BaseModel, DockerModel): def __init__(self, name, job_def, job_queue, log_backend, container_overrides): """ Docker Job :param name: Job Name :param job_def: Job definition :type: job_def: JobDefinition :param job_queue: Job Queue :param log_backend: Log backend :type log_backend: moto.logs.models.LogsBackend """ threading.Thread.__init__(self) DockerModel.__init__(self) self.job_name = name self.job_id = str(uuid.uuid4()) self.job_definition = job_def self.container_overrides = container_overrides or {} self.job_queue = job_queue self.job_state = "SUBMITTED" # One of SUBMITTED | PENDING | RUNNABLE | STARTING | RUNNING | SUCCEEDED | FAILED self.job_queue.jobs.append(self) self.job_started_at = datetime.datetime(1970, 1, 1) self.job_stopped_at = datetime.datetime(1970, 1, 1) self.job_stopped = False self.job_stopped_reason = None self.stop = False self.daemon = True self.name = "MOTO-BATCH-" + self.job_id self._log_backend = log_backend self.log_stream_name = None def describe(self): result = { "jobDefinition": self.job_definition.arn, "jobId": self.job_id, "jobName": self.job_name, "jobQueue": self.job_queue.arn, "status": self.job_state, "dependsOn": [], } if result["status"] not in ["SUBMITTED", "PENDING", "RUNNABLE", "STARTING"]: result["startedAt"] = datetime2int(self.job_started_at) if self.job_stopped: result["stoppedAt"] = datetime2int(self.job_stopped_at) result["container"] = {} result["container"]["command"] = [ '/bin/sh -c "for a in `seq 1 10`; do echo Hello World; sleep 1; done"' ] result["container"]["privileged"] = False result["container"]["readonlyRootFilesystem"] = False result["container"]["ulimits"] = {} result["container"]["vcpus"] = 1 result["container"]["volumes"] = "" result["container"]["logStreamName"] = self.log_stream_name if self.job_stopped_reason is not None: result["statusReason"] = self.job_stopped_reason return result def _get_container_property(self, p, default): return self.container_overrides.get( p, self.job_definition.container_properties.get(p, default) ) def run(self): """ Run the container. Logic is as follows: Generate container info (eventually from task definition) Start container Loop whilst not asked to stop and the container is running. Get all logs from container between the last time I checked and now. Convert logs into cloudwatch format Put logs into cloudwatch :return: """ try: self.job_state = "PENDING" time.sleep(1) image = self.job_definition.container_properties.get( "image", "alpine:latest" ) privileged = self.job_definition.container_properties.get( "privileged", False ) cmd = self._get_container_property( "command", '/bin/sh -c "for a in `seq 1 10`; do echo Hello World; sleep 1; done"', ) environment = { e["name"]: e["value"] for e in self._get_container_property("environment", []) } volumes = { v["name"]: v["host"] for v in self._get_container_property("volumes", []) } mounts = [ docker.types.Mount( m["containerPath"], volumes[m["sourceVolume"]]["sourcePath"], type="bind", read_only=m["readOnly"], ) for m in self._get_container_property("mountPoints", []) ] name = "{0}-{1}".format(self.job_name, self.job_id) self.job_state = "RUNNABLE" # TODO setup ecs container instance time.sleep(1) self.job_state = "STARTING" log_config = docker.types.LogConfig(type=docker.types.LogConfig.types.JSON) container = self.docker_client.containers.run( image, cmd, detach=True, name=name, log_config=log_config, environment=environment, mounts=mounts, privileged=privileged, ) self.job_state = "RUNNING" self.job_started_at = datetime.datetime.now() try: # Log collection logs_stdout = [] logs_stderr = [] container.reload() # Dodgy hack, we can only check docker logs once a second, but we want to loop more # so we can stop if asked to in a quick manner, should all go away if we go async # There also be some dodgyness when sending an integer to docker logs and some # events seem to be duplicated. now = datetime.datetime.now() i = 1 while container.status == "running" and not self.stop: time.sleep(0.2) if i % 5 == 0: logs_stderr.extend( container.logs( stdout=False, stderr=True, timestamps=True, since=datetime2int(now), ) .decode() .split("\n") ) logs_stdout.extend( container.logs( stdout=True, stderr=False, timestamps=True, since=datetime2int(now), ) .decode() .split("\n") ) now = datetime.datetime.now() container.reload() i += 1 # Container should be stopped by this point... unless asked to stop if container.status == "running": container.kill() self.job_stopped_at = datetime.datetime.now() # Get final logs logs_stderr.extend( container.logs( stdout=False, stderr=True, timestamps=True, since=datetime2int(now), ) .decode() .split("\n") ) logs_stdout.extend( container.logs( stdout=True, stderr=False, timestamps=True, since=datetime2int(now), ) .decode() .split("\n") ) self.job_state = "SUCCEEDED" if not self.stop else "FAILED" # Process logs logs_stdout = [x for x in logs_stdout if len(x) > 0] logs_stderr = [x for x in logs_stderr if len(x) > 0] logs = [] for line in logs_stdout + logs_stderr: date, line = line.split(" ", 1) date = dateutil.parser.parse(date) # TODO: Replace with int(date.timestamp()) once we yeet Python2 out of the window date = int( (time.mktime(date.timetuple()) + date.microsecond / 1000000.0) ) logs.append({"timestamp": date, "message": line.strip()}) # Send to cloudwatch log_group = "/aws/batch/job" stream_name = "{0}/default/{1}".format( self.job_definition.name, self.job_id ) self.log_stream_name = stream_name self._log_backend.ensure_log_group(log_group, None) self._log_backend.create_log_stream(log_group, stream_name) self._log_backend.put_log_events(log_group, stream_name, logs, None) except Exception as err: logger.error( "Failed to run AWS Batch container {0}. Error {1}".format( self.name, err ) ) self.job_state = "FAILED" container.kill() finally: container.remove() except Exception as err: logger.error( "Failed to run AWS Batch container {0}. Error {1}".format( self.name, err ) ) self.job_state = "FAILED" self.job_stopped = True self.job_stopped_at = datetime.datetime.now() def terminate(self, reason): if not self.stop: self.stop = True self.job_stopped_reason = reason class BatchBackend(BaseBackend): def __init__(self, region_name=None): super(BatchBackend, self).__init__() self.region_name = region_name self._compute_environments = {} self._job_queues = {} self._job_definitions = {} self._jobs = {} @property def iam_backend(self): """ :return: IAM Backend :rtype: moto.iam.models.IAMBackend """ return iam_backends["global"] @property def ec2_backend(self): """ :return: EC2 Backend :rtype: moto.ec2.models.EC2Backend """ return ec2_backends[self.region_name] @property def ecs_backend(self): """ :return: ECS Backend :rtype: moto.ecs.models.EC2ContainerServiceBackend """ return ecs_backends[self.region_name] @property def logs_backend(self): """ :return: ECS Backend :rtype: moto.logs.models.LogsBackend """ return logs_backends[self.region_name] def reset(self): region_name = self.region_name for job in self._jobs.values(): if job.job_state not in ("FAILED", "SUCCEEDED"): job.stop = True # Try to join job.join(0.2) self.__dict__ = {} self.__init__(region_name) def get_compute_environment_by_arn(self, arn): return self._compute_environments.get(arn) def get_compute_environment_by_name(self, name): for comp_env in self._compute_environments.values(): if comp_env.name == name: return comp_env return None def get_compute_environment(self, identifier): """ Get compute environment by name or ARN :param identifier: Name or ARN :type identifier: str :return: Compute Environment or None :rtype: ComputeEnvironment or None """ env = self.get_compute_environment_by_arn(identifier) if env is None: env = self.get_compute_environment_by_name(identifier) return env def get_job_queue_by_arn(self, arn): return self._job_queues.get(arn) def get_job_queue_by_name(self, name): for comp_env in self._job_queues.values(): if comp_env.name == name: return comp_env return None def get_job_queue(self, identifier): """ Get job queue by name or ARN :param identifier: Name or ARN :type identifier: str :return: Job Queue or None :rtype: JobQueue or None """ env = self.get_job_queue_by_arn(identifier) if env is None: env = self.get_job_queue_by_name(identifier) return env def get_job_definition_by_arn(self, arn): return self._job_definitions.get(arn) def get_job_definition_by_name(self, name): latest_revision = -1 latest_job = None for job_def in self._job_definitions.values(): if job_def.name == name and job_def.revision > latest_revision: latest_job = job_def latest_revision = job_def.revision return latest_job def get_job_definition_by_name_revision(self, name, revision): for job_def in self._job_definitions.values(): if job_def.name == name and job_def.revision == revision: return job_def return None def get_job_definition(self, identifier): """ Get job definitions by name or ARN :param identifier: Name or ARN :type identifier: str :return: Job definition or None :rtype: JobDefinition or None """ job_def = self.get_job_definition_by_arn(identifier) if job_def is None: if ":" in identifier: job_def = self.get_job_definition_by_name_revision( *identifier.split(":", 1) ) else: job_def = self.get_job_definition_by_name(identifier) return job_def def get_job_definitions(self, identifier): """ Get job definitions by name or ARN :param identifier: Name or ARN :type identifier: str :return: Job definition or None :rtype: list of JobDefinition """ result = [] env = self.get_job_definition_by_arn(identifier) if env is not None: result.append(env) else: for value in self._job_definitions.values(): if value.name == identifier: result.append(value) return result def get_job_by_id(self, identifier): """ Get job by id :param identifier: Job ID :type identifier: str :return: Job :rtype: Job """ try: return self._jobs[identifier] except KeyError: return None def describe_compute_environments( self, environments=None, max_results=None, next_token=None ): envs = set() if environments is not None: envs = set(environments) result = [] for arn, environment in self._compute_environments.items(): # Filter shortcut if len(envs) > 0 and arn not in envs and environment.name not in envs: continue json_part = { "computeEnvironmentArn": arn, "computeEnvironmentName": environment.name, "ecsClusterArn": environment.ecs_arn, "serviceRole": environment.service_role, "state": environment.state, "type": environment.env_type, "status": "VALID", } if environment.env_type == "MANAGED": json_part["computeResources"] = environment.compute_resources result.append(json_part) return result def create_compute_environment( self, compute_environment_name, _type, state, compute_resources, service_role ): # Validate if COMPUTE_ENVIRONMENT_NAME_REGEX.match(compute_environment_name) is None: raise InvalidParameterValueException( "Compute environment name does not match ^[A-Za-z0-9][A-Za-z0-9_-]{1,126}[A-Za-z0-9]$" ) if self.get_compute_environment_by_name(compute_environment_name) is not None: raise InvalidParameterValueException( "A compute environment already exists with the name {0}".format( compute_environment_name ) ) # Look for IAM role try: self.iam_backend.get_role_by_arn(service_role) except IAMNotFoundException: raise InvalidParameterValueException( "Could not find IAM role {0}".format(service_role) ) if _type not in ("MANAGED", "UNMANAGED"): raise InvalidParameterValueException( "type {0} must be one of MANAGED | UNMANAGED".format(service_role) ) if state is not None and state not in ("ENABLED", "DISABLED"): raise InvalidParameterValueException( "state {0} must be one of ENABLED | DISABLED".format(state) ) if compute_resources is None and _type == "MANAGED": raise InvalidParameterValueException( "computeResources must be specified when creating a MANAGED environment".format( state ) ) elif compute_resources is not None: self._validate_compute_resources(compute_resources) # By here, all values except SPOT ones have been validated new_comp_env = ComputeEnvironment( compute_environment_name, _type, state, compute_resources, service_role, region_name=self.region_name, ) self._compute_environments[new_comp_env.arn] = new_comp_env # Ok by this point, everything is legit, so if its Managed then start some instances if _type == "MANAGED": cpus = int( compute_resources.get("desiredvCpus", compute_resources["minvCpus"]) ) instance_types = compute_resources["instanceTypes"] needed_instance_types = self.find_min_instances_to_meet_vcpus( instance_types, cpus ) # Create instances # Will loop over and over so we get decent subnet coverage subnet_cycle = cycle(compute_resources["subnets"]) for instance_type in needed_instance_types: reservation = self.ec2_backend.add_instances( image_id="ami-ecs-optimised", # Todo import AMIs count=1, user_data=None, security_group_names=[], instance_type=instance_type, region_name=self.region_name, subnet_id=six.next(subnet_cycle), key_name=compute_resources.get("ec2KeyPair", "AWS_OWNED"), security_group_ids=compute_resources["securityGroupIds"], ) new_comp_env.add_instance(reservation.instances[0]) # Create ECS cluster # Should be of format P2OnDemand_Batch_UUID cluster_name = "OnDemand_Batch_" + str(uuid.uuid4()) ecs_cluster = self.ecs_backend.create_cluster(cluster_name) new_comp_env.set_ecs(ecs_cluster.arn, cluster_name) return compute_environment_name, new_comp_env.arn def _validate_compute_resources(self, cr): """ Checks contents of sub dictionary for managed clusters :param cr: computeResources :type cr: dict """ for param in ( "instanceRole", "maxvCpus", "minvCpus", "instanceTypes", "securityGroupIds", "subnets", "type", ): if param not in cr: raise InvalidParameterValueException( "computeResources must contain {0}".format(param) ) for profile in self.iam_backend.get_instance_profiles(): if profile.arn == cr["instanceRole"]: break else: raise InvalidParameterValueException( "could not find instanceRole {0}".format(cr["instanceRole"]) ) if cr["maxvCpus"] < 0: raise InvalidParameterValueException("maxVCpus must be positive") if cr["minvCpus"] < 0: raise InvalidParameterValueException("minVCpus must be positive") if cr["maxvCpus"] < cr["minvCpus"]: raise InvalidParameterValueException( "maxVCpus must be greater than minvCpus" ) if len(cr["instanceTypes"]) == 0: raise InvalidParameterValueException( "At least 1 instance type must be provided" ) for instance_type in cr["instanceTypes"]: if instance_type == "optimal": pass # Optimal should pick from latest of current gen elif instance_type not in EC2_INSTANCE_TYPES: raise InvalidParameterValueException( "Instance type {0} does not exist".format(instance_type) ) for sec_id in cr["securityGroupIds"]: if self.ec2_backend.get_security_group_from_id(sec_id) is None: raise InvalidParameterValueException( "security group {0} does not exist".format(sec_id) ) if len(cr["securityGroupIds"]) == 0: raise InvalidParameterValueException( "At least 1 security group must be provided" ) for subnet_id in cr["subnets"]: try: self.ec2_backend.get_subnet(subnet_id) except InvalidSubnetIdError: raise InvalidParameterValueException( "subnet {0} does not exist".format(subnet_id) ) if len(cr["subnets"]) == 0: raise InvalidParameterValueException("At least 1 subnet must be provided") if cr["type"] not in ("EC2", "SPOT"): raise InvalidParameterValueException( "computeResources.type must be either EC2 | SPOT" ) if cr["type"] == "SPOT": raise InternalFailure("SPOT NOT SUPPORTED YET") @staticmethod def find_min_instances_to_meet_vcpus(instance_types, target): """ Finds the minimum needed instances to meed a vcpu target :param instance_types: Instance types, like ['t2.medium', 't2.small'] :type instance_types: list of str :param target: VCPU target :type target: float :return: List of instance types :rtype: list of str """ # vcpus = [ (vcpus, instance_type), (vcpus, instance_type), ... ] instance_vcpus = [] instances = [] for instance_type in instance_types: if instance_type == "optimal": instance_type = "m4.4xlarge" instance_vcpus.append( (EC2_INSTANCE_TYPES[instance_type]["vcpus"], instance_type) ) instance_vcpus = sorted(instance_vcpus, key=lambda item: item[0], reverse=True) # Loop through, # if biggest instance type smaller than target, and len(instance_types)> 1, then use biggest type # if biggest instance type bigger than target, and len(instance_types)> 1, then remove it and move on # if biggest instance type bigger than target and len(instan_types) == 1 then add instance and finish # if biggest instance type smaller than target and len(instan_types) == 1 then loop adding instances until target == 0 # ^^ boils down to keep adding last till target vcpus is negative # #Algorithm ;-) ... Could probably be done better with some quality lambdas while target > 0: current_vcpu, current_instance = instance_vcpus[0] if len(instance_vcpus) > 1: if current_vcpu <= target: target -= current_vcpu instances.append(current_instance) else: # try next biggest instance instance_vcpus.pop(0) else: # Were on the last instance target -= current_vcpu instances.append(current_instance) return instances def delete_compute_environment(self, compute_environment_name): if compute_environment_name is None: raise InvalidParameterValueException("Missing computeEnvironment parameter") compute_env = self.get_compute_environment(compute_environment_name) if compute_env is not None: # Pop ComputeEnvironment self._compute_environments.pop(compute_env.arn) # Delete ECS cluster self.ecs_backend.delete_cluster(compute_env.ecs_name) if compute_env.env_type == "MANAGED": # Delete compute environment instance_ids = [instance.id for instance in compute_env.instances] self.ec2_backend.terminate_instances(instance_ids) def update_compute_environment( self, compute_environment_name, state, compute_resources, service_role ): # Validate compute_env = self.get_compute_environment(compute_environment_name) if compute_env is None: raise ClientException("Compute environment {0} does not exist") # Look for IAM role if service_role is not None: try: role = self.iam_backend.get_role_by_arn(service_role) except IAMNotFoundException: raise InvalidParameterValueException( "Could not find IAM role {0}".format(service_role) ) compute_env.service_role = role if state is not None: if state not in ("ENABLED", "DISABLED"): raise InvalidParameterValueException( "state {0} must be one of ENABLED | DISABLED".format(state) ) compute_env.state = state if compute_resources is not None: # TODO Implement resizing of instances based on changing vCpus # compute_resources CAN contain desiredvCpus, maxvCpus, minvCpus, and can contain none of them. pass return compute_env.name, compute_env.arn def create_job_queue(self, queue_name, priority, state, compute_env_order): """ Create a job queue :param queue_name: Queue name :type queue_name: str :param priority: Queue priority :type priority: int :param state: Queue state :type state: string :param compute_env_order: Compute environment list :type compute_env_order: list of dict :return: Tuple of Name, ARN :rtype: tuple of str """ for variable, var_name in ( (queue_name, "jobQueueName"), (priority, "priority"), (state, "state"), (compute_env_order, "computeEnvironmentOrder"), ): if variable is None: raise ClientException("{0} must be provided".format(var_name)) if state not in ("ENABLED", "DISABLED"): raise ClientException( "state {0} must be one of ENABLED | DISABLED".format(state) ) if self.get_job_queue_by_name(queue_name) is not None: raise ClientException("Job queue {0} already exists".format(queue_name)) if len(compute_env_order) == 0: raise ClientException("At least 1 compute environment must be provided") try: # orders and extracts computeEnvironment names ordered_compute_environments = [ item["computeEnvironment"] for item in sorted(compute_env_order, key=lambda x: x["order"]) ] env_objects = [] # Check each ARN exists, then make a list of compute env's for arn in ordered_compute_environments: env = self.get_compute_environment_by_arn(arn) if env is None: raise ClientException( "Compute environment {0} does not exist".format(arn) ) env_objects.append(env) except Exception: raise ClientException("computeEnvironmentOrder is malformed") # Create new Job Queue queue = JobQueue( queue_name, priority, state, env_objects, compute_env_order, self.region_name, ) self._job_queues[queue.arn] = queue return queue_name, queue.arn def describe_job_queues(self, job_queues=None, max_results=None, next_token=None): envs = set() if job_queues is not None: envs = set(job_queues) result = [] for arn, job_queue in self._job_queues.items(): # Filter shortcut if len(envs) > 0 and arn not in envs and job_queue.name not in envs: continue result.append(job_queue.describe()) return result def update_job_queue(self, queue_name, priority, state, compute_env_order): """ Update a job queue :param queue_name: Queue name :type queue_name: str :param priority: Queue priority :type priority: int :param state: Queue state :type state: string :param compute_env_order: Compute environment list :type compute_env_order: list of dict :return: Tuple of Name, ARN :rtype: tuple of str """ if queue_name is None: raise ClientException("jobQueueName must be provided") job_queue = self.get_job_queue(queue_name) if job_queue is None: raise ClientException("Job queue {0} does not exist".format(queue_name)) if state is not None: if state not in ("ENABLED", "DISABLED"): raise ClientException( "state {0} must be one of ENABLED | DISABLED".format(state) ) job_queue.state = state if compute_env_order is not None: if len(compute_env_order) == 0: raise ClientException("At least 1 compute environment must be provided") try: # orders and extracts computeEnvironment names ordered_compute_environments = [ item["computeEnvironment"] for item in sorted(compute_env_order, key=lambda x: x["order"]) ] env_objects = [] # Check each ARN exists, then make a list of compute env's for arn in ordered_compute_environments: env = self.get_compute_environment_by_arn(arn) if env is None: raise ClientException( "Compute environment {0} does not exist".format(arn) ) env_objects.append(env) except Exception: raise ClientException("computeEnvironmentOrder is malformed") job_queue.env_order_json = compute_env_order job_queue.environments = env_objects if priority is not None: job_queue.priority = priority return queue_name, job_queue.arn def delete_job_queue(self, queue_name): job_queue = self.get_job_queue(queue_name) if job_queue is not None: del self._job_queues[job_queue.arn] def register_job_definition( self, def_name, parameters, _type, retry_strategy, container_properties ): if def_name is None: raise ClientException("jobDefinitionName must be provided") job_def = self.get_job_definition_by_name(def_name) if retry_strategy is not None: try: retry_strategy = retry_strategy["attempts"] except Exception: raise ClientException("retryStrategy is malformed") if job_def is None: job_def = JobDefinition( def_name, parameters, _type, container_properties, region_name=self.region_name, retry_strategy=retry_strategy, ) else: # Make new jobdef job_def = job_def.update( parameters, _type, container_properties, retry_strategy ) self._job_definitions[job_def.arn] = job_def return def_name, job_def.arn, job_def.revision def deregister_job_definition(self, def_name): job_def = self.get_job_definition_by_arn(def_name) if job_def is None and ":" in def_name: name, revision = def_name.split(":", 1) job_def = self.get_job_definition_by_name_revision(name, revision) if job_def is not None: del self._job_definitions[job_def.arn] def describe_job_definitions( self, job_def_name=None, job_def_list=None, status=None, max_results=None, next_token=None, ): jobs = [] # As a job name can reference multiple revisions, we get a list of them if job_def_name is not None: job_def = self.get_job_definitions(job_def_name) if job_def is not None: jobs.extend(job_def) elif job_def_list is not None: for job in job_def_list: job_def = self.get_job_definitions(job) if job_def is not None: jobs.extend(job_def) else: jobs.extend(self._job_definitions.values()) # Got all the job defs were after, filter then by status if status is not None: return [job for job in jobs if job.status == status] return jobs def submit_job( self, job_name, job_def_id, job_queue, parameters=None, retries=None, depends_on=None, container_overrides=None, ): # TODO parameters, retries (which is a dict raw from request), job dependencies and container overrides are ignored for now # Look for job definition job_def = self.get_job_definition(job_def_id) if job_def is None: raise ClientException( "Job definition {0} does not exist".format(job_def_id) ) queue = self.get_job_queue(job_queue) if queue is None: raise ClientException("Job queue {0} does not exist".format(job_queue)) job = Job( job_name, job_def, queue, log_backend=self.logs_backend, container_overrides=container_overrides, ) self._jobs[job.job_id] = job # Here comes the fun job.start() return job_name, job.job_id def describe_jobs(self, jobs): job_filter = set() if jobs is not None: job_filter = set(jobs) result = [] for key, job in self._jobs.items(): if len(job_filter) > 0 and key not in job_filter: continue result.append(job.describe()) return result def list_jobs(self, job_queue, job_status=None, max_results=None, next_token=None): jobs = [] job_queue = self.get_job_queue(job_queue) if job_queue is None: raise ClientException("Job queue {0} does not exist".format(job_queue)) if job_status is not None and job_status not in ( "SUBMITTED", "PENDING", "RUNNABLE", "STARTING", "RUNNING", "SUCCEEDED", "FAILED", ): raise ClientException( "Job status is not one of SUBMITTED | PENDING | RUNNABLE | STARTING | RUNNING | SUCCEEDED | FAILED" ) for job in job_queue.jobs: if job_status is not None and job.job_state != job_status: continue jobs.append(job) return jobs def terminate_job(self, job_id, reason): if job_id is None: raise ClientException("Job ID does not exist") if reason is None: raise ClientException("Reason does not exist") job = self.get_job_by_id(job_id) if job is None: raise ClientException("Job not found") job.terminate(reason) batch_backends = {} for region in Session().get_available_regions("batch"): batch_backends[region] = BatchBackend(region) for region in Session().get_available_regions("batch", partition_name="aws-us-gov"): batch_backends[region] = BatchBackend(region) for region in Session().get_available_regions("batch", partition_name="aws-cn"): batch_backends[region] = BatchBackend(region)
_update_arn
sliceobject.rs
use libc::c_int; use crate::object::*; use crate::pyport::Py_ssize_t; #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { pub static mut PySlice_Type: PyTypeObject; pub static mut PyEllipsis_Type: PyTypeObject; } #[inline(always)] pub unsafe fn
(op: *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PySlice_Type) as c_int } #[cfg_attr(windows, link(name = "pythonXY"))] extern "C" { pub fn PySlice_New( start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject, ) -> *mut PyObject; pub fn PySlice_GetIndices( r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t, ) -> c_int; pub fn PySlice_GetIndicesEx( r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t, slicelength: *mut Py_ssize_t, ) -> c_int; #[cfg(Py_3_7)] // available since 3.5.4/3.6.1, but we don't have a cfg for the point releases pub fn PySlice_Unpack( slice: *mut PyObject, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: *mut Py_ssize_t, ) -> c_int; #[cfg(Py_3_7)] // available since 3.5.4/3.6.1, but we don't have a cfg for the point releases pub fn PySlice_AdjustIndices( length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut Py_ssize_t, step: Py_ssize_t, ) -> Py_ssize_t; }
PySlice_Check
index.js
import React, { Component } from 'react' import { graphql } from 'gatsby' import Img from 'gatsby-image' import styled from 'styled-components' import { PropTypes } from 'prop-types' import Layout from '../components/Layout' import SEO from '../components/seo' import SlidingWords from '../components/SlidingWords/SlidingWords' class
extends Component { render() { const { data: { passionImage, expressionImage, concertImage, writingImage }, } = this.props return ( <Layout> <SEO title="Home" keywords={[`oscar`, `arriaga`, `rapper`, `producer`]} /> <ImageConatiner> <BeatsImage fluid={passionImage.childImageSharp.fluid} /> <SmokeImage fluid={expressionImage.childImageSharp.fluid} /> <ConcertImage fluid={concertImage.childImageSharp.fluid} imgStyle={{ objectPosition: 'top' }} /> <WritingImage fluid={writingImage.childImageSharp.fluid} /> </ImageConatiner> <SlidingWords /> </Layout> ) } } export default IndexPage const ImageConatiner = styled.div` display: grid; height: calc(100vh - 72px); grid-template-columns: 1.25fr 0.5fr 1.25fr; grid-template-rows: 1fr 1fr; grid-template-areas: 'beats beats writing' 'smoke concert concert'; ` const BeatsImage = styled(Img)` grid-area: beats; object-fit: cover; border: 3px solid #131313; border-top: 0; ::after { box-shadow: inset 0 0 0 1000px rgba(83, 48, 235, 0.23); content: ''; display: block; height: 100%; position: absolute; top: 0; width: 100%; } ` const SmokeImage = styled(Img)` grid-area: smoke; border: 3px solid #131313; border-top: 0; ::after { box-shadow: inset 0 0 0 1000px rgba(41, 159, 255, 0.22); content: ''; display: block; height: 100%; position: absolute; top: 0; width: 100%; } ` const WritingImage = styled(Img)` grid-area: writing; border: 3px solid #131313; border-top: 0; border-left: 0; ::after { box-shadow: inset 0 0 0 1000px rgba(245, 232, 255, 0.25); content: ''; display: block; height: 100%; position: absolute; top: 0; width: 100%; } ` const ConcertImage = styled(Img)` grid-area: concert; object-position: 50% 0; border: 3px solid #131313; border-top: 0; border-left: 0; ::after { box-shadow: inset 0 0 0 1000px rgba(254, 141, 81, 0.18); content: ''; display: block; height: 100%; position: absolute; top: 0; width: 100%; } ` IndexPage.propTypes = { data: PropTypes.object, } export const query = graphql` query HomepageImageQuery { passionImage: file(relativePath: { eq: "beats.jpg" }) { ...fluidImage } expressionImage: file(relativePath: { eq: "smoke.jpg" }) { ...fluidImage } concertImage: file(relativePath: { eq: "concert.jpg" }) { ...fluidImage } writingImage: file(relativePath: { eq: "writing.jpg" }) { ...fluidImage } } `
IndexPage
main.rs
/* * Encode a struct of floats/ints of different lengths, also a string and turn it into a vector of * bytes, then send that to be deserialized- maybe actually send it over the network? * */ use std::convert::TryInto; #[derive(Debug)] struct
{ val1: f64, val2: f32, val3: i64, val4: u8, text: String, val5: u32, } impl DataStuff { fn to_bytes(&self) -> Vec<u8> { let mut data_bytes: Vec<u8> = Vec::new(); println!("{:?}", data_bytes); println!("{:?}", self.val1.to_be_bytes()); for byte in self.val1.to_be_bytes().iter() { data_bytes.push(*byte); } for byte in self.val2.to_be_bytes().iter() { data_bytes.push(*byte); } for byte in self.val3.to_be_bytes().iter() { data_bytes.push(*byte); } for byte in self.val4.to_be_bytes().iter() { data_bytes.push(*byte); } // let string_bytes = self.text.clone().into_bytes(); // let text_len: usize = string_bytes.len(); let text_len = self.text.as_bytes().len(); print!("text length {}, {}..", text_len, data_bytes.len()); for byte in text_len.to_be_bytes().iter() { data_bytes.push(*byte); } println!("{}", data_bytes.len()); for byte in self.text.as_bytes().iter() { data_bytes.push(*byte); } // for byte in string_bytes.iter() { // data_bytes.push(*byte); // } for byte in self.val5.to_be_bytes().iter() { data_bytes.push(*byte); } println!("encoded {} bytes", data_bytes.len()); data_bytes } fn from_bytes(data_bytes: Vec<u8>) -> DataStuff { println!("decoding {} bytes", data_bytes.len()); let mut ind1 = 0; let mut ind2 = 0; let mut val1: f64 = 0.0; ind2 += val1.to_be_bytes().len(); val1 = f64::from_be_bytes(data_bytes[ind1..ind2].to_vec().try_into().unwrap()); println!("val1 {}", val1); ind1 = ind2; let mut val2: f32 = 0.0; ind2 += val2.to_be_bytes().len(); val2 = f32::from_be_bytes(data_bytes[ind1..ind2].to_vec().try_into().unwrap()); println!("val2 {}", val2); ind1 = ind2; let mut val3: i64 = 0; ind2 += val3.to_be_bytes().len(); val3 = i64::from_be_bytes(data_bytes[ind1..ind2].to_vec().try_into().unwrap()); println!("val3 {}", val3); ind1 = ind2; let mut val4: u8 = 0; ind2 += val4.to_be_bytes().len(); val4 = u8::from_be_bytes(data_bytes[ind1..ind2].to_vec().try_into().unwrap()); println!("val4 {}, {}..{}", val4, ind1, ind2); ind1 = ind2; let mut text_len: usize = 0; ind2 += text_len.to_be_bytes().len(); text_len = usize::from_be_bytes(data_bytes[ind1..ind2].to_vec().try_into().unwrap()); println!("text length {}, {}..{}", text_len, ind1, ind2); ind1 = ind2; let mut text: String; ind2 += text_len; let text_vec = data_bytes[ind1..ind2].to_vec().try_into().unwrap(); text = String::from_utf8(text_vec).unwrap(); ind1 = ind2; let mut val5: u32 = 0; ind2 += val5.to_be_bytes().len(); val5 = u32::from_be_bytes(data_bytes[ind1..ind2].to_vec().try_into().unwrap()); let data = DataStuff { val1, val2, val3, val4, text, val5, }; data } } fn main() { let data0 = DataStuff{ val1: 234.24213, val2: 0.001419, val3: -9432235, val4: 201, text: String::from("test message blah blah"), val5: 24323, }; println!("{:?}", data0); let data_bytes = data0.to_bytes(); println!("{:?}", data_bytes); let data1 = DataStuff::from_bytes(data_bytes); println!("{:?}", data1); }
DataStuff
main.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package server import ( "bytes" "context" "fmt" "io/ioutil" "net" "net/http" _ "net/http/pprof" // This is essentially the main package for the orderer "os" "os/signal" "sync" "syscall" "time" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-lib-go/healthz" cb "github.com/hyperledger/fabric-protos-go/common" ab "github.com/hyperledger/fabric-protos-go/orderer" "github.com/hyperledger/fabric/bccsp" "github.com/hyperledger/fabric/bccsp/factory" "github.com/hyperledger/fabric/common/channelconfig" "github.com/hyperledger/fabric/common/crypto" "github.com/hyperledger/fabric/common/flogging" floggingmetrics "github.com/hyperledger/fabric/common/flogging/metrics" "github.com/hyperledger/fabric/common/grpclogging" "github.com/hyperledger/fabric/common/grpcmetrics" "github.com/hyperledger/fabric/common/ledger/blockledger" "github.com/hyperledger/fabric/common/metrics" "github.com/hyperledger/fabric/common/metrics/disabled" "github.com/hyperledger/fabric/core/operations" "github.com/hyperledger/fabric/internal/pkg/comm" "github.com/hyperledger/fabric/internal/pkg/identity" "github.com/hyperledger/fabric/msp" "github.com/hyperledger/fabric/orderer/common/bootstrap/file" "github.com/hyperledger/fabric/orderer/common/channelparticipation" "github.com/hyperledger/fabric/orderer/common/cluster" "github.com/hyperledger/fabric/orderer/common/localconfig" "github.com/hyperledger/fabric/orderer/common/metadata" "github.com/hyperledger/fabric/orderer/common/multichannel" "github.com/hyperledger/fabric/orderer/common/onboarding" "github.com/hyperledger/fabric/orderer/consensus" "github.com/hyperledger/fabric/orderer/consensus/etcdraft" "github.com/hyperledger/fabric/orderer/consensus/kafka" "github.com/hyperledger/fabric/orderer/consensus/solo" "github.com/hyperledger/fabric/protoutil" "go.uber.org/zap/zapcore" "google.golang.org/grpc" "gopkg.in/alecthomas/kingpin.v2" ) var logger = flogging.MustGetLogger("orderer.common.server") //command line flags var ( app = kingpin.New("orderer", "Hyperledger Fabric orderer node") _ = app.Command("start", "Start the orderer node").Default() // preserved for cli compatibility version = app.Command("version", "Show version information") clusterTypes = map[string]struct{}{"etcdraft": {}} ) // Main is the entry point of orderer process func Main() { fullCmd := kingpin.MustParse(app.Parse(os.Args[1:])) // "version" command if fullCmd == version.FullCommand() { fmt.Println(metadata.GetVersionInfo()) return } conf, err := localconfig.Load() if err != nil { logger.Error("failed to parse config: ", err) os.Exit(1) } initializeLogging() prettyPrintStruct(conf) cryptoProvider := factory.GetDefault() signer, signErr := loadLocalMSP(conf).GetDefaultSigningIdentity() if signErr != nil { logger.Panicf("Failed to get local MSP identity: %s", signErr) } opsSystem := newOperationsSystem(conf.Operations, conf.Metrics) metricsProvider := opsSystem.Provider logObserver := floggingmetrics.NewObserver(metricsProvider) flogging.SetObserver(logObserver) serverConfig := initializeServerConfig(conf, metricsProvider) grpcServer := initializeGrpcServer(conf, serverConfig) caMgr := &caManager{ appRootCAsByChain: make(map[string][][]byte), ordererRootCAsByChain: make(map[string][][]byte), clientRootCAs: serverConfig.SecOpts.ClientRootCAs, } lf, err := createLedgerFactory(conf, metricsProvider) if err != nil { logger.Panicf("Failed to create ledger factory: %v", err) } var bootstrapBlock *cb.Block if conf.General.BootstrapMethod == "file" { bootstrapBlock = file.New(conf.General.BootstrapFile).GenesisBlock() if err := onboarding.ValidateBootstrapBlock(bootstrapBlock, cryptoProvider); err != nil { logger.Panicf("Failed validating bootstrap block: %v", err) } // Are we bootstrapping with a genesis block (i.e. bootstrap block number = 0)? // If yes, generate the system channel with a genesis block. if len(lf.ChannelIDs()) == 0 && bootstrapBlock.Header.Number == 0 { logger.Info("Bootstrapping the system channel") initializeBootstrapChannel(bootstrapBlock, lf) } else if len(lf.ChannelIDs()) > 0 { logger.Info("Not bootstrapping the system channel because of existing channels") } else { logger.Infof("Not bootstrapping the system channel because the bootstrap block number is %d (>0), replication is needed", bootstrapBlock.Header.Number) } } else if conf.General.BootstrapMethod != "none" { logger.Panicf("Unknown bootstrap method: %s", conf.General.BootstrapMethod) } // select the highest numbered block among the bootstrap block and the last config block if the system channel. sysChanConfigBlock := extractSystemChannel(lf, cryptoProvider) clusterBootBlock := selectClusterBootBlock(bootstrapBlock, sysChanConfigBlock) // determine whether the orderer is of cluster type var isClusterType bool if clusterBootBlock == nil { logger.Infof("Starting without a system channel") isClusterType = true } else { sysChanID, err := protoutil.GetChannelIDFromBlock(clusterBootBlock) if err != nil { logger.Panicf("Failed getting channel ID from clusterBootBlock: %s", err) } consensusTypeName := consensusType(clusterBootBlock, cryptoProvider) logger.Infof("Starting with system channel: %s, consensus type: %s", sysChanID, consensusTypeName) _, isClusterType = clusterTypes[consensusTypeName] } // configure following artifacts properly if orderer is of cluster type var repInitiator *onboarding.ReplicationInitiator clusterServerConfig := serverConfig clusterGRPCServer := grpcServer // by default, cluster shares the same grpc server var clusterClientConfig comm.ClientConfig var clusterDialer *cluster.PredicateDialer var reuseGrpcListener bool var serversToUpdate []*comm.GRPCServer if isClusterType { logger.Infof("Setting up cluster") clusterClientConfig = initializeClusterClientConfig(conf) clusterDialer = &cluster.PredicateDialer{ Config: clusterClientConfig, } if reuseGrpcListener = reuseListener(conf); !reuseGrpcListener { clusterServerConfig, clusterGRPCServer = configureClusterListener(conf, serverConfig, ioutil.ReadFile) } // If we have a separate gRPC server for the cluster, // we need to update its TLS CA certificate pool. serversToUpdate = append(serversToUpdate, clusterGRPCServer) } // If the orderer has a system channel and is of cluster type, it may have to replicate first. if clusterBootBlock != nil && isClusterType { // Are we bootstrapping with a clusterBootBlock with number >0 ? If yes, perform replication. // Only clusters that are equipped with a recent config block (number i.e. >0) can replicate. // This will replicate all channels if the clusterBootBlock number > system-channel height (i.e. there is a gap in the ledger). repInitiator = onboarding.NewReplicationInitiator(lf, clusterBootBlock, conf, clusterClientConfig.SecOpts, signer, cryptoProvider) if conf.General.BootstrapMethod == "file" { repInitiator.ReplicateIfNeeded(clusterBootBlock) } } identityBytes, err := signer.Serialize() if err != nil { logger.Panicf("Failed serializing signing identity: %v", err) } expirationLogger := flogging.MustGetLogger("certmonitor") crypto.TrackExpiration( serverConfig.SecOpts.UseTLS, serverConfig.SecOpts.Certificate, [][]byte{clusterClientConfig.SecOpts.Certificate}, identityBytes, expirationLogger.Warnf, // This can be used to piggyback a metric event in the future time.Now(), time.AfterFunc) // if cluster is reusing client-facing server, then it is already // appended to serversToUpdate at this point. if grpcServer.MutualTLSRequired() && !reuseGrpcListener { serversToUpdate = append(serversToUpdate, grpcServer) } tlsCallback := func(bundle *channelconfig.Bundle) { logger.Debug("Executing callback to update root CAs") caMgr.updateTrustedRoots(bundle, serversToUpdate...) if isClusterType { caMgr.updateClusterDialer( clusterDialer, clusterClientConfig.SecOpts.ServerRootCAs, ) } } manager := initializeMultichannelRegistrar( clusterBootBlock, repInitiator, clusterDialer, clusterServerConfig, clusterGRPCServer, conf, signer, metricsProvider, opsSystem, lf, cryptoProvider, tlsCallback, ) opsSystem.RegisterHandler( channelparticipation.URLBaseV1, channelparticipation.NewHTTPHandler(conf.ChannelParticipation, manager), ) if err = opsSystem.Start(); err != nil { logger.Panicf("failed to start operations subsystem: %s", err) } defer opsSystem.Stop() mutualTLS := serverConfig.SecOpts.UseTLS && serverConfig.SecOpts.RequireClientCert server := NewServer( manager, metricsProvider, &conf.Debug, conf.General.Authentication.TimeWindow, mutualTLS, conf.General.Authentication.NoExpirationChecks, ) logger.Infof("Starting %s", metadata.GetVersionInfo()) handleSignals(addPlatformSignals(map[os.Signal]func(){ syscall.SIGTERM: func() { grpcServer.Stop() if clusterGRPCServer != grpcServer { clusterGRPCServer.Stop() } }, })) if !reuseGrpcListener && isClusterType { logger.Info("Starting cluster listener on", clusterGRPCServer.Address()) go clusterGRPCServer.Start() } if conf.General.Profile.Enabled { go initializeProfilingService(conf) } ab.RegisterAtomicBroadcastServer(grpcServer.Server(), server) logger.Info("Beginning to serve requests") if err := grpcServer.Start(); err != nil { logger.Fatalf("Atomic Broadcast gRPC server has terminated while serving requests due to: %v", err) } } func reuseListener(conf *localconfig.TopLevel) bool { clusterConf := conf.General.Cluster // If listen address is not configured, and the TLS certificate isn't configured, // it means we use the general listener of the node. if clusterConf.ListenPort == 0 && clusterConf.ServerCertificate == "" && clusterConf.ListenAddress == "" && clusterConf.ServerPrivateKey == "" { logger.Info("Cluster listener is not configured, defaulting to use the general listener on port", conf.General.ListenPort) if !conf.General.TLS.Enabled { logger.Panicf("TLS is required for running ordering nodes of cluster type.") } return true } // Else, one of the above is defined, so all 4 properties should be defined. if clusterConf.ListenPort == 0 || clusterConf.ServerCertificate == "" || clusterConf.ListenAddress == "" || clusterConf.ServerPrivateKey == "" { logger.Panic("Options: General.Cluster.ListenPort, General.Cluster.ListenAddress, General.Cluster.ServerCertificate," + " General.Cluster.ServerPrivateKey, should be defined altogether.") } return false } // Extract system channel last config block func extractSysChanLastConfig(lf blockledger.Factory, bootstrapBlock *cb.Block) *cb.Block { // Are we bootstrapping? channelCount := len(lf.ChannelIDs()) if channelCount == 0 { logger.Info("Bootstrapping because no existing channels") return nil } logger.Infof("Not bootstrapping because of %d existing channels", channelCount) systemChannelName, err := protoutil.GetChannelIDFromBlock(bootstrapBlock) if err != nil { logger.Panicf("Failed extracting system channel name from bootstrap block: %v", err) } systemChannelLedger, err := lf.GetOrCreate(systemChannelName) if err != nil { logger.Panicf("Failed getting system channel ledger: %v", err) } height := systemChannelLedger.Height() lastConfigBlock := multichannel.ConfigBlock(systemChannelLedger) logger.Infof("System channel: name=%s, height=%d, last config block number=%d", systemChannelName, height, lastConfigBlock.Header.Number) return lastConfigBlock } // extractSystemChannel loops through all channels, and return the last // config block for the system channel. Returns nil if no system channel // was found. func extractSystemChannel(lf blockledger.Factory, bccsp bccsp.BCCSP) *cb.Block { for _, cID := range lf.ChannelIDs() { channelLedger, err := lf.GetOrCreate(cID) if err != nil { logger.Panicf("Failed getting channel %v's ledger: %v", cID, err) } channelConfigBlock := multichannel.ConfigBlock(channelLedger) err = onboarding.ValidateBootstrapBlock(channelConfigBlock, bccsp) if err == nil { return channelConfigBlock } } return nil } // Select cluster boot block func selectClusterBootBlock(bootstrapBlock, sysChanLastConfig *cb.Block) *cb.Block { if sysChanLastConfig == nil { logger.Debug("Selected bootstrap block, because system channel last config block is nil") return bootstrapBlock } if bootstrapBlock == nil { logger.Debug("Selected system channel last config block, because bootstrap block is nil") return sysChanLastConfig } if sysChanLastConfig.Header.Number > bootstrapBlock.Header.Number { logger.Infof("Cluster boot block is system channel last config block; Blocks Header.Number system-channel=%d, bootstrap=%d", sysChanLastConfig.Header.Number, bootstrapBlock.Header.Number) return sysChanLastConfig } logger.Infof("Cluster boot block is bootstrap (genesis) block; Blocks Header.Number system-channel=%d, bootstrap=%d", sysChanLastConfig.Header.Number, bootstrapBlock.Header.Number) return bootstrapBlock } func initializeLogging() { loggingSpec := os.Getenv("FABRIC_LOGGING_SPEC") loggingFormat := os.Getenv("FABRIC_LOGGING_FORMAT") flogging.Init(flogging.Config{ Format: loggingFormat, Writer: os.Stderr, LogSpec: loggingSpec, }) } // Start the profiling service if enabled. func initializeProfilingService(conf *localconfig.TopLevel) { logger.Info("Starting Go pprof profiling service on:", conf.General.Profile.Address) // The ListenAndServe() call does not return unless an error occurs. logger.Panic("Go pprof service failed:", http.ListenAndServe(conf.General.Profile.Address, nil)) } func handleSignals(handlers map[os.Signal]func()) { var signals []os.Signal for sig := range handlers { signals = append(signals, sig) } signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, signals...) go func() { for sig := range signalChan { logger.Infof("Received signal: %d (%s)", sig, sig) handlers[sig]() } }() } type loadPEMFunc func(string) ([]byte, error) // configureClusterListener returns a new ServerConfig and a new gRPC server (with its own TLS listener). func configureClusterListener(conf *localconfig.TopLevel, generalConf comm.ServerConfig, loadPEM loadPEMFunc) (comm.ServerConfig, *comm.GRPCServer) { clusterConf := conf.General.Cluster cert, err := loadPEM(clusterConf.ServerCertificate) if err != nil { logger.Panicf("Failed to load cluster server certificate from '%s' (%s)", clusterConf.ServerCertificate, err) } key, err := loadPEM(clusterConf.ServerPrivateKey) if err != nil { logger.Panicf("Failed to load cluster server key from '%s' (%s)", clusterConf.ServerPrivateKey, err) } port := fmt.Sprintf("%d", clusterConf.ListenPort) bindAddr := net.JoinHostPort(clusterConf.ListenAddress, port) var clientRootCAs [][]byte for _, serverRoot := range conf.General.Cluster.RootCAs { rootCACert, err := loadPEM(serverRoot) if err != nil { logger.Panicf("Failed to load CA cert file '%s' (%s)", serverRoot, err) } clientRootCAs = append(clientRootCAs, rootCACert) } serverConf := comm.ServerConfig{ StreamInterceptors: generalConf.StreamInterceptors, UnaryInterceptors: generalConf.UnaryInterceptors, ConnectionTimeout: generalConf.ConnectionTimeout, ServerStatsHandler: generalConf.ServerStatsHandler, Logger: generalConf.Logger, KaOpts: generalConf.KaOpts, SecOpts: comm.SecureOptions{ TimeShift: conf.General.Cluster.TLSHandshakeTimeShift, CipherSuites: comm.DefaultTLSCipherSuites, ClientRootCAs: clientRootCAs, RequireClientCert: true, Certificate: cert, UseTLS: true, Key: key, }, } srv, err := comm.NewGRPCServer(bindAddr, serverConf) if err != nil { logger.Panicf("Failed creating gRPC server on %s:%d due to %v", clusterConf.ListenAddress, clusterConf.ListenPort, err) } return serverConf, srv } func initializeClusterClientConfig(conf *localconfig.TopLevel) comm.ClientConfig { cc := comm.ClientConfig{ AsyncConnect: true, KaOpts: comm.DefaultKeepaliveOptions, Timeout: conf.General.Cluster.DialTimeout, SecOpts: comm.SecureOptions{}, } if conf.General.Cluster.ClientCertificate == "" { return cc } certFile := conf.General.Cluster.ClientCertificate certBytes, err := ioutil.ReadFile(certFile) if err != nil { logger.Fatalf("Failed to load client TLS certificate file '%s' (%s)", certFile, err) } keyFile := conf.General.Cluster.ClientPrivateKey keyBytes, err := ioutil.ReadFile(keyFile) if err != nil { logger.Fatalf("Failed to load client TLS key file '%s' (%s)", keyFile, err) } var serverRootCAs [][]byte for _, serverRoot := range conf.General.Cluster.RootCAs { rootCACert, err := ioutil.ReadFile(serverRoot) if err != nil { logger.Fatalf("Failed to load ServerRootCAs file '%s' (%s)", serverRoot, err) } serverRootCAs = append(serverRootCAs, rootCACert) } cc.SecOpts = comm.SecureOptions{ TimeShift: conf.General.Cluster.TLSHandshakeTimeShift, RequireClientCert: true, CipherSuites: comm.DefaultTLSCipherSuites, ServerRootCAs: serverRootCAs, Certificate: certBytes, Key: keyBytes, UseTLS: true, } return cc } func initializeServerConfig(conf *localconfig.TopLevel, metricsProvider metrics.Provider) comm.ServerConfig { // secure server config secureOpts := comm.SecureOptions{ UseTLS: conf.General.TLS.Enabled, RequireClientCert: conf.General.TLS.ClientAuthRequired, } // check to see if TLS is enabled if secureOpts.UseTLS { msg := "TLS" // load crypto material from files serverCertificate, err := ioutil.ReadFile(conf.General.TLS.Certificate) if err != nil { logger.Fatalf("Failed to load server Certificate file '%s' (%s)", conf.General.TLS.Certificate, err) } serverKey, err := ioutil.ReadFile(conf.General.TLS.PrivateKey) if err != nil { logger.Fatalf("Failed to load PrivateKey file '%s' (%s)", conf.General.TLS.PrivateKey, err) } var serverRootCAs, clientRootCAs [][]byte for _, serverRoot := range conf.General.TLS.RootCAs { root, err := ioutil.ReadFile(serverRoot) if err != nil { logger.Fatalf("Failed to load ServerRootCAs file '%s' (%s)", err, serverRoot) } serverRootCAs = append(serverRootCAs, root) } if secureOpts.RequireClientCert { for _, clientRoot := range conf.General.TLS.ClientRootCAs { root, err := ioutil.ReadFile(clientRoot) if err != nil { logger.Fatalf("Failed to load ClientRootCAs file '%s' (%s)", err, clientRoot) } clientRootCAs = append(clientRootCAs, root) } msg = "mutual TLS" } secureOpts.Key = serverKey secureOpts.Certificate = serverCertificate secureOpts.ServerRootCAs = serverRootCAs secureOpts.ClientRootCAs = clientRootCAs logger.Infof("Starting orderer with %s enabled", msg) } kaOpts := comm.DefaultKeepaliveOptions // keepalive settings // ServerMinInterval must be greater than 0 if conf.General.Keepalive.ServerMinInterval > time.Duration(0) { kaOpts.ServerMinInterval = conf.General.Keepalive.ServerMinInterval } kaOpts.ServerInterval = conf.General.Keepalive.ServerInterval kaOpts.ServerTimeout = conf.General.Keepalive.ServerTimeout commLogger := flogging.MustGetLogger("core.comm").With("server", "Orderer") if metricsProvider == nil { metricsProvider = &disabled.Provider{} } return comm.ServerConfig{ SecOpts: secureOpts, KaOpts: kaOpts, Logger: commLogger, ServerStatsHandler: comm.NewServerStatsHandler(metricsProvider), ConnectionTimeout: conf.General.ConnectionTimeout, StreamInterceptors: []grpc.StreamServerInterceptor{ grpcmetrics.StreamServerInterceptor(grpcmetrics.NewStreamMetrics(metricsProvider)), grpclogging.StreamServerInterceptor(flogging.MustGetLogger("comm.grpc.server").Zap()), }, UnaryInterceptors: []grpc.UnaryServerInterceptor{ grpcmetrics.UnaryServerInterceptor(grpcmetrics.NewUnaryMetrics(metricsProvider)), grpclogging.UnaryServerInterceptor( flogging.MustGetLogger("comm.grpc.server").Zap(), grpclogging.WithLeveler(grpclogging.LevelerFunc(grpcLeveler)), ), }, } } func grpcLeveler(ctx context.Context, fullMethod string) zapcore.Level { switch fullMethod { case "/orderer.Cluster/Step": return flogging.DisabledLevel default: return zapcore.InfoLevel } } func extractBootstrapBlock(conf *localconfig.TopLevel) *cb.Block { var bootstrapBlock *cb.Block // Select the bootstrapping mechanism switch conf.General.BootstrapMethod { case "file": // For now, "file" is the only supported genesis method bootstrapBlock = file.New(conf.General.BootstrapFile).GenesisBlock() case "none": // simply honor the configuration value return nil default: logger.Panic("Unknown genesis method:", conf.General.BootstrapMethod) } return bootstrapBlock } func initializeBootstrapChannel(genesisBlock *cb.Block, lf blockledger.Factory) { channelID, err := protoutil.GetChannelIDFromBlock(genesisBlock) if err != nil { logger.Fatal("Failed to parse channel ID from genesis block:", err) } gl, err := lf.GetOrCreate(channelID) if err != nil { logger.Fatal("Failed to create the system channel:", err) } if err := gl.Append(genesisBlock); err != nil { logger.Fatal("Could not write genesis block to ledger:", err) } } func isClusterType(genesisBlock *cb.Block, bccsp bccsp.BCCSP) bool { _, exists := clusterTypes[consensusType(genesisBlock, bccsp)] return exists } func consensusType(genesisBlock *cb.Block, bccsp bccsp.BCCSP) string { if genesisBlock == nil || genesisBlock.Data == nil || len(genesisBlock.Data.Data) == 0 { logger.Fatalf("Empty genesis block") } env := &cb.Envelope{} if err := proto.Unmarshal(genesisBlock.Data.Data[0], env); err != nil { logger.Fatalf("Failed to unmarshal the genesis block's envelope: %v", err) } bundle, err := channelconfig.NewBundleFromEnvelope(env, bccsp) if err != nil { logger.Fatalf("Failed creating bundle from the genesis block: %v", err) } ordConf, exists := bundle.OrdererConfig() if !exists { logger.Fatalf("Orderer config doesn't exist in bundle derived from genesis block") } return ordConf.ConsensusType() } func initializeGrpcServer(conf *localconfig.TopLevel, serverConfig comm.ServerConfig) *comm.GRPCServer { lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", conf.General.ListenAddress, conf.General.ListenPort)) if err != nil { logger.Fatal("Failed to listen:", err) } // Create GRPC server - return if an error occurs grpcServer, err := comm.NewGRPCServerFromListener(lis, serverConfig) if err != nil { logger.Fatal("Failed to return new GRPC server:", err) } return grpcServer } func
(conf *localconfig.TopLevel) msp.MSP { // MUST call GetLocalMspConfig first, so that default BCCSP is properly // initialized prior to LoadByType. mspConfig, err := msp.GetLocalMspConfig(conf.General.LocalMSPDir, conf.General.BCCSP, conf.General.LocalMSPID) if err != nil { logger.Panicf("Failed to get local msp config: %v", err) } typ := msp.ProviderTypeToString(msp.FABRIC) opts, found := msp.Options[typ] if !found { logger.Panicf("MSP option for type %s is not found", typ) } localmsp, err := msp.New(opts, factory.GetDefault()) if err != nil { logger.Panicf("Failed to load local MSP: %v", err) } if err = localmsp.Setup(mspConfig); err != nil { logger.Panicf("Failed to setup local msp with config: %v", err) } return localmsp } //go:generate counterfeiter -o mocks/health_checker.go -fake-name HealthChecker . healthChecker // HealthChecker defines the contract for health checker type healthChecker interface { RegisterChecker(component string, checker healthz.HealthChecker) error } func initializeMultichannelRegistrar( bootstrapBlock *cb.Block, repInitiator *onboarding.ReplicationInitiator, clusterDialer *cluster.PredicateDialer, srvConf comm.ServerConfig, srv *comm.GRPCServer, conf *localconfig.TopLevel, signer identity.SignerSerializer, metricsProvider metrics.Provider, healthChecker healthChecker, lf blockledger.Factory, bccsp bccsp.BCCSP, callbacks ...channelconfig.BundleActor, ) *multichannel.Registrar { registrar := multichannel.NewRegistrar(*conf, lf, signer, metricsProvider, bccsp, callbacks...) consenters := map[string]consensus.Consenter{} var icr etcdraft.InactiveChainRegistry if conf.General.BootstrapMethod == "file" || conf.General.BootstrapMethod == "none" { if bootstrapBlock != nil && isClusterType(bootstrapBlock, bccsp) { // with a system channel etcdConsenter := initializeEtcdraftConsenter(consenters, conf, lf, clusterDialer, bootstrapBlock, repInitiator, srvConf, srv, registrar, metricsProvider, bccsp) icr = etcdConsenter.InactiveChainRegistry } else if bootstrapBlock == nil { // without a system channel: assume cluster type, InactiveChainRegistry == nil, no go-routine. consenters["etcdraft"] = etcdraft.New(clusterDialer, conf, srvConf, srv, registrar, nil, metricsProvider, bccsp) } } consenters["solo"] = solo.New() var kafkaMetrics *kafka.Metrics consenters["kafka"], kafkaMetrics = kafka.New(conf.Kafka, metricsProvider, healthChecker, icr, registrar.CreateChain) // Note, we pass a 'nil' channel here, we could pass a channel that // closes if we wished to cleanup this routine on exit. go kafkaMetrics.PollGoMetricsUntilStop(time.Minute, nil) registrar.Initialize(consenters) return registrar } func initializeEtcdraftConsenter( consenters map[string]consensus.Consenter, conf *localconfig.TopLevel, lf blockledger.Factory, clusterDialer *cluster.PredicateDialer, bootstrapBlock *cb.Block, ri *onboarding.ReplicationInitiator, srvConf comm.ServerConfig, srv *comm.GRPCServer, registrar *multichannel.Registrar, metricsProvider metrics.Provider, bccsp bccsp.BCCSP, ) *etcdraft.Consenter { systemChannelName, err := protoutil.GetChannelIDFromBlock(bootstrapBlock) if err != nil { logger.Panicf("Failed extracting system channel name from bootstrap block: %v", err) } systemLedger, err := lf.GetOrCreate(systemChannelName) if err != nil { logger.Panicf("Failed obtaining system channel (%s) ledger: %v", systemChannelName, err) } getConfigBlock := func() *cb.Block { return multichannel.ConfigBlock(systemLedger) } icr := onboarding.NewInactiveChainReplicator(ri, getConfigBlock, ri.RegisterChain, conf.General.Cluster.ReplicationBackgroundRefreshInterval) // Use the inactiveChainReplicator as a channel lister, since it has knowledge // of all inactive chains. // This is to prevent us pulling the entire system chain when attempting to enumerate // the channels in the system. ri.ChannelLister = icr go icr.Run() raftConsenter := etcdraft.New(clusterDialer, conf, srvConf, srv, registrar, icr, metricsProvider, bccsp) consenters["etcdraft"] = raftConsenter return raftConsenter } func newOperationsSystem(ops localconfig.Operations, metrics localconfig.Metrics) *operations.System { return operations.NewSystem(operations.Options{ Logger: flogging.MustGetLogger("orderer.operations"), ListenAddress: ops.ListenAddress, Metrics: operations.MetricsOptions{ Provider: metrics.Provider, Statsd: &operations.Statsd{ Network: metrics.Statsd.Network, Address: metrics.Statsd.Address, WriteInterval: metrics.Statsd.WriteInterval, Prefix: metrics.Statsd.Prefix, }, }, TLS: operations.TLS{ Enabled: ops.TLS.Enabled, CertFile: ops.TLS.Certificate, KeyFile: ops.TLS.PrivateKey, ClientCertRequired: ops.TLS.ClientAuthRequired, ClientCACertFiles: ops.TLS.ClientRootCAs, }, Version: metadata.Version, }) } // caMgr manages certificate authorities scoped by channel type caManager struct { sync.Mutex appRootCAsByChain map[string][][]byte ordererRootCAsByChain map[string][][]byte clientRootCAs [][]byte } func (mgr *caManager) updateTrustedRoots( cm channelconfig.Resources, servers ...*comm.GRPCServer, ) { mgr.Lock() defer mgr.Unlock() appRootCAs := [][]byte{} ordererRootCAs := [][]byte{} appOrgMSPs := make(map[string]struct{}) ordOrgMSPs := make(map[string]struct{}) if ac, ok := cm.ApplicationConfig(); ok { //loop through app orgs and build map of MSPIDs for _, appOrg := range ac.Organizations() { appOrgMSPs[appOrg.MSPID()] = struct{}{} } } if ac, ok := cm.OrdererConfig(); ok { //loop through orderer orgs and build map of MSPIDs for _, ordOrg := range ac.Organizations() { ordOrgMSPs[ordOrg.MSPID()] = struct{}{} } } if cc, ok := cm.ConsortiumsConfig(); ok { for _, consortium := range cc.Consortiums() { //loop through consortium orgs and build map of MSPIDs for _, consortiumOrg := range consortium.Organizations() { appOrgMSPs[consortiumOrg.MSPID()] = struct{}{} } } } cid := cm.ConfigtxValidator().ChannelID() logger.Debugf("updating root CAs for channel [%s]", cid) msps, err := cm.MSPManager().GetMSPs() if err != nil { logger.Errorf("Error getting root CAs for channel %s (%s)", cid, err) return } for k, v := range msps { // check to see if this is a FABRIC MSP if v.GetType() == msp.FABRIC { for _, root := range v.GetTLSRootCerts() { // check to see of this is an app org MSP if _, ok := appOrgMSPs[k]; ok { logger.Debugf("adding app root CAs for MSP [%s]", k) appRootCAs = append(appRootCAs, root) } // check to see of this is an orderer org MSP if _, ok := ordOrgMSPs[k]; ok { logger.Debugf("adding orderer root CAs for MSP [%s]", k) ordererRootCAs = append(ordererRootCAs, root) } } for _, intermediate := range v.GetTLSIntermediateCerts() { // check to see of this is an app org MSP if _, ok := appOrgMSPs[k]; ok { logger.Debugf("adding app root CAs for MSP [%s]", k) appRootCAs = append(appRootCAs, intermediate) } // check to see of this is an orderer org MSP if _, ok := ordOrgMSPs[k]; ok { logger.Debugf("adding orderer root CAs for MSP [%s]", k) ordererRootCAs = append(ordererRootCAs, intermediate) } } } } mgr.appRootCAsByChain[cid] = appRootCAs mgr.ordererRootCAsByChain[cid] = ordererRootCAs // now iterate over all roots for all app and orderer chains trustedRoots := [][]byte{} for _, roots := range mgr.appRootCAsByChain { trustedRoots = append(trustedRoots, roots...) } for _, roots := range mgr.ordererRootCAsByChain { trustedRoots = append(trustedRoots, roots...) } // also need to append statically configured root certs if len(mgr.clientRootCAs) > 0 { trustedRoots = append(trustedRoots, mgr.clientRootCAs...) } // now update the client roots for the gRPC server for _, srv := range servers { err = srv.SetClientRootCAs(trustedRoots) if err != nil { msg := "Failed to update trusted roots for orderer from latest config " + "block. This orderer may not be able to communicate " + "with members of channel %s (%s)" logger.Warningf(msg, cm.ConfigtxValidator().ChannelID(), err) } } } func (mgr *caManager) updateClusterDialer( clusterDialer *cluster.PredicateDialer, localClusterRootCAs [][]byte, ) { mgr.Lock() defer mgr.Unlock() // Iterate over all orderer root CAs for all chains and add them // to the root CAs var clusterRootCAs [][]byte for _, roots := range mgr.ordererRootCAsByChain { clusterRootCAs = append(clusterRootCAs, roots...) } // Add the local root CAs too clusterRootCAs = append(clusterRootCAs, localClusterRootCAs...) // Update the cluster config with the new root CAs clusterDialer.UpdateRootCAs(clusterRootCAs) } func prettyPrintStruct(i interface{}) { params := localconfig.Flatten(i) var buffer bytes.Buffer for i := range params { buffer.WriteString("\n\t") buffer.WriteString(params[i]) } logger.Infof("Orderer config values:%s\n", buffer.String()) }
loadLocalMSP
tls13.rs
use crate::msgs::enums::{ContentType, HandshakeType, ProtocolVersion}; use crate::msgs::enums::{AlertDescription, SignatureScheme, NamedGroup}; use crate::msgs::enums::{Compression, PSKKeyExchangeMode}; use crate::msgs::enums::KeyUpdateRequest; use crate::msgs::message::{Message, MessagePayload}; use crate::msgs::handshake::HandshakePayload; use crate::msgs::handshake::HandshakeMessagePayload; use crate::msgs::handshake::NewSessionTicketPayloadTLS13; use crate::msgs::handshake::CertificateEntry; use crate::msgs::handshake::CertificateExtension; use crate::msgs::handshake::CertificateStatus; use crate::msgs::handshake::CertificatePayloadTLS13; use crate::msgs::handshake::CertificateRequestPayloadTLS13; use crate::msgs::handshake::CertReqExtension; use crate::msgs::handshake::ClientHelloPayload; use crate::msgs::handshake::HelloRetryRequest; use crate::msgs::handshake::HelloRetryExtension; use crate::msgs::handshake::ServerHelloPayload; use crate::msgs::handshake::KeyShareEntry; use crate::msgs::handshake::SessionID; use crate::msgs::handshake::ServerExtension; use crate::msgs::handshake::Random; use crate::msgs::handshake::DigitallySignedStruct; use crate::msgs::ccs::ChangeCipherSpecPayload; use crate::msgs::base::{Payload, PayloadU8}; use crate::msgs::codec::Codec; use crate::msgs::persist; use crate::server::ServerSessionImpl; use crate::key_schedule::{ KeyScheduleNonSecret, KeyScheduleEarly, KeyScheduleHandshake, KeyScheduleTrafficWithClientFinishedPending, KeyScheduleTraffic }; use crate::cipher; use crate::verify; use crate::rand; use crate::sign; use crate::suites; #[cfg(feature = "logging")] use crate::log::{warn, trace, debug}; use crate::error::TLSError; use crate::handshake::{check_handshake_message, check_message}; #[cfg(feature = "quic")] use crate::{ quic, msgs::handshake::NewSessionTicketExtension, session::Protocol }; use crate::server::common::{HandshakeDetails, ClientCertDetails}; use crate::server::hs; use ring::constant_time; pub struct CompleteClientHelloHandling { pub handshake: HandshakeDetails, pub done_retry: bool, pub send_cert_status: bool, pub send_sct: bool, pub send_ticket: bool, } impl CompleteClientHelloHandling { fn check_binder(&self, sess: &mut ServerSessionImpl, client_hello: &Message, psk: &[u8], binder: &[u8]) -> bool { let binder_plaintext = match client_hello.payload { MessagePayload::Handshake(ref hmp) => hmp.get_encoding_for_binder_signing(), _ => unreachable!(), }; let suite = sess.common.get_suite_assert(); let suite_hash = suite.get_hash(); let handshake_hash = self.handshake.transcript.get_hash_given(suite_hash, &binder_plaintext); let key_schedule = KeyScheduleEarly::new(suite.hkdf_algorithm, &psk); let real_binder = key_schedule.resumption_psk_binder_key_and_sign_verify_data(&handshake_hash); constant_time::verify_slices_are_equal(&real_binder, binder).is_ok() } fn into_expect_retried_client_hello(self) -> hs::NextState { Box::new(hs::ExpectClientHello { handshake: self.handshake, done_retry: true, send_cert_status: self.send_cert_status, send_sct: self.send_sct, send_ticket: self.send_ticket, }) } fn into_expect_certificate(self, key_schedule: KeyScheduleTrafficWithClientFinishedPending) -> hs::NextState { Box::new(ExpectCertificate { handshake: self.handshake, key_schedule, send_ticket: self.send_ticket, }) } fn into_expect_finished(self, key_schedule: KeyScheduleTrafficWithClientFinishedPending) -> hs::NextState { Box::new(ExpectFinished { handshake: self.handshake, key_schedule, send_ticket: self.send_ticket, }) } fn emit_server_hello(&mut self, sess: &mut ServerSessionImpl, session_id: &SessionID, share: &KeyShareEntry, chosen_psk_idx: Option<usize>, resuming_psk: Option<&[u8]>) -> Result<KeyScheduleHandshake, TLSError> { let mut extensions = Vec::new(); // Do key exchange let kxr = suites::KeyExchange::start_ecdhe(share.group) .and_then(|kx| kx.complete(&share.payload.0)) .ok_or_else(|| TLSError::PeerMisbehavedError("key exchange failed".to_string()))?; let kse = KeyShareEntry::new(share.group, kxr.pubkey.as_ref()); extensions.push(ServerExtension::KeyShare(kse)); extensions.push(ServerExtension::SupportedVersions(ProtocolVersion::TLSv1_3)); if let Some(psk_idx) = chosen_psk_idx { extensions.push(ServerExtension::PresharedKey(psk_idx as u16)); } let sh = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_2, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::ServerHello, payload: HandshakePayload::ServerHello(ServerHelloPayload { legacy_version: ProtocolVersion::TLSv1_2, random: Random::from_slice(&self.handshake.randoms.server), session_id: *session_id, cipher_suite: sess.common.get_suite_assert().suite, compression_method: Compression::Null, extensions, }), }), }; hs::check_aligned_handshake(sess)?; #[cfg(feature = "quic")] let client_hello_hash = self.handshake.transcript .get_hash_given(sess.common.get_suite_assert().get_hash(), &[]); trace!("sending server hello {:?}", sh); self.handshake.transcript.add_message(&sh); sess.common.send_msg(sh, false); // Start key schedule let suite = sess.common.get_suite_assert(); let mut key_schedule = if let Some(psk) = resuming_psk { let early_key_schedule = KeyScheduleEarly::new(suite.hkdf_algorithm, psk); #[cfg(feature = "quic")] { if sess.common.protocol == Protocol::Quic { let client_early_traffic_secret = early_key_schedule .client_early_traffic_secret(&client_hello_hash, &*sess.config.key_log, &self.handshake.randoms.client); // If 0-RTT should be rejected, this will be clobbered by ExtensionProcessing // before the application can see. sess.common.quic.early_secret = Some(client_early_traffic_secret); } } early_key_schedule .into_handshake(&kxr.shared_secret) } else { KeyScheduleNonSecret::new(suite.hkdf_algorithm) .into_handshake(&kxr.shared_secret) }; let handshake_hash = self.handshake.transcript.get_current_hash(); let write_key = key_schedule .server_handshake_traffic_secret(&handshake_hash, &*sess.config.key_log, &self.handshake.randoms.client); sess.common .record_layer .set_message_encrypter(cipher::new_tls13_write(suite, &write_key)); let read_key = key_schedule .client_handshake_traffic_secret(&handshake_hash, &*sess.config.key_log, &self.handshake.randoms.client); sess.common .record_layer .set_message_decrypter(cipher::new_tls13_read(suite, &read_key)); #[cfg(feature = "quic")] { sess.common.quic.hs_secrets = Some(quic::Secrets { client: read_key, server: write_key, }); } Ok(key_schedule) } fn emit_fake_ccs(&mut self, sess: &mut ServerSessionImpl) { #[cfg(feature = "quic")] { if let Protocol::Quic = sess.common.protocol { return; } } let m = Message { typ: ContentType::ChangeCipherSpec, version: ProtocolVersion::TLSv1_2, payload: MessagePayload::ChangeCipherSpec(ChangeCipherSpecPayload {}) }; sess.common.send_msg(m, false); } fn emit_hello_retry_request(&mut self, sess: &mut ServerSessionImpl, group: NamedGroup) { let mut req = HelloRetryRequest { legacy_version: ProtocolVersion::TLSv1_2, session_id: SessionID::empty(), cipher_suite: sess.common.get_suite_assert().suite, extensions: Vec::new(), }; req.extensions.push(HelloRetryExtension::KeyShare(group)); req.extensions.push(HelloRetryExtension::SupportedVersions(ProtocolVersion::TLSv1_3)); let m = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_2, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::HelloRetryRequest, payload: HandshakePayload::HelloRetryRequest(req), }), }; trace!("Requesting retry {:?}", m); self.handshake.transcript.rollup_for_hrr(); self.handshake.transcript.add_message(&m); sess.common.send_msg(m, false); } fn emit_encrypted_extensions(&mut self, sess: &mut ServerSessionImpl, server_key: &mut sign::CertifiedKey, hello: &ClientHelloPayload, resumedata: Option<&persist::ServerSessionValue>) -> Result<(), TLSError> { let mut ep = hs::ExtensionProcessing::new(); ep.process_common(sess, Some(server_key), hello, resumedata, &self.handshake)?; self.send_cert_status = ep.send_cert_status; self.send_sct = ep.send_sct; let ee = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_3, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::EncryptedExtensions, payload: HandshakePayload::EncryptedExtensions(ep.exts), }), }; trace!("sending encrypted extensions {:?}", ee); self.handshake.transcript.add_message(&ee); sess.common.send_msg(ee, true); Ok(()) } fn emit_certificate_req_tls13(&mut self, sess: &mut ServerSessionImpl) -> bool { if !sess.config.verifier.offer_client_auth() { return false; } let mut cr = CertificateRequestPayloadTLS13 { context: PayloadU8::empty(), extensions: Vec::new(), }; let schemes = verify::supported_verify_schemes(); cr.extensions.push(CertReqExtension::SignatureAlgorithms(schemes.to_vec())); let names = sess.config.verifier.client_auth_root_subjects(); if !names.is_empty() { cr.extensions.push(CertReqExtension::AuthorityNames(names)); } let m = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_3, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::CertificateRequest, payload: HandshakePayload::CertificateRequestTLS13(cr), }), }; trace!("Sending CertificateRequest {:?}", m); self.handshake.transcript.add_message(&m); sess.common.send_msg(m, true); true } fn emit_certificate_tls13(&mut self, sess: &mut ServerSessionImpl, server_key: &mut sign::CertifiedKey) { let mut cert_entries = vec![]; for cert in server_key.take_cert() { let entry = CertificateEntry { cert, exts: Vec::new(), }; cert_entries.push(entry); } if let Some(end_entity_cert) = cert_entries.first_mut() { // Apply OCSP response to first certificate (we don't support OCSP // except for leaf certs). if self.send_cert_status { if let Some(ocsp) = server_key.take_ocsp() { let cst = CertificateStatus::new(ocsp); end_entity_cert.exts.push(CertificateExtension::CertificateStatus(cst)); } } // Likewise, SCT if self.send_sct { if let Some(sct_list) = server_key.take_sct_list() { end_entity_cert.exts.push(CertificateExtension::make_sct(sct_list)); } } } let cert_body = CertificatePayloadTLS13::new(cert_entries); let c = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_3, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::Certificate, payload: HandshakePayload::CertificateTLS13(cert_body), }), }; trace!("sending certificate {:?}", c); self.handshake.transcript.add_message(&c); sess.common.send_msg(c, true); } fn emit_certificate_verify_tls13(&mut self, sess: &mut ServerSessionImpl, server_key: &mut sign::CertifiedKey, schemes: &[SignatureScheme]) -> Result<(), TLSError> { let mut message = Vec::new(); message.resize(64, 0x20u8); message.extend_from_slice(b"TLS 1.3, server CertificateVerify\x00"); message.extend_from_slice(&self.handshake.transcript.get_current_hash()); let signing_key = &server_key.key; let signer = signing_key.choose_scheme(schemes) .ok_or_else(|| hs::incompatible(sess, "no overlapping sigschemes"))?; let scheme = signer.get_scheme(); let sig = signer.sign(&message)?; let cv = DigitallySignedStruct::new(scheme, sig); let m = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_3, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::CertificateVerify, payload: HandshakePayload::CertificateVerify(cv), }), }; trace!("sending certificate-verify {:?}", m); self.handshake.transcript.add_message(&m); sess.common.send_msg(m, true); Ok(()) } fn emit_finished_tls13(&mut self, sess: &mut ServerSessionImpl, key_schedule: KeyScheduleHandshake) -> KeyScheduleTrafficWithClientFinishedPending { let handshake_hash = self.handshake.transcript.get_current_hash(); let verify_data = key_schedule.sign_server_finish(&handshake_hash); let verify_data_payload = Payload::new(verify_data); let m = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_3, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::Finished, payload: HandshakePayload::Finished(verify_data_payload), }), }; trace!("sending finished {:?}", m); self.handshake.transcript.add_message(&m); self.handshake.hash_at_server_fin = self.handshake.transcript.get_current_hash(); sess.common.send_msg(m, true); // Now move to application data keys. Read key change is deferred until // the Finish message is received & validated. let mut key_schedule_traffic = key_schedule.into_traffic_with_client_finished_pending(); let suite = sess.common.get_suite_assert(); let write_key = key_schedule_traffic .server_application_traffic_secret(&self.handshake.hash_at_server_fin, &*sess.config.key_log, &self.handshake.randoms.client); sess.common .record_layer .set_message_encrypter(cipher::new_tls13_write(suite, &write_key)); key_schedule_traffic .exporter_master_secret(&self.handshake.hash_at_server_fin, &*sess.config.key_log, &self.handshake.randoms.client); let _read_key = key_schedule_traffic .client_application_traffic_secret(&self.handshake.hash_at_server_fin, &*sess.config.key_log, &self.handshake.randoms.client); #[cfg(feature = "quic")] { sess.common.quic.traffic_secrets = Some(quic::Secrets { client: _read_key, server: write_key, }); } key_schedule_traffic } fn attempt_tls13_ticket_decryption(&mut self, sess: &mut ServerSessionImpl, ticket: &[u8]) -> Option<persist::ServerSessionValue> { if sess.config.ticketer.enabled() { sess.config .ticketer .decrypt(ticket) .and_then(|plain| persist::ServerSessionValue::read_bytes(&plain)) } else { sess.config .session_storage .take(ticket) .and_then(|plain| persist::ServerSessionValue::read_bytes(&plain)) } } pub fn handle_client_hello(mut self, sess: &mut ServerSessionImpl, sni: Option<webpki::DNSName>, mut server_key: sign::CertifiedKey, chm: &Message) -> hs::NextStateOrError { let client_hello = extract_handshake!(chm, HandshakePayload::ClientHello).unwrap(); if client_hello.compression_methods.len() != 1 { return Err(hs::illegal_param(sess, "client offered wrong compressions")); } let groups_ext = client_hello.get_namedgroups_extension() .ok_or_else(|| hs::incompatible(sess, "client didn't describe groups"))?; let mut sigschemes_ext = client_hello.get_sigalgs_extension() .ok_or_else(|| hs::incompatible(sess, "client didn't describe sigschemes"))? .clone(); let tls13_schemes = sign::supported_sign_tls13(); sigschemes_ext.retain(|scheme| tls13_schemes.contains(scheme)); let shares_ext = client_hello.get_keyshare_extension() .ok_or_else(|| hs::incompatible(sess, "client didn't send keyshares"))?; if client_hello.has_keyshare_extension_with_duplicates() { return Err(hs::illegal_param(sess, "client sent duplicate keyshares")); } let share_groups: Vec<NamedGroup> = shares_ext.iter() .map(|share| share.group) .collect(); let supported_groups = suites::KeyExchange::supported_groups(); let chosen_group = supported_groups .iter() .filter(|group| share_groups.contains(group)) .nth(0) .cloned(); if chosen_group.is_none() { // We don't have a suitable key share. Choose a suitable group and // send a HelloRetryRequest. let retry_group_maybe = supported_groups .iter() .filter(|group| groups_ext.contains(group)) .nth(0) .cloned(); self.handshake.transcript.add_message(chm); if let Some(group) = retry_group_maybe { if self.done_retry { return Err(hs::illegal_param(sess, "did not follow retry request")); } self.emit_hello_retry_request(sess, group); self.emit_fake_ccs(sess); return Ok(self.into_expect_retried_client_hello()); } return Err(hs::incompatible(sess, "no kx group overlap with client")); } hs::save_sni(sess, sni); let chosen_group = chosen_group.unwrap(); let chosen_share = shares_ext.iter() .find(|share| share.group == chosen_group) .unwrap(); let mut chosen_psk_index = None; let mut resumedata = None; if let Some(psk_offer) = client_hello.get_psk() { if !client_hello.check_psk_ext_is_last() { return Err(hs::illegal_param(sess, "psk extension in wrong position")); } if psk_offer.binders.is_empty() { return Err(hs::decode_error(sess, "psk extension missing binder")); } if psk_offer.binders.len() != psk_offer.identities.len() { return Err(hs::illegal_param(sess, "psk extension mismatched ids/binders")); } for (i, psk_id) in psk_offer.identities.iter().enumerate() { let maybe_resume = self.attempt_tls13_ticket_decryption(sess, &psk_id.identity.0); if !hs::can_resume(sess, &self.handshake, &maybe_resume) { continue; } let resume = maybe_resume.unwrap(); if !self.check_binder(sess, chm, &resume.master_secret.0, &psk_offer.binders[i].0) { sess.common.send_fatal_alert(AlertDescription::DecryptError); return Err(TLSError::PeerMisbehavedError("client sent wrong binder".to_string())); } chosen_psk_index = Some(i); resumedata = Some(resume); break; } } if !client_hello.psk_mode_offered(PSKKeyExchangeMode::PSK_DHE_KE) { warn!("Resumption ignored, DHE_KE not offered"); self.send_ticket = false; chosen_psk_index = None; resumedata = None; } else { self.send_ticket = true; } if let Some(ref resume) = resumedata { sess.received_resumption_data = Some(resume.application_data.0.clone()); } let full_handshake = resumedata.is_none(); self.handshake.transcript.add_message(chm); let key_schedule = self.emit_server_hello(sess, &client_hello.session_id, chosen_share, chosen_psk_index, resumedata.as_ref().map(|x| &x.master_secret.0[..]))?; if !self.done_retry { self.emit_fake_ccs(sess); } self.emit_encrypted_extensions(sess, &mut server_key, client_hello, resumedata.as_ref())?; let doing_client_auth = if full_handshake { let client_auth = self.emit_certificate_req_tls13(sess); self.emit_certificate_tls13(sess, &mut server_key); self.emit_certificate_verify_tls13(sess, &mut server_key, &sigschemes_ext)?; client_auth } else { false }; hs::check_aligned_handshake(sess)?; let key_schedule_traffic = self.emit_finished_tls13(sess, key_schedule); if doing_client_auth { Ok(self.into_expect_certificate(key_schedule_traffic)) } else { Ok(self.into_expect_finished(key_schedule_traffic)) } } } pub struct ExpectCertificate { pub handshake: HandshakeDetails, pub key_schedule: KeyScheduleTrafficWithClientFinishedPending, pub send_ticket: bool, } impl ExpectCertificate { fn into_expect_finished(self) -> hs::NextState { Box::new(ExpectFinished { key_schedule: self.key_schedule, handshake: self.handshake, send_ticket: self.send_ticket, }) } fn into_expect_certificate_verify(self, cert: ClientCertDetails) -> hs::NextState { Box::new(ExpectCertificateVerify { handshake: self.handshake, key_schedule: self.key_schedule, client_cert: cert, send_ticket: self.send_ticket, }) } } impl hs::State for ExpectCertificate { fn check_message(&self, m: &Message) -> hs::CheckResult { check_handshake_message(m, &[HandshakeType::Certificate]) } fn handle(mut self: Box<Self>, sess: &mut ServerSessionImpl, m: Message) -> hs::NextStateOrError { let certp = extract_handshake!(m, HandshakePayload::CertificateTLS13).unwrap(); self.handshake.transcript.add_message(&m); // We don't send any CertificateRequest extensions, so any extensions // here are illegal. if certp.any_entry_has_extension() { return Err(TLSError::PeerMisbehavedError("client sent unsolicited cert extension" .to_string())); } let cert_chain = certp.convert(); if cert_chain.is_empty() { if !sess.config.verifier.client_auth_mandatory() { debug!("client auth requested but no certificate supplied"); self.handshake.transcript.abandon_client_auth(); return Ok(self.into_expect_finished()); } sess.common.send_fatal_alert(AlertDescription::CertificateRequired); return Err(TLSError::NoCertificatesPresented); } sess.config.get_verifier().verify_client_cert(&cert_chain) .or_else(|err| { hs::incompatible(sess, "certificate invalid"); Err(err) })?; let cert = ClientCertDetails::new(cert_chain); Ok(self.into_expect_certificate_verify(cert)) } } pub struct ExpectCertificateVerify { handshake: HandshakeDetails, key_schedule: KeyScheduleTrafficWithClientFinishedPending, client_cert: ClientCertDetails, send_ticket: bool, } impl ExpectCertificateVerify { fn into_expect_finished(self) -> hs::NextState { Box::new(ExpectFinished { key_schedule: self.key_schedule, handshake: self.handshake, send_ticket: self.send_ticket, }) } } impl hs::State for ExpectCertificateVerify { fn
(&self, m: &Message) -> hs::CheckResult { check_handshake_message(m, &[HandshakeType::CertificateVerify]) } fn handle(mut self: Box<Self>, sess: &mut ServerSessionImpl, m: Message) -> hs::NextStateOrError { let rc = { let sig = extract_handshake!(m, HandshakePayload::CertificateVerify).unwrap(); let handshake_hash = self.handshake.transcript.get_current_hash(); self.handshake.transcript.abandon_client_auth(); let certs = &self.client_cert.cert_chain; verify::verify_tls13(&certs[0], sig, &handshake_hash, b"TLS 1.3, client CertificateVerify\x00") }; if let Err(e) = rc { sess.common.send_fatal_alert(AlertDescription::AccessDenied); return Err(e); } trace!("client CertificateVerify OK"); sess.client_cert_chain = Some(self.client_cert.take_chain()); self.handshake.transcript.add_message(&m); Ok(self.into_expect_finished()) } } // --- Process client's Finished --- fn get_server_session_value(handshake: &mut HandshakeDetails, key_schedule: &KeyScheduleTraffic, sess: &ServerSessionImpl, nonce: &[u8]) -> persist::ServerSessionValue { let scs = sess.common.get_suite_assert(); let version = ProtocolVersion::TLSv1_3; let handshake_hash = handshake .transcript .get_current_hash(); let secret = key_schedule .resumption_master_secret_and_derive_ticket_psk(&handshake_hash, nonce); persist::ServerSessionValue::new( sess.get_sni(), version, scs.suite, secret, &sess.client_cert_chain, sess.alpn_protocol.clone(), sess.resumption_data.clone(), ) } pub struct ExpectFinished { pub handshake: HandshakeDetails, pub key_schedule: KeyScheduleTrafficWithClientFinishedPending, pub send_ticket: bool, } impl ExpectFinished { fn into_expect_traffic(fin: verify::FinishedMessageVerified, ks: KeyScheduleTraffic) -> hs::NextState { Box::new(ExpectTraffic { key_schedule: ks, want_write_key_update: false, _fin_verified: fin, }) } fn emit_stateless_ticket(handshake: &mut HandshakeDetails, sess: &mut ServerSessionImpl, key_schedule: &KeyScheduleTraffic) { let nonce = rand::random_vec(32); let plain = get_server_session_value(handshake, key_schedule, sess, &nonce) .get_encoding(); let maybe_ticket = sess.config .ticketer .encrypt(&plain); let ticket_lifetime = sess.config.ticketer.get_lifetime(); if maybe_ticket.is_none() { return; } let ticket = maybe_ticket.unwrap(); let age_add = rand::random_u32(); // nb, we don't do 0-RTT data, so whatever #[allow(unused_mut)] let mut payload = NewSessionTicketPayloadTLS13::new(ticket_lifetime, age_add, nonce, ticket); #[cfg(feature = "quic")] { if sess.config.max_early_data_size > 0 && sess.common.protocol == Protocol::Quic { payload.exts.push(NewSessionTicketExtension::EarlyData(sess.config.max_early_data_size)); } } let m = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_3, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::NewSessionTicket, payload: HandshakePayload::NewSessionTicketTLS13(payload), }), }; trace!("sending new ticket {:?}", m); handshake.transcript.add_message(&m); sess.common.send_msg(m, true); } fn emit_stateful_ticket(handshake: &mut HandshakeDetails, sess: &mut ServerSessionImpl, key_schedule: &KeyScheduleTraffic) { let nonce = rand::random_vec(32); let id = rand::random_vec(32); let plain = get_server_session_value(handshake, key_schedule, sess, &nonce) .get_encoding(); if sess.config.session_storage.put(id.clone(), plain) { let stateful_lifetime = 24 * 60 * 60; // this is a bit of a punt let age_add = rand::random_u32(); #[allow(unused_mut)] let mut payload = NewSessionTicketPayloadTLS13::new(stateful_lifetime, age_add, nonce, id); #[cfg(feature = "quic")] { if sess.config.max_early_data_size > 0 && sess.common.protocol == Protocol::Quic { payload.exts.push(NewSessionTicketExtension::EarlyData(sess.config.max_early_data_size)); } } let m = Message { typ: ContentType::Handshake, version: ProtocolVersion::TLSv1_3, payload: MessagePayload::Handshake(HandshakeMessagePayload { typ: HandshakeType::NewSessionTicket, payload: HandshakePayload::NewSessionTicketTLS13(payload), }), }; trace!("sending new stateful ticket {:?}", m); handshake.transcript.add_message(&m); sess.common.send_msg(m, true); } else { trace!("resumption not available; not issuing ticket"); } } } impl hs::State for ExpectFinished { fn check_message(&self, m: &Message) -> hs::CheckResult { check_handshake_message(m, &[HandshakeType::Finished]) } fn handle(mut self: Box<Self>, sess: &mut ServerSessionImpl, m: Message) -> hs::NextStateOrError { let finished = extract_handshake!(m, HandshakePayload::Finished).unwrap(); let handshake_hash = self.handshake.transcript.get_current_hash(); let expect_verify_data = self.key_schedule.sign_client_finish(&handshake_hash); let fin = constant_time::verify_slices_are_equal(&expect_verify_data, &finished.0) .map_err(|_| { sess.common.send_fatal_alert(AlertDescription::DecryptError); warn!("Finished wrong"); TLSError::DecryptError }) .map(|_| verify::FinishedMessageVerified::assertion())?; // nb. future derivations include Client Finished, but not the // main application data keying. self.handshake.transcript.add_message(&m); hs::check_aligned_handshake(sess)?; let suite = sess.common.get_suite_assert(); // Install keying to read future messages. let read_key = self.key_schedule .client_application_traffic_secret(&self.handshake.hash_at_server_fin, &*sess.config.key_log, &self.handshake.randoms.client); sess.common .record_layer .set_message_decrypter(cipher::new_tls13_read(suite, &read_key)); let key_schedule_traffic = self.key_schedule.into_traffic(); if self.send_ticket { if sess.config.ticketer.enabled() { Self::emit_stateless_ticket(&mut self.handshake, sess, &key_schedule_traffic); } else { Self::emit_stateful_ticket(&mut self.handshake, sess, &key_schedule_traffic); } } sess.common.start_traffic(); #[cfg(feature = "quic")] { if sess.common.protocol == Protocol::Quic { return Ok(Box::new(ExpectQUICTraffic { _fin_verified: fin })); } } Ok(Self::into_expect_traffic(fin, key_schedule_traffic)) } } // --- Process traffic --- pub struct ExpectTraffic { key_schedule: KeyScheduleTraffic, want_write_key_update: bool, _fin_verified: verify::FinishedMessageVerified, } impl ExpectTraffic { fn handle_traffic(&self, sess: &mut ServerSessionImpl, mut m: Message) -> Result<(), TLSError> { sess.common.take_received_plaintext(m.take_opaque_payload().unwrap()); Ok(()) } fn handle_key_update(&mut self, sess: &mut ServerSessionImpl, m: Message) -> Result<(), TLSError> { let kur = extract_handshake!(m, HandshakePayload::KeyUpdate).unwrap(); #[cfg(feature = "quic")] { if let Protocol::Quic = sess.common.protocol { sess.common.send_fatal_alert(AlertDescription::UnexpectedMessage); let msg = "KeyUpdate received in QUIC connection".to_string(); warn!("{}", msg); return Err(TLSError::PeerMisbehavedError(msg)); } } hs::check_aligned_handshake(sess)?; match kur { KeyUpdateRequest::UpdateNotRequested => {} KeyUpdateRequest::UpdateRequested => { self.want_write_key_update = true; } _ => { sess.common.send_fatal_alert(AlertDescription::IllegalParameter); return Err(TLSError::CorruptMessagePayload(ContentType::Handshake)); } } // Update our read-side keys. let new_read_key = self.key_schedule.next_client_application_traffic_secret(); let suite = sess.common.get_suite_assert(); sess.common.record_layer.set_message_decrypter(cipher::new_tls13_read(suite, &new_read_key)); Ok(()) } } impl hs::State for ExpectTraffic { fn check_message(&self, m: &Message) -> hs::CheckResult { check_message(m, &[ContentType::ApplicationData, ContentType::Handshake], &[HandshakeType::KeyUpdate]) } fn handle(mut self: Box<Self>, sess: &mut ServerSessionImpl, m: Message) -> hs::NextStateOrError { if m.is_content_type(ContentType::ApplicationData) { self.handle_traffic(sess, m)?; } else if m.is_handshake_type(HandshakeType::KeyUpdate) { self.handle_key_update(sess, m)?; } Ok(self) } fn export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) -> Result<(), TLSError> { self.key_schedule.export_keying_material(output, label, context) } fn perhaps_write_key_update(&mut self, sess: &mut ServerSessionImpl) { if self.want_write_key_update { self.want_write_key_update = false; sess.common.send_msg_encrypt(Message::build_key_update_notify()); let write_key = self.key_schedule.next_server_application_traffic_secret(); let scs = sess.common.get_suite_assert(); sess.common.record_layer.set_message_encrypter(cipher::new_tls13_write(scs, &write_key)); } } } #[cfg(feature = "quic")] pub struct ExpectQUICTraffic { _fin_verified: verify::FinishedMessageVerified, } #[cfg(feature = "quic")] impl hs::State for ExpectQUICTraffic { fn check_message(&self, m: &Message) -> hs::CheckResult { Err(TLSError::InappropriateMessage { expect_types: Vec::new(), got_type: m.typ, }) } fn handle(self: Box<Self>, _: &mut ServerSessionImpl, _: Message) -> hs::NextStateOrError { unreachable!("check_message always fails"); } }
check_message
mod.rs
/// The desired input location information. #[derive(Clone, PartialEq, ::prost::Message)] pub struct InputConfig { /// The input data format that used to store the model in Cloud Storage. #[prost(enumeration="DataFormat", tag="2")] pub data_format: i32, /// The location of the input model in cloud storage. /// Required. #[prost(oneof="input_config::Source", tags="1")] pub source: ::core::option::Option<input_config::Source>, } /// Nested message and enum types in `InputConfig`. pub mod input_config { /// The location of the input model in cloud storage. /// Required. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Source { /// The Google Cloud Storage location to read the input from. This must be a /// single file. #[prost(message, tag="1")] GcsSource(super::GcsSource), } } /// The desired output location. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OutputConfig { /// The output data format that used to store the results in Cloud Storage. #[prost(enumeration="DataFormat", tag="2")] pub data_format: i32, /// The location of the output result in cloud storage. /// Required. #[prost(oneof="output_config::Destination", tags="1")] pub destination: ::core::option::Option<output_config::Destination>, } /// Nested message and enum types in `OutputConfig`. pub mod output_config { /// The location of the output result in cloud storage. /// Required. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Destination { /// The Google Cloud Storage location to write the output to. #[prost(message, tag="1")] GcsDestination(super::GcsDestination), } } /// The Google Cloud Storage location where the input file will be read from. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GcsSource { /// Required. URI of the Google Cloud Storage location. #[prost(string, tag="1")] pub uri: ::prost::alloc::string::String, } /// The Google Cloud Storage location where the output file will be written to. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GcsDestination { /// Required. URI of the Google Cloud Storage location. #[prost(string, tag="1")] pub uri: ::prost::alloc::string::String, } /// The long running operation metadata for async model related methods. #[derive(Clone, PartialEq, ::prost::Message)] pub struct AsyncModelMetadata { /// The state of the current operation. #[prost(enumeration="async_model_metadata::State", tag="1")] pub state: i32, /// A message providing more details about the current state of the operation. /// For example, the error message if the operation is failed. #[prost(string, tag="2")] pub state_message: ::prost::alloc::string::String, /// The creation time of the operation. #[prost(message, optional, tag="3")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// The last update time of the operation. #[prost(message, optional, tag="4")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, } /// Nested message and enum types in `AsyncModelMetadata`. pub mod async_model_metadata { /// Possible states of the operation. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum State { /// The default value. This value is used if the state is omitted. Unspecified = 0, /// Request is being processed. Running = 1, /// The operation completed successfully. Succeeded = 2, /// The operation was cancelled. Cancelled = 3, /// The operation has failed. Failed = 4, } } /// Data formats for input and output files. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum DataFormat { /// Default value. Unspecified = 0, /// Input data in json format. Json = 1, /// Input data in string format. String = 2, } /// Request to be given to a tour optimization solver which defines the /// shipment model to solve as well as optimization parameters. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OptimizeToursRequest { /// Required. Target project and location to make a call. /// /// Format: `projects/{project-id}/locations/{location-id}`. /// /// If no location is specified, a region will be chosen automatically. #[prost(string, tag="1")] pub parent: ::prost::alloc::string::String, /// If this timeout is set, the server returns a response before the timeout /// period has elapsed or the server deadline for synchronous requests is /// reached, whichever is sooner. /// /// For asynchronous requests, the server will generate a solution (if /// possible) before the timeout has elapsed. #[prost(message, optional, tag="2")] pub timeout: ::core::option::Option<::prost_types::Duration>, /// Shipment model to solve. #[prost(message, optional, tag="3")] pub model: ::core::option::Option<ShipmentModel>, /// By default, the solving mode is `DEFAULT_SOLVE` (0). #[prost(enumeration="optimize_tours_request::SolvingMode", tag="4")] pub solving_mode: i32, /// Truncates the number of validation errors returned. Those errors are /// typically attached to an INVALID_ARGUMENT error payload as a BadRequest /// error detail (<https://cloud.google.com/apis/design/errors#error_details>), /// unless solving_mode=VALIDATE_ONLY: see the /// \[OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors\] /// field. /// This defaults to 100 and is capped at 10,000. #[prost(int32, optional, tag="5")] pub max_validation_errors: ::core::option::Option<i32>, /// Search mode used to solve the request. #[prost(enumeration="optimize_tours_request::SearchMode", tag="6")] pub search_mode: i32, /// Guide the optimization algorithm in finding a first solution that is /// similar to a previous solution. /// /// The model is constrained when the first solution is built. /// Any shipments not performed on a route are implicitly skipped in the first /// solution, but they may be performed in successive solutions. /// /// The solution must satisfy some basic validity assumptions: /// /// * for all routes, `vehicle_index` must be in range and not be duplicated. /// * for all visits, `shipment_index` and `visit_request_index` must be /// in range. /// * a shipment may only be referenced on one route. /// * the pickup of a pickup-delivery shipment must be performed before /// the delivery. /// * no more than one pickup alternative or delivery alternative of /// a shipment may be performed. /// * for all routes, times are increasing (i.e., `vehicle_start_time /// <= visits\[0\].start_time <= visits\[1\].start_time ... /// <= vehicle_end_time`). /// * a shipment may only be performed on a vehicle that is allowed. A /// vehicle is allowed if \[Shipment.allowed_vehicle_indices][google.cloud.optimization.v1.Shipment.allowed_vehicle_indices\] is empty or /// its `vehicle_index` is included in /// \[Shipment.allowed_vehicle_indices][google.cloud.optimization.v1.Shipment.allowed_vehicle_indices\]. /// /// If the injected solution is not feasible, a validation error is not /// necessarily returned and an error indicating infeasibility may be returned /// instead. #[prost(message, repeated, tag="7")] pub injected_first_solution_routes: ::prost::alloc::vec::Vec<ShipmentRoute>, /// Constrain the optimization algorithm to find a final solution that is /// similar to a previous solution. For example, this may be used to freeze /// portions of routes which have already been completed or which are to be /// completed but must not be modified. /// /// If the injected solution is not feasible, a validation error is not /// necessarily returned and an error indicating infeasibility may be returned /// instead. #[prost(message, optional, tag="8")] pub injected_solution_constraint: ::core::option::Option<InjectedSolutionConstraint>, /// If non-empty, the given routes will be refreshed, without modifying their /// underlying sequence of visits or travel times: only other details will be /// updated. This does not solve the model. /// /// As of 2020/11, this only populates the polylines of non-empty routes and /// requires that `populate_polylines` is true. /// /// The `route_polyline` fields of the passed-in routes may be inconsistent /// with route `transitions`. /// /// This field must not be used together with `injected_first_solution_routes` /// or `injected_solution_constraint`. /// /// `Shipment.ignore` and `Vehicle.ignore` have no effect on the behavior. /// Polylines are still populated between all visits in all non-empty routes /// regardless of whether the related shipments or vehicles are ignored. #[prost(message, repeated, tag="9")] pub refresh_details_routes: ::prost::alloc::vec::Vec<ShipmentRoute>, /// If true: /// /// * uses \[ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label\] instead of `vehicle_index` to /// match routes in an injected solution with vehicles in the request; /// reuses the mapping of original \[ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index\] to new /// \[ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index\] to update /// \[ConstraintRelaxation.vehicle_indices][google.cloud.optimization.v1.InjectedSolutionConstraint.ConstraintRelaxation.vehicle_indices\] /// if non-empty, but the mapping must be unambiguous (i.e., multiple /// `ShipmentRoute`s must not share the same original `vehicle_index`). /// * uses \[ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label\] instead of `shipment_index` /// to match visits in an injected solution with shipments in the request; /// * uses \[SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label\] instead of \[SkippedShipment.index][google.cloud.optimization.v1.SkippedShipment.index\] to /// match skipped shipments in the injected solution with request /// shipments. /// /// This interpretation applies to the `injected_first_solution_routes`, /// `injected_solution_constraint`, and `refresh_details_routes` fields. /// It can be used when shipment or vehicle indices in the request have /// changed since the solution was created, perhaps because shipments or /// vehicles have been removed from or added to the request. /// /// If true, labels in the following categories must appear at most once in /// their category: /// /// * \[Vehicle.label][google.cloud.optimization.v1.Vehicle.label\] in the request; /// * \[Shipment.label][google.cloud.optimization.v1.Shipment.label\] in the request; /// * \[ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label\] in the injected solution; /// * \[SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label\] and \[ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label\] in /// the injected solution (except pickup/delivery visit pairs, whose /// `shipment_label` must appear twice). /// /// If a `vehicle_label` in the injected solution does not correspond to a /// request vehicle, the corresponding route is removed from the solution /// along with its visits. If a `shipment_label` in the injected solution does /// not correspond to a request shipment, the corresponding visit is removed /// from the solution. If a \[SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label\] in the injected solution /// does not correspond to a request shipment, the `SkippedShipment` is removed /// from the solution. /// /// Removing route visits or entire routes from an injected solution may /// have an effect on the implied constraints, which may lead to change in /// solution, validation errors, or infeasibility. /// /// NOTE: The caller must ensure that each \[Vehicle.label][google.cloud.optimization.v1.Vehicle.label\] /// (resp. \[Shipment.label][google.cloud.optimization.v1.Shipment.label\]) uniquely identifies a vehicle (resp. shipment) /// entity used across the two relevant requests: the past request that /// produced the `OptimizeToursResponse` used in the injected solution and the /// current request that includes the injected solution. The uniqueness checks /// described above are not enough to guarantee this requirement. #[prost(bool, tag="10")] pub interpret_injected_solutions_using_labels: bool, /// Consider traffic estimation in calculating `ShipmentRoute` fields /// \[Transition.travel_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_duration\], /// \[Visit.start_time][google.cloud.optimization.v1.ShipmentRoute.Visit.start_time\], /// and `vehicle_end_time`; in setting the /// \[ShipmentRoute.has_traffic_infeasibilities][google.cloud.optimization.v1.ShipmentRoute.has_traffic_infeasibilities\] field, and in calculating the /// \[OptimizeToursResponse.total_cost][google.cloud.optimization.v1.OptimizeToursResponse.total_cost\] field. #[prost(bool, tag="11")] pub consider_road_traffic: bool, /// If true, polylines will be populated in response `ShipmentRoute`s. #[prost(bool, tag="12")] pub populate_polylines: bool, /// If true, polylines will be populated in response /// \[ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions\]. /// Note that in this case, the polylines will also be populated in the /// deprecated `travel_steps`. #[prost(bool, tag="13")] pub populate_transition_polylines: bool, /// If this is set, then the request can have a deadline /// (see <https://grpc.io/blog/deadlines>) of up to 60 minutes. /// Otherwise, the maximum deadline is only 30 minutes. /// Note that long-lived requests have a significantly larger (but still small) /// risk of interruption. #[prost(bool, tag="14")] pub allow_large_deadline_despite_interruption_risk: bool, /// If true, travel distances will be computed using geodesic distances instead /// of Google Maps distances, and travel times will be computed using geodesic /// distances with a speed defined by `geodesic_meters_per_second`. #[prost(bool, tag="15")] pub use_geodesic_distances: bool, /// When `use_geodesic_distances` is true, this field must be set and defines /// the speed applied to compute travel times. Its value must be at least 1.0 /// meters/seconds. #[prost(double, optional, tag="16")] pub geodesic_meters_per_second: ::core::option::Option<f64>, /// Label that may be used to identify this request, reported back in the /// \[OptimizeToursResponse.request_label][google.cloud.optimization.v1.OptimizeToursResponse.request_label\]. #[prost(string, tag="17")] pub label: ::prost::alloc::string::String, /// Deprecated: Use \[OptimizeToursRequest.populate_transition_polylines][\] instead. /// If true, polylines will be populated in response /// \[ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions\]. Note that in this case, the polylines will /// also be populated in the deprecated `travel_steps`. #[deprecated] #[prost(bool, tag="20")] pub populate_travel_step_polylines: bool, } /// Nested message and enum types in `OptimizeToursRequest`. pub mod optimize_tours_request { /// Defines how the solver should handle the request. In all modes but /// `VALIDATE_ONLY`, if the request is invalid, you will receive an /// `INVALID_REQUEST` error. See \[max_validation_errors][google.cloud.optimization.v1.OptimizeToursRequest.max_validation_errors\] to cap the number of /// errors returned. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum SolvingMode { /// Solve the model. DefaultSolve = 0, /// Only validates the model without solving it: populates as many /// \[OptimizeToursResponse.validation_errors][google.cloud.optimization.v1.OptimizeToursResponse.validation_errors\] /// as possible. ValidateOnly = 1, /// Only populates /// \[OptimizeToursResponse.skipped_shipments][google.cloud.optimization.v1.OptimizeToursResponse.skipped_shipments\], /// and doesn't actually solve the rest of the request (`status` and `routes` /// are unset in the response). /// /// *IMPORTANT*: not all infeasible shipments are returned here, but only the /// ones that are detected as infeasible as a preprocessing. DetectSomeInfeasibleShipments = 2, } /// Mode defining the behavior of the search, trading off latency versus /// solution quality. In all modes, the global request deadline is enforced. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum SearchMode { /// Unspecified search mode, equivalent to `RETURN_FAST`. Unspecified = 0, /// Stop the search after finding the first good solution. ReturnFast = 1, /// Spend all the available time to search for better solutions. ConsumeAllAvailableTime = 2, } } /// Response after solving a tour optimization problem containing the routes /// followed by each vehicle, the shipments which have been skipped and the /// overall cost of the solution. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OptimizeToursResponse { /// Routes computed for each vehicle; the i-th route corresponds to the i-th /// vehicle in the model. #[prost(message, repeated, tag="1")] pub routes: ::prost::alloc::vec::Vec<ShipmentRoute>, /// Copy of the \[OptimizeToursRequest.label][google.cloud.optimization.v1.OptimizeToursRequest.label\], if a label was specified in the /// request. #[prost(string, tag="3")] pub request_label: ::prost::alloc::string::String, /// The list of all shipments skipped. #[prost(message, repeated, tag="4")] pub skipped_shipments: ::prost::alloc::vec::Vec<SkippedShipment>, /// List of all the validation errors that we were able to detect /// independently. See the "MULTIPLE ERRORS" explanation for the /// \[OptimizeToursValidationError][google.cloud.optimization.v1.OptimizeToursValidationError\] message. #[prost(message, repeated, tag="5")] pub validation_errors: ::prost::alloc::vec::Vec<OptimizeToursValidationError>, /// Duration, distance and usage metrics for this solution. #[prost(message, optional, tag="6")] pub metrics: ::core::option::Option<optimize_tours_response::Metrics>, /// Deprecated: Use \[Metrics.total_cost][\] instead. /// Total cost of the solution. This takes into account all costs: costs per /// per hour and travel hour, fixed vehicle costs, unperformed shipment penalty /// costs, global duration cost, etc. #[deprecated] #[prost(double, tag="2")] pub total_cost: f64, } /// Nested message and enum types in `OptimizeToursResponse`. pub mod optimize_tours_response { /// Overall metrics, aggregated over all routes. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Metrics { /// Aggregated over the routes. Each metric is the sum (or max, for loads) /// over all \[ShipmentRoute.metrics][google.cloud.optimization.v1.ShipmentRoute.metrics\] fields of the same name. #[prost(message, optional, tag="1")] pub aggregated_route_metrics: ::core::option::Option<super::AggregatedMetrics>, /// Number of mandatory shipments skipped. #[prost(int32, tag="2")] pub skipped_mandatory_shipment_count: i32, /// Number of vehicles used. Note: if a vehicle route is empty and /// \[Vehicle.used_if_route_is_empty][google.cloud.optimization.v1.Vehicle.used_if_route_is_empty\] is true, the vehicle is considered /// used. #[prost(int32, tag="3")] pub used_vehicle_count: i32, /// The earliest start time for a used vehicle, computed as the minimum over /// all used vehicles of \[ShipmentRoute.vehicle_start_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_start_time\]. #[prost(message, optional, tag="4")] pub earliest_vehicle_start_time: ::core::option::Option<::prost_types::Timestamp>, /// The latest end time for a used vehicle, computed as the maximum over all /// used vehicles of \[ShipmentRoute.vehicle_end_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_end_time\]. #[prost(message, optional, tag="5")] pub latest_vehicle_end_time: ::core::option::Option<::prost_types::Timestamp>, /// Cost of the solution, broken down by cost-related request fields. /// The keys are proto paths, relative to the input OptimizeToursRequest, /// e.g. "model.shipments.pickups.cost", and the values are the total cost /// generated by the corresponding cost field, aggregated over the whole /// solution. In other words, costs\["model.shipments.pickups.cost"\] is the /// sum of all pickup costs over the solution. All costs defined in the model /// are reported in detail here with the exception of costs related to /// TransitionAttributes that are only reported in an aggregated way as of /// 2022/01. #[prost(btree_map="string, double", tag="10")] pub costs: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, f64>, /// Total cost of the solution. The sum of all values in the costs map. #[prost(double, tag="6")] pub total_cost: f64, } } /// Request to batch optimize tours as an asynchronous operation. /// Each input file should contain one `OptimizeToursRequest`, and each output /// file will contain one `OptimizeToursResponse`. The request contains /// information to read/write and parse the files. All the input and output files /// should be under the same project. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BatchOptimizeToursRequest { /// Required. Target project and location to make a call. /// /// Format: `projects/{project-id}/locations/{location-id}`. /// /// If no location is specified, a region will be chosen automatically. #[prost(string, tag="1")] pub parent: ::prost::alloc::string::String, /// Required. Input/Output information each purchase model, such as file paths and data /// formats. #[prost(message, repeated, tag="2")] pub model_configs: ::prost::alloc::vec::Vec<batch_optimize_tours_request::AsyncModelConfig>, } /// Nested message and enum types in `BatchOptimizeToursRequest`. pub mod batch_optimize_tours_request { /// Information for solving one optimization model asynchronously. #[derive(Clone, PartialEq, ::prost::Message)] pub struct AsyncModelConfig { /// User defined model name, can be used as alias by users to keep track of /// models. #[prost(string, tag="1")] pub display_name: ::prost::alloc::string::String, /// Required. Information about the input model. #[prost(message, optional, tag="2")] pub input_config: ::core::option::Option<super::InputConfig>, /// Required. The desired output location information. #[prost(message, optional, tag="3")] pub output_config: ::core::option::Option<super::OutputConfig>, /// If this is set, the model will be solved in the checkpoint mode. In this /// mode, the input model can have a deadline longer than 30 mins without the /// risk of interruption. The model will be solved in multiple short-running /// stages. Each stage generates an intermediate checkpoint /// and stores it in the user's Cloud Storage buckets. The checkpoint /// mode should be preferred over /// allow_large_deadline_despite_interruption_risk since it prevents the risk /// of interruption. #[prost(bool, tag="4")] pub enable_checkpoints: bool, } } /// Response to a `BatchOptimizeToursRequest`. This is returned in /// the LRO Operation after the operation is complete. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BatchOptimizeToursResponse { } /// A shipment model contains a set of shipments which must be performed by a /// set of vehicles, while minimizing the overall cost, which is the sum of: /// /// * the cost of routing the vehicles (sum of cost per total time, cost per /// travel time, and fixed cost over all vehicles). /// * the unperformed shipment penalties. /// * the cost of the global duration of the shipments #[derive(Clone, PartialEq, ::prost::Message)] pub struct ShipmentModel { /// Set of shipments which must be performed in the model. #[prost(message, repeated, tag="1")] pub shipments: ::prost::alloc::vec::Vec<Shipment>, /// Set of vehicles which can be used to perform visits. #[prost(message, repeated, tag="2")] pub vehicles: ::prost::alloc::vec::Vec<Vehicle>, /// Constrains the maximum number of active vehicles. A vehicle is active if /// its route performs at least one shipment. This can be used to limit the /// number of routes in the case where there are fewer drivers than /// vehicles and that the fleet of vehicles is heterogeneous. The optimization /// will then select the best subset of vehicles to use. /// Must be strictly positive. #[prost(int32, optional, tag="4")] pub max_active_vehicles: ::core::option::Option<i32>, /// Global start and end time of the model: no times outside of this range /// can be considered valid. /// /// The model's time span must be less than a year, i.e. the `global_end_time` /// and the `global_start_time` must be within 31536000 seconds of each other. /// /// When using `cost_per_*hour` fields, you might want to set this window to a /// smaller interval to increase performance (eg. if you model a single day, /// you should set the global time limits to that day). /// If unset, 00:00:00 UTC, January 1, 1970 (i.e. seconds: 0, nanos: 0) is used /// as default. #[prost(message, optional, tag="5")] pub global_start_time: ::core::option::Option<::prost_types::Timestamp>, /// If unset, 00:00:00 UTC, January 1, 1971 (i.e. seconds: 31536000, nanos: 0) /// is used as default. #[prost(message, optional, tag="6")] pub global_end_time: ::core::option::Option<::prost_types::Timestamp>, /// The "global duration" of the overall plan is the difference between the /// earliest effective start time and the latest effective end time of /// all vehicles. Users can assign a cost per hour to that quantity to try /// and optimize for earliest job completion, for example. This cost must be in /// the same unit as \[Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost\]. #[prost(double, tag="7")] pub global_duration_cost_per_hour: f64, /// Specifies duration and distance matrices used in the model. If this field /// is empty, Google Maps or geodesic distances will be used instead, depending /// on the value of the `use_geodesic_distances` field. If it is not empty, /// `use_geodesic_distances` cannot be true and neither /// `duration_distance_matrix_src_tags` nor `duration_distance_matrix_dst_tags` /// can be empty. /// /// Usage examples: /// /// * There are two locations: locA and locB. /// * 1 vehicle starting its route at locA and ending it at locA. /// * 1 pickup visit request at locB. /// /// ``` /// model { /// vehicles { start_tags: "locA" end_tags: "locA" } /// shipments { pickups { tags: "locB" } } /// duration_distance_matrix_src_tags: "locA" /// duration_distance_matrix_src_tags: "locB" /// duration_distance_matrix_dst_tags: "locA" /// duration_distance_matrix_dst_tags: "locB" /// duration_distance_matrices { /// rows { # from: locA /// durations { seconds: 0 } meters: 0 # to: locA /// durations { seconds: 100 } meters: 1000 # to: locB /// } /// rows { # from: locB /// durations { seconds: 102 } meters: 990 # to: locA /// durations { seconds: 0 } meters: 0 # to: locB /// } /// } /// } /// ``` /// /// /// * There are three locations: locA, locB and locC. /// * 1 vehicle starting its route at locA and ending it at locB, using /// matrix "fast". /// * 1 vehicle starting its route at locB and ending it at locB, using /// matrix "slow". /// * 1 vehicle starting its route at locB and ending it at locB, using /// matrix "fast". /// * 1 pickup visit request at locC. /// /// ``` /// model { /// vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } /// vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } /// vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } /// shipments { pickups { tags: "locC" } } /// duration_distance_matrix_src_tags: "locA" /// duration_distance_matrix_src_tags: "locB" /// duration_distance_matrix_src_tags: "locC" /// duration_distance_matrix_dst_tags: "locB" /// duration_distance_matrix_dst_tags: "locC" /// duration_distance_matrices { /// vehicle_start_tag: "fast" /// rows { # from: locA /// durations { seconds: 1000 } meters: 2000 # to: locB /// durations { seconds: 600 } meters: 1000 # to: locC /// } /// rows { # from: locB /// durations { seconds: 0 } meters: 0 # to: locB /// durations { seconds: 700 } meters: 1200 # to: locC /// } /// rows { # from: locC /// durations { seconds: 702 } meters: 1190 # to: locB /// durations { seconds: 0 } meters: 0 # to: locC /// } /// } /// duration_distance_matrices { /// vehicle_start_tag: "slow" /// rows { # from: locA /// durations { seconds: 1800 } meters: 2001 # to: locB /// durations { seconds: 900 } meters: 1002 # to: locC /// } /// rows { # from: locB /// durations { seconds: 0 } meters: 0 # to: locB /// durations { seconds: 1000 } meters: 1202 # to: locC /// } /// rows { # from: locC /// durations { seconds: 1001 } meters: 1195 # to: locB /// durations { seconds: 0 } meters: 0 # to: locC /// } /// } /// } /// ``` #[prost(message, repeated, tag="8")] pub duration_distance_matrices: ::prost::alloc::vec::Vec<shipment_model::DurationDistanceMatrix>, /// Tags defining the sources of the duration and distance matrices; /// `duration_distance_matrices(i).rows(j)` defines durations and distances /// from visits with tag `duration_distance_matrix_src_tags(j)` to other visits /// in matrix i. /// /// Tags correspond to /// \[VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags\] /// or \[Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags\]. /// A given `VisitRequest` or `Vehicle` must match exactly one tag in this /// field. Note that a `Vehicle`'s source, destination and matrix tags may be /// the same; similarly a `VisitRequest`'s source and destination tags may be /// the same. All tags must be different and cannot be empty strings. If this /// field is not empty, then `duration_distance_matrices` must not be empty. #[prost(string, repeated, tag="9")] pub duration_distance_matrix_src_tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Tags defining the destinations of the duration and distance matrices; /// `duration_distance_matrices(i).rows(j).durations(k)` (resp. /// `duration_distance_matrices(i).rows(j).meters(k))` defines the duration /// (resp. the distance) of the travel from visits with tag /// `duration_distance_matrix_src_tags(j)` to visits with tag /// `duration_distance_matrix_dst_tags(k)` in matrix i. /// /// Tags correspond to /// \[VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags\] /// or \[Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags\]. /// A given `VisitRequest` or `Vehicle` must match exactly one tag in this /// field. Note that a `Vehicle`'s source, destination and matrix tags may be /// the same; similarly a `VisitRequest`'s source and destination tags may be /// the same. All tags must be different and cannot be empty strings. If this /// field is not empty, then `duration_distance_matrices` must not be empty. #[prost(string, repeated, tag="10")] pub duration_distance_matrix_dst_tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Transition attributes added to the model. #[prost(message, repeated, tag="11")] pub transition_attributes: ::prost::alloc::vec::Vec<TransitionAttributes>, /// Sets of incompatible shipment_types (see `ShipmentTypeIncompatibility`). #[prost(message, repeated, tag="12")] pub shipment_type_incompatibilities: ::prost::alloc::vec::Vec<ShipmentTypeIncompatibility>, /// Sets of `shipment_type` requirements (see `ShipmentTypeRequirement`). #[prost(message, repeated, tag="13")] pub shipment_type_requirements: ::prost::alloc::vec::Vec<ShipmentTypeRequirement>, /// Set of precedence rules which must be enforced in the model. #[prost(message, repeated, tag="14")] pub precedence_rules: ::prost::alloc::vec::Vec<shipment_model::PrecedenceRule>, /// Deprecated: No longer used. /// Set of break rules used in the model. /// Each vehicle specifies the `BreakRule` that applies to it via the /// \[Vehicle.break_rule_indices][google.cloud.optimization.v1.Vehicle.break_rule_indices\] field (which must be a singleton). #[deprecated] #[prost(message, repeated, tag="15")] pub break_rules: ::prost::alloc::vec::Vec<shipment_model::BreakRule>, } /// Nested message and enum types in `ShipmentModel`. pub mod shipment_model { /// Specifies a duration and distance matrix from visit and vehicle start /// locations to visit and vehicle end locations. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DurationDistanceMatrix { /// Specifies the rows of the duration and distance matrix. It must have as /// many elements as \[ShipmentModel.duration_distance_matrix_src_tags][google.cloud.optimization.v1.ShipmentModel.duration_distance_matrix_src_tags\]. #[prost(message, repeated, tag="1")] pub rows: ::prost::alloc::vec::Vec<duration_distance_matrix::Row>, /// Tag defining to which vehicles this duration and distance matrix applies. /// If empty, this applies to all vehicles, and there can only be a single /// matrix. /// /// Each vehicle start must match exactly one matrix, i.e. exactly one of /// their `start_tags` field must match the `vehicle_start_tag` of a matrix /// (and of that matrix only). /// /// All matrices must have a different `vehicle_start_tag`. #[prost(string, tag="2")] pub vehicle_start_tag: ::prost::alloc::string::String, } /// Nested message and enum types in `DurationDistanceMatrix`. pub mod duration_distance_matrix { /// Specifies a row of the duration and distance matrix. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Row { /// Duration values for a given row. It must have as many elements as /// \[ShipmentModel.duration_distance_matrix_dst_tags][google.cloud.optimization.v1.ShipmentModel.duration_distance_matrix_dst_tags\]. #[prost(message, repeated, tag="1")] pub durations: ::prost::alloc::vec::Vec<::prost_types::Duration>, /// Distance values for a given row. If no costs or constraints refer to /// distances in the model, this can be left empty; otherwise it must have /// as many elements as `durations`. #[prost(double, repeated, tag="2")] pub meters: ::prost::alloc::vec::Vec<f64>, } } /// A precedence rule between two events (each event is the pickup or the /// delivery of a shipment): the "second" event has to start at least /// `offset_duration` after "first" has started. /// /// Several precedences can refer to the same (or related) events, e.g., /// "pickup of B happens after delivery of A" and "pickup of C happens after /// pickup of B". /// /// Furthermore, precedences only apply when both shipments are performed and /// are otherwise ignored. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PrecedenceRule { /// Shipment index of the "first" event. This field must be specified. #[prost(int32, optional, tag="1")] pub first_index: ::core::option::Option<i32>, /// Indicates if the "first" event is a delivery. #[prost(bool, tag="3")] pub first_is_delivery: bool, /// Shipment index of the "second" event. This field must be specified. #[prost(int32, optional, tag="2")] pub second_index: ::core::option::Option<i32>, /// Indicates if the "second" event is a delivery. #[prost(bool, tag="4")] pub second_is_delivery: bool, /// The offset between the "first" and "second" event. It can be negative. #[prost(message, optional, tag="5")] pub offset_duration: ::core::option::Option<::prost_types::Duration>, } /// Deprecated: Use top level \[BreakRule][\] instead. /// Rules to generate time breaks for a vehicle (e.g. lunch /// breaks). A break is a contiguous period of time during which the vehicle /// remains idle at its current position and cannot perform any visit. A break /// may occur: /// /// * during the travel between two visits (which includes the time right /// before or right after a visit, but not in the middle of a visit), in /// which case it extends the corresponding transit time between the visits, /// * or before the vehicle start (the vehicle may not start in the middle of /// a break), in which case it does not affect the vehicle start time. /// * or after the vehicle end (ditto, with the vehicle end time). #[derive(Clone, PartialEq, ::prost::Message)] pub struct BreakRule { /// Sequence of breaks. See the `BreakRequest` message. #[prost(message, repeated, tag="1")] pub break_requests: ::prost::alloc::vec::Vec<break_rule::BreakRequest>, /// Several `FrequencyConstraint` may apply. They must all be satisfied by /// the `BreakRequest`s of this `BreakRule`. See `FrequencyConstraint`. #[prost(message, repeated, tag="2")] pub frequency_constraints: ::prost::alloc::vec::Vec<break_rule::FrequencyConstraint>, } /// Nested message and enum types in `BreakRule`. pub mod break_rule { /// The sequence of breaks (i.e. their number and order) that apply to each /// vehicle must be known beforehand. The repeated `BreakRequest`s define /// that sequence, in the order in which they must occur. Their time windows /// (`earliest_start_time` / `latest_start_time`) may overlap, but they must /// be compatible with the order (this is checked). #[derive(Clone, PartialEq, ::prost::Message)] pub struct BreakRequest { /// Required. Lower bound (inclusive) on the start of the break. #[prost(message, optional, tag="1")] pub earliest_start_time: ::core::option::Option<::prost_types::Timestamp>, /// Required. Upper bound (inclusive) on the start of the break. #[prost(message, optional, tag="2")] pub latest_start_time: ::core::option::Option<::prost_types::Timestamp>, /// Required. Minimum duration of the break. Must be positive. #[prost(message, optional, tag="3")] pub min_duration: ::core::option::Option<::prost_types::Duration>, } /// One may further constrain the frequency and duration of the breaks /// specified above, by enforcing a minimum break frequency, such as /// "There must be a break of at least 1 hour every 12 hours". Assuming that /// this can be interpreted as "Within any sliding time window of 12h, there /// must be at least one break of at least one hour", that example would /// translate to the following `FrequencyConstraint`: /// ``` /// { /// min_break_duration { seconds: 3600 } # 1 hour. /// max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). /// } /// ``` /// /// The timing and duration of the breaks in the solution will respect all /// such constraints, in addition to the time windows and minimum durations /// already specified in the `BreakRequest`. /// /// A `FrequencyConstraint` may in practice apply to non-consecutive breaks. /// For example, the following schedule honors the "1h every 12h" example: /// ``` /// 04:00 vehicle start /// .. performing travel and visits .. /// 09:00 1 hour break /// 10:00 end of the break /// .. performing travel and visits .. /// 12:00 20-min lunch break /// 12:20 end of the break /// .. performing travel and visits .. /// 21:00 1 hour break /// 22:00 end of the break /// .. performing travel and visits .. /// 23:59 vehicle end /// ``` #[derive(Clone, PartialEq, ::prost::Message)] pub struct FrequencyConstraint { /// Required. Minimum break duration for this constraint. Nonnegative. /// See description of `FrequencyConstraint`. #[prost(message, optional, tag="1")] pub min_break_duration: ::core::option::Option<::prost_types::Duration>, /// Required. Maximum allowed span of any interval of time in the route that does not /// include at least partially a break of `duration >= /// min_break_duration`. Must be positive. #[prost(message, optional, tag="2")] pub max_inter_break_duration: ::core::option::Option<::prost_types::Duration>, } } } /// The shipment of a single item, from one of its pickups to one of its /// deliveries. For the shipment to be considered as performed, a unique vehicle /// must visit one of its pickup locations (and decrease its spare capacities /// accordingly), then visit one of its delivery locations later on (and /// therefore re-increase its spare capacities accordingly). #[derive(Clone, PartialEq, ::prost::Message)] pub struct Shipment { /// Set of pickup alternatives associated to the shipment. If not specified, /// the vehicle only needs to visit a location corresponding to the deliveries. #[prost(message, repeated, tag="1")] pub pickups: ::prost::alloc::vec::Vec<shipment::VisitRequest>, /// Set of delivery alternatives associated to the shipment. If not specified, /// the vehicle only needs to visit a location corresponding to the pickups. #[prost(message, repeated, tag="2")] pub deliveries: ::prost::alloc::vec::Vec<shipment::VisitRequest>, /// Load demands of the shipment (for example weight, volume, number of /// pallets etc). The keys in the map should be identifiers describing the type /// of the corresponding load, ideally also including the units. /// For example: "weight_kg", "volume_gallons", "pallet_count", etc. /// If a given key does not appear in the map, the corresponding load is /// considered as null. #[prost(btree_map="string, message", tag="14")] pub load_demands: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, shipment::Load>, /// If the shipment is not completed, this penalty is added to the overall /// cost of the routes. A shipment is considered completed if one of its pickup /// and delivery alternatives is visited. The cost may be expressed in the /// same unit used for all other cost-related fields in the model and must be /// positive. /// /// *IMPORTANT*: If this penalty is not specified, it is considered infinite, /// i.e. the shipment must be completed. #[prost(double, optional, tag="4")] pub penalty_cost: ::core::option::Option<f64>, /// The set of vehicles that may perform this shipment. If empty, all vehicles /// may perform it. Vehicles are given by their index in the `ShipmentModel`'s /// `vehicles` list. #[prost(int32, repeated, tag="5")] pub allowed_vehicle_indices: ::prost::alloc::vec::Vec<i32>, /// Specifies the cost that is incurred when this shipment is delivered by each /// vehicle. If specified, it must have EITHER: /// /// * the same number of elements as `costs_per_vehicle_indices`. /// `costs_per_vehicle\[i\]` corresponds to vehicle /// `costs_per_vehicle_indices\[i\]` of the model. /// * the same number of elements as there are vehicles in the model. The /// i-th element corresponds to vehicle #i of the model. /// /// These costs must be in the same unit as `penalty_cost` and must not be /// negative. Leave this field empty, if there are no such costs. #[prost(double, repeated, tag="6")] pub costs_per_vehicle: ::prost::alloc::vec::Vec<f64>, /// Indices of the vehicles to which `costs_per_vehicle` applies. If non-empty, /// it must have the same number of elements as `costs_per_vehicle`. A vehicle /// index may not be specified more than once. If a vehicle is excluded from /// `costs_per_vehicle_indices`, its cost is zero. #[prost(int32, repeated, tag="7")] pub costs_per_vehicle_indices: ::prost::alloc::vec::Vec<i32>, /// Specifies the maximum relative detour time compared to the shortest path /// from pickup to delivery. If specified, it must be nonnegative, and the /// shipment must contain at least a pickup and a delivery. /// /// For example, let t be the shortest time taken to go from the selected /// pickup alternative directly to the selected delivery alternative. Then /// setting `pickup_to_delivery_relative_detour_limit` enforces: /// /// ``` /// start_time(delivery) - start_time(pickup) <= /// std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit)) /// ``` /// /// If both relative and absolute limits are specified on the same shipment, /// the more constraining limit is used for each possible pickup/delivery pair. /// As of 2017/10, detours are only supported when travel durations do not /// depend on vehicles. #[prost(double, optional, tag="8")] pub pickup_to_delivery_relative_detour_limit: ::core::option::Option<f64>, /// Specifies the maximum absolute detour time compared to the shortest path /// from pickup to delivery. If specified, it must be nonnegative, and the /// shipment must contain at least a pickup and a delivery. /// /// For example, let t be the shortest time taken to go from the selected /// pickup alternative directly to the selected delivery alternative. Then /// setting `pickup_to_delivery_absolute_detour_limit` enforces: /// /// ``` /// start_time(delivery) - start_time(pickup) <= /// t + pickup_to_delivery_absolute_detour_limit /// ``` /// /// If both relative and absolute limits are specified on the same shipment, /// the more constraining limit is used for each possible pickup/delivery pair. /// As of 2017/10, detours are only supported when travel durations do not /// depend on vehicles. #[prost(message, optional, tag="9")] pub pickup_to_delivery_absolute_detour_limit: ::core::option::Option<::prost_types::Duration>, /// Specifies the maximum duration from start of pickup to start of delivery of /// a shipment. If specified, it must be nonnegative, and the shipment must /// contain at least a pickup and a delivery. This does not depend on which /// alternatives are selected for pickup and delivery, nor on vehicle speed. /// This can be specified alongside maximum detour constraints: the solution /// will respect both specifications. #[prost(message, optional, tag="10")] pub pickup_to_delivery_time_limit: ::core::option::Option<::prost_types::Duration>, /// Non-empty string specifying a "type" for this shipment. /// This feature can be used to define incompatibilities or requirements /// between `shipment_types` (see `shipment_type_incompatibilities` and /// `shipment_type_requirements` in `ShipmentModel`). /// /// Differs from `visit_types` which is specified for a single visit: All /// pickup/deliveries belonging to the same shipment share the same /// `shipment_type`. #[prost(string, tag="11")] pub shipment_type: ::prost::alloc::string::String,
/// Specifies a label for this shipment. This label is reported in the response /// in the `shipment_label` of the corresponding \[ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit\]. #[prost(string, tag="12")] pub label: ::prost::alloc::string::String, /// If true, skip this shipment, but don't apply a `penalty_cost`. /// /// Ignoring a shipment results in a validation error when there are any /// `shipment_type_requirements` in the model. /// /// Ignoring a shipment that is performed in `injected_first_solution_routes` /// or `injected_solution_constraint` is permitted; the solver removes the /// related pickup/delivery visits from the performing route. /// `precedence_rules` that reference ignored shipments will also be ignored. #[prost(bool, tag="13")] pub ignore: bool, /// Deprecated: Use \[Shipment.load_demands][\] instead. #[deprecated] #[prost(message, repeated, tag="3")] pub demands: ::prost::alloc::vec::Vec<CapacityQuantity>, } /// Nested message and enum types in `Shipment`. pub mod shipment { /// Request for a visit which can be done by a vehicle: it has a geo-location /// (or two, see below), opening and closing times represented by time windows, /// and a service duration time (time spent by the vehicle once it has arrived /// to pickup or drop off goods). #[derive(Clone, PartialEq, ::prost::Message)] pub struct VisitRequest { /// The geo-location where the vehicle arrives when performing this /// `VisitRequest`. If the shipment model has duration distance matrices, /// `arrival_location` must not be specified. #[prost(message, optional, tag="1")] pub arrival_location: ::core::option::Option<super::super::super::super::r#type::LatLng>, /// The waypoint where the vehicle arrives when performing this /// `VisitRequest`. If the shipment model has duration distance matrices, /// `arrival_waypoint` must not be specified. #[prost(message, optional, tag="2")] pub arrival_waypoint: ::core::option::Option<super::Waypoint>, /// The geo-location where the vehicle departs after completing this /// `VisitRequest`. Can be omitted if it is the same as `arrival_location`. /// If the shipment model has duration distance matrices, /// `departure_location` must not be specified. #[prost(message, optional, tag="3")] pub departure_location: ::core::option::Option<super::super::super::super::r#type::LatLng>, /// The waypoint where the vehicle departs after completing this /// `VisitRequest`. Can be omitted if it is the same as `arrival_waypoint`. /// If the shipment model has duration distance matrices, /// `departure_waypoint` must not be specified. #[prost(message, optional, tag="4")] pub departure_waypoint: ::core::option::Option<super::Waypoint>, /// Specifies tags attached to the visit request. /// Empty or duplicate strings are not allowed. #[prost(string, repeated, tag="5")] pub tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Time windows which constrain the arrival time at a visit. /// Note that a vehicle may depart outside of the arrival time window, i.e. /// arrival time + duration do not need to be inside a time window. This can /// result in waiting time if the vehicle arrives before /// \[TimeWindow.start_time][google.cloud.optimization.v1.TimeWindow.start_time\]. /// /// The absence of `TimeWindow` means that the vehicle can perform this visit /// at any time. /// /// Time windows must be disjoint, i.e. no time window must overlap with or /// be adjacent to another, and they must be in increasing order. /// /// `cost_per_hour_after_soft_end_time` and `soft_end_time` can only /// be set if there is a single time window. #[prost(message, repeated, tag="6")] pub time_windows: ::prost::alloc::vec::Vec<super::TimeWindow>, /// Duration of the visit, i.e. time spent by the vehicle between arrival /// and departure (to be added to the possible waiting time; see /// `time_windows`). #[prost(message, optional, tag="7")] pub duration: ::core::option::Option<::prost_types::Duration>, /// Cost to service this visit request on a vehicle route. This can be used /// to pay different costs for each alternative pickup or delivery of a /// shipment. This cost must be in the same unit as `Shipment.penalty_cost` /// and must not be negative. #[prost(double, tag="8")] pub cost: f64, /// Load demands of this visit request. This is just like /// \[Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands\] field, except that it only applies to this /// \[VisitRequest][google.cloud.optimization.v1.Shipment.VisitRequest\] instead of the whole \[Shipment][google.cloud.optimization.v1.Shipment\]. /// The demands listed here are added to the demands listed in /// \[Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands\]. #[prost(btree_map="string, message", tag="12")] pub load_demands: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, Load>, /// Specifies the types of the visit. This may be used to allocate additional /// time required for a vehicle to complete this visit (see /// \[Vehicle.extra_visit_duration_for_visit_type][google.cloud.optimization.v1.Vehicle.extra_visit_duration_for_visit_type\]). /// /// A type can only appear once. #[prost(string, repeated, tag="10")] pub visit_types: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Specifies a label for this `VisitRequest`. This label is reported in the /// response as `visit_label` in the corresponding \[ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit\]. #[prost(string, tag="11")] pub label: ::prost::alloc::string::String, /// Deprecated: Use \[VisitRequest.load_demands][\] instead. #[deprecated] #[prost(message, repeated, tag="9")] pub demands: ::prost::alloc::vec::Vec<super::CapacityQuantity>, } /// When performing a visit, a predefined amount may be added to the vehicle /// load if it's a pickup, or subtracted if it's a delivery. This message /// defines such amount. See \[load_demands][google.cloud.optimization.v1.Shipment.load_demands\]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Load { /// The amount by which the load of the vehicle performing the corresponding /// visit will vary. Since it is an integer, users are advised to choose an /// appropriate unit to avoid loss of precision. Must be ≥ 0. #[prost(int64, tag="2")] pub amount: i64, } } /// Specifies incompatibilties between shipments depending on their /// shipment_type. The appearance of incompatible shipments on the same route is /// restricted based on the incompatibility mode. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ShipmentTypeIncompatibility { /// List of incompatible types. Two shipments having different `shipment_types` /// among those listed are "incompatible". #[prost(string, repeated, tag="1")] pub types: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Mode applied to the incompatibility. #[prost(enumeration="shipment_type_incompatibility::IncompatibilityMode", tag="2")] pub incompatibility_mode: i32, } /// Nested message and enum types in `ShipmentTypeIncompatibility`. pub mod shipment_type_incompatibility { /// Modes defining how the appearance of incompatible shipments are restricted /// on the same route. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum IncompatibilityMode { /// Unspecified incompatibility mode. This value should never be used. Unspecified = 0, /// In this mode, two shipments with incompatible types can never share the /// same vehicle. NotPerformedBySameVehicle = 1, /// For two shipments with incompatible types with the /// `NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY` incompatibility mode: /// /// * If both are pickups only (no deliveries) or deliveries only (no /// pickups), they cannot share the same vehicle at all. /// * If one of the shipments has a delivery and the other a pickup, the two /// shipments can share the same vehicle iff the former shipment is /// delivered before the latter is picked up. NotInSameVehicleSimultaneously = 2, } } /// Specifies requirements between shipments based on their shipment_type. /// The specifics of the requirement are defined by the requirement mode. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ShipmentTypeRequirement { /// List of alternative shipment types required by the /// `dependent_shipment_types`. #[prost(string, repeated, tag="1")] pub required_shipment_type_alternatives: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// All shipments with a type in the `dependent_shipment_types` field require /// at least one shipment of type `required_shipment_type_alternatives` to be /// visited on the same route. /// /// NOTE: Chains of requirements such that a `shipment_type` depends on itself /// are not allowed. #[prost(string, repeated, tag="2")] pub dependent_shipment_types: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Mode applied to the requirement. #[prost(enumeration="shipment_type_requirement::RequirementMode", tag="3")] pub requirement_mode: i32, } /// Nested message and enum types in `ShipmentTypeRequirement`. pub mod shipment_type_requirement { /// Modes defining the appearance of dependent shipments on a route. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum RequirementMode { /// Unspecified requirement mode. This value should never be used. Unspecified = 0, /// In this mode, all "dependent" shipments must share the same vehicle as at /// least one of their "required" shipments. PerformedBySameVehicle = 1, /// With the `IN_SAME_VEHICLE_AT_PICKUP_TIME` mode, all "dependent" /// shipments need to have at least one "required" shipment on their vehicle /// at the time of their pickup. /// /// A "dependent" shipment pickup must therefore have either: /// /// * A delivery-only "required" shipment delivered on the route after, or /// * A "required" shipment picked up on the route before it, and if the /// "required" shipment has a delivery, this delivery must be performed /// after the "dependent" shipment's pickup. InSameVehicleAtPickupTime = 2, /// Same as before, except the "dependent" shipments need to have a /// "required" shipment on their vehicle at the time of their *delivery*. InSameVehicleAtDeliveryTime = 3, } } /// Models a vehicle in a shipment problem. Solving a shipment problem will /// build a route starting from `start_location` and ending at `end_location` /// for this vehicle. A route is a sequence of visits (see `ShipmentRoute`). #[derive(Clone, PartialEq, ::prost::Message)] pub struct Vehicle { /// The travel mode which affects the roads usable by the vehicle and its /// speed. See also `travel_duration_multiple`. #[prost(enumeration="vehicle::TravelMode", tag="1")] pub travel_mode: i32, /// Geographic location where the vehicle starts before picking up any /// shipments. If not specified, the vehicle starts at its first pickup. /// If the shipment model has duration and distance matrices, `start_location` /// must not be specified. #[prost(message, optional, tag="3")] pub start_location: ::core::option::Option<super::super::super::r#type::LatLng>, /// Waypoint representing a geographic location where the vehicle starts before /// picking up any shipments. If neither `start_waypoint` nor `start_location` /// is specified, the vehicle starts at its first pickup. /// If the shipment model has duration and distance matrices, `start_waypoint` /// must not be specified. #[prost(message, optional, tag="4")] pub start_waypoint: ::core::option::Option<Waypoint>, /// Geographic location where the vehicle ends after it has completed its last /// `VisitRequest`. If not specified the vehicle's `ShipmentRoute` ends /// immediately when it completes its last `VisitRequest`. /// If the shipment model has duration and distance matrices, `end_location` /// must not be specified. #[prost(message, optional, tag="5")] pub end_location: ::core::option::Option<super::super::super::r#type::LatLng>, /// Waypoint representing a geographic location where the vehicle ends after /// it has completed its last `VisitRequest`. If neither `end_waypoint` nor /// `end_location` is specified, the vehicle's `ShipmentRoute` ends immediately /// when it completes its last `VisitRequest`. /// If the shipment model has duration and distance matrices, `end_waypoint` /// must not be specified. #[prost(message, optional, tag="6")] pub end_waypoint: ::core::option::Option<Waypoint>, /// Specifies tags attached to the start of the vehicle's route. /// /// Empty or duplicate strings are not allowed. #[prost(string, repeated, tag="7")] pub start_tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Specifies tags attached to the end of the vehicle's route. /// /// Empty or duplicate strings are not allowed. #[prost(string, repeated, tag="8")] pub end_tags: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Time windows during which the vehicle may depart its start location. /// They must be within the global time limits (see /// \[ShipmentModel.global_*][google.cloud.optimization.v1.ShipmentModel.global_start_time\] /// fields). If unspecified, there is no limitation besides those global time /// limits. /// /// Time windows belonging to the same repeated field must be disjoint, i.e. no /// time window can overlap with or be adjacent to another, and they must be in /// chronological order. /// /// `cost_per_hour_after_soft_end_time` and `soft_end_time` can only be set if /// there is a single time window. #[prost(message, repeated, tag="9")] pub start_time_windows: ::prost::alloc::vec::Vec<TimeWindow>, /// Time windows during which the vehicle may arrive at its end location. /// They must be within the global time limits (see /// \[ShipmentModel.global_*][google.cloud.optimization.v1.ShipmentModel.global_start_time\] /// fields). If unspecified, there is no limitation besides those global time /// limits. /// /// Time windows belonging to the same repeated field must be disjoint, i.e. no /// time window can overlap with or be adjacent to another, and they must be in /// chronological order. /// /// `cost_per_hour_after_soft_end_time` and `soft_end_time` can only be set if /// there is a single time window. #[prost(message, repeated, tag="10")] pub end_time_windows: ::prost::alloc::vec::Vec<TimeWindow>, /// Specifies a multiplicative factor that can be used to increase or decrease /// travel times of this vehicle. For example, setting this to 2.0 means /// that this vehicle is slower and has travel times that are twice what they /// are for standard vehicles. This multiple does not affect visit durations. /// It does affect cost if `cost_per_hour` or `cost_per_traveled_hour` are /// specified. This must be in the range [0.001, 1000.0]. If unset, the vehicle /// is standard, and this multiple is considered 1.0. /// /// WARNING: Travel times will be rounded to the nearest second after this /// multiple is applied but before performing any numerical operations, thus, /// a small multiple may result in a loss of precision. /// /// See also `extra_visit_duration_for_visit_type` below. #[prost(double, optional, tag="11")] pub travel_duration_multiple: ::core::option::Option<f64>, /// Unloading policy enforced on the vehicle. #[prost(enumeration="vehicle::UnloadingPolicy", tag="12")] pub unloading_policy: i32, /// Capacities of the vehicle (weight, volume, # of pallets for example). /// The keys in the map are the identifiers of the type of load, consistent /// with the keys of the /// \[Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands\] /// field. If a given key is absent from this map, the corresponding capacity /// is considered to be limitless. #[prost(btree_map="string, message", tag="30")] pub load_limits: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, vehicle::LoadLimit>, /// Vehicle costs: all costs add up and must be in the same unit as /// \[Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost\]. /// /// Cost per hour of the vehicle route. This cost is applied to the total time /// taken by the route, and includes travel time, waiting time, and visit time. /// Using `cost_per_hour` instead of just `cost_per_traveled_hour` may result /// in additional latency. #[prost(double, tag="16")] pub cost_per_hour: f64, /// Cost per traveled hour of the vehicle route. This cost is applied only to /// travel time taken by the route (i.e., that reported in /// \[ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions\]), and excludes waiting time and visit time. #[prost(double, tag="17")] pub cost_per_traveled_hour: f64, /// Cost per kilometer of the vehicle route. This cost is applied to the /// distance reported in the \[ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions\] and does not apply /// to any distance implicitly traveled from the `arrival_location` to the /// `departure_location` of a single `VisitRequest`. #[prost(double, tag="18")] pub cost_per_kilometer: f64, /// Fixed cost applied if this vehicle is used to handle a shipment. #[prost(double, tag="19")] pub fixed_cost: f64, /// This field only applies to vehicles when their route does not serve any /// shipments. It indicates if the vehicle should be considered as used or not /// in this case. /// /// If true, the vehicle goes from its start to its end location even if it /// doesn't serve any shipments, and time and distance costs resulting from its /// start --> end travel are taken into account. /// /// Otherwise, it doesn't travel from its start to its end location, and no /// `break_rule` or delay (from `TransitionAttributes`) are scheduled for this /// vehicle. In this case, the vehicle's `ShipmentRoute` doesn't contain any /// information except for the vehicle index and label. #[prost(bool, tag="20")] pub used_if_route_is_empty: bool, /// Limit applied to the total duration of the vehicle's route. In a given /// `OptimizeToursResponse`, the route duration of a vehicle is the /// difference between its `vehicle_end_time` and `vehicle_start_time`. #[prost(message, optional, tag="21")] pub route_duration_limit: ::core::option::Option<vehicle::DurationLimit>, /// Limit applied to the travel duration of the vehicle's route. In a given /// `OptimizeToursResponse`, the route travel duration is the sum of all its /// \[transitions.travel_duration][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_duration\]. #[prost(message, optional, tag="22")] pub travel_duration_limit: ::core::option::Option<vehicle::DurationLimit>, /// Limit applied to the total distance of the vehicle's route. In a given /// `OptimizeToursResponse`, the route distance is the sum of all its /// \[transitions.travel_distance_meters][google.cloud.optimization.v1.ShipmentRoute.Transition.travel_distance_meters\]. #[prost(message, optional, tag="23")] pub route_distance_limit: ::core::option::Option<DistanceLimit>, /// Specifies a map from visit_types strings to durations. The duration is time /// in addition to /// \[VisitRequest.duration][google.cloud.optimization.v1.Shipment.VisitRequest.duration\] /// to be taken at visits with the specified `visit_types`. This extra visit /// duration adds cost if `cost_per_hour` is specified. Keys (i.e. /// `visit_types`) cannot be empty strings. /// /// If a visit request has multiple types, a duration will be added for each /// type in the map. #[prost(btree_map="string, message", tag="24")] pub extra_visit_duration_for_visit_type: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, ::prost_types::Duration>, /// Describes the break schedule to be enforced on this vehicle. /// If empty, no breaks will be scheduled for this vehicle. #[prost(message, optional, tag="25")] pub break_rule: ::core::option::Option<BreakRule>, /// Specifies a label for this vehicle. This label is reported in the response /// as the `vehicle_label` of the corresponding \[ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute\]. #[prost(string, tag="27")] pub label: ::prost::alloc::string::String, /// If true, `used_if_route_is_empty` must be false, and this vehicle will /// remain unused. /// /// If a shipment is performed by an ignored vehicle in /// `injected_first_solution_routes`, it is skipped in the first solution but /// is free to be performed in the response. /// /// If a shipment is performed by an ignored vehicle in /// `injected_solution_constraint` and any related pickup/delivery is /// constrained to remain on the vehicle (i.e., not relaxed to level /// `RELAX_ALL_AFTER_THRESHOLD`), it is skipped in the response. /// If a shipment has a non-empty `allowed_vehicle_indices` field and all of /// the allowed vehicles are ignored, it is skipped in the response. #[prost(bool, tag="28")] pub ignore: bool, /// Deprecated: No longer used. /// Indices in the `break_rule` field in the source /// \[ShipmentModel][\]. They correspond to break rules enforced on the vehicle. /// /// /// As of 2018/03, at most one rule index per vehicle can be specified. #[deprecated] #[prost(int32, repeated, packed="false", tag="29")] pub break_rule_indices: ::prost::alloc::vec::Vec<i32>, /// Deprecated: Use \[Vehicle.load_limits][\] instead. #[deprecated] #[prost(message, repeated, tag="13")] pub capacities: ::prost::alloc::vec::Vec<CapacityQuantity>, /// Deprecated: Use \[Vehicle.LoadLimit.start_load_interval][\] instead. #[deprecated] #[prost(message, repeated, tag="14")] pub start_load_intervals: ::prost::alloc::vec::Vec<CapacityQuantityInterval>, /// Deprecated: Use \[Vehicle.LoadLimit.end_load_interval][\] instead. #[deprecated] #[prost(message, repeated, tag="15")] pub end_load_intervals: ::prost::alloc::vec::Vec<CapacityQuantityInterval>, } /// Nested message and enum types in `Vehicle`. pub mod vehicle { /// Defines a load limit applying to a vehicle, e.g. "this truck may only /// carry up to 3500 kg". See \[load_limits][google.cloud.optimization.v1.Vehicle.load_limits\]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct LoadLimit { /// The maximum acceptable amount of load. #[prost(int64, optional, tag="1")] pub max_load: ::core::option::Option<i64>, /// A soft limit of the load. See \[cost_per_unit_above_soft_max][google.cloud.optimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max\]. #[prost(int64, tag="2")] pub soft_max_load: i64, /// If the load ever exceeds \[soft_max_load][google.cloud.optimization.v1.Vehicle.LoadLimit.soft_max_load\] along this vehicle's route, /// the following cost penalty applies (only once per vehicle): /// (load - \[soft_max_load][google.cloud.optimization.v1.Vehicle.LoadLimit.soft_max_load\]) * \[cost_per_unit_above_soft_max][google.cloud.optimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max\]. All costs /// add up and must be in the same unit as \[Shipment.penalty_cost][google.cloud.optimization.v1.Shipment.penalty_cost\]. #[prost(double, tag="3")] pub cost_per_unit_above_soft_max: f64, /// The acceptable load interval of the vehicle at the start of the route. #[prost(message, optional, tag="4")] pub start_load_interval: ::core::option::Option<load_limit::Interval>, /// The acceptable load interval of the vehicle at the end of the route. #[prost(message, optional, tag="5")] pub end_load_interval: ::core::option::Option<load_limit::Interval>, } /// Nested message and enum types in `LoadLimit`. pub mod load_limit { /// Interval of acceptable load amounts. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Interval { /// A minimum acceptable load. Must be ≥ 0. /// If they're both specified, \[min][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.min\] must be ≤ \[max][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.max\]. #[prost(int64, tag="1")] pub min: i64, /// A maximum acceptable load. Must be ≥ 0. If unspecified, the maximum /// load is unrestricted by this message. /// If they're both specified, \[min][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.min\] must be ≤ \[max][google.cloud.optimization.v1.Vehicle.LoadLimit.Interval.max\]. #[prost(int64, optional, tag="2")] pub max: ::core::option::Option<i64>, } } /// A limit defining a maximum duration of the route of a vehicle. It can be /// either hard or soft. /// /// When a soft limit field is defined, both the soft max threshold and its /// associated cost must be defined together. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DurationLimit { /// A hard limit constraining the duration to be at most max_duration. #[prost(message, optional, tag="1")] pub max_duration: ::core::option::Option<::prost_types::Duration>, /// A soft limit not enforcing a maximum duration limit, but when violated /// makes the route incur a cost. This cost adds up to other costs defined in /// the model, with the same unit. /// /// If defined, `soft_max_duration` must be nonnegative. If max_duration is /// also defined, `soft_max_duration` must be less than max_duration. #[prost(message, optional, tag="2")] pub soft_max_duration: ::core::option::Option<::prost_types::Duration>, /// Cost per hour incurred if the `soft_max_duration` threshold is violated. /// The additional cost is 0 if the duration is under the threshold, /// otherwise the cost depends on the duration as follows: /// ``` /// cost_per_hour_after_soft_max * (duration - soft_max_duration) /// ``` /// The cost must be nonnegative. #[prost(double, optional, tag="3")] pub cost_per_hour_after_soft_max: ::core::option::Option<f64>, /// A soft limit not enforcing a maximum duration limit, but when violated /// makes the route incur a cost, quadratic in the duration. This cost adds /// up to other costs defined in the model, with the same unit. /// /// If defined, `quadratic_soft_max_duration` must be nonnegative. If /// `max_duration` is also defined, `quadratic_soft_max_duration` must be /// less than `max_duration`, and the difference must be no larger than one /// day: /// /// `max_duration - quadratic_soft_max_duration <= 86400 seconds` #[prost(message, optional, tag="4")] pub quadratic_soft_max_duration: ::core::option::Option<::prost_types::Duration>, /// Cost per square hour incurred if the /// `quadratic_soft_max_duration` threshold is violated. /// /// The additional cost is 0 if the duration is under the threshold, /// otherwise the cost depends on the duration as follows: /// /// ``` /// cost_per_square_hour_after_quadratic_soft_max * /// (duration - quadratic_soft_max_duration)^2 /// ``` /// /// The cost must be nonnegative. #[prost(double, optional, tag="5")] pub cost_per_square_hour_after_quadratic_soft_max: ::core::option::Option<f64>, } /// Travel modes which can be used by vehicles. /// /// These should be a subset of the Google Maps Platform Routes Preferred API /// travel modes, see: /// <https://developers.google.com/maps/documentation/routes_preferred/reference/rest/Shared.Types/RouteTravelMode.> #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum TravelMode { /// Unspecified travel mode, equivalent to `DRIVING`. Unspecified = 0, /// Travel mode corresponding to driving directions (car, ...). Driving = 1, } /// Policy on how a vehicle can be unloaded. Applies only to shipments having /// both a pickup and a delivery. /// /// Other shipments are free to occur anywhere on the route independent of /// `unloading_policy`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum UnloadingPolicy { /// Unspecified unloading policy; deliveries must just occur after their /// corresponding pickups. Unspecified = 0, /// Deliveries must occur in reverse order of pickups LastInFirstOut = 1, /// Deliveries must occur in the same order as pickups FirstInFirstOut = 2, } } /// Time windows constrain the time of an event, such as the arrival time at a /// visit, or the start and end time of a vehicle. /// /// Hard time window bounds, `start_time` and `end_time`, enforce the earliest /// and latest time of the event, such that `start_time <= event_time <= /// end_time`. The soft time window lower bound, `soft_start_time`, expresses a /// preference for the event to happen at or after `soft_start_time` by incurring /// a cost proportional to how long before soft_start_time the event occurs. The /// soft time window upper bound, `soft_end_time`, expresses a preference for the /// event to happen at or before `soft_end_time` by incurring a cost proportional /// to how long after `soft_end_time` the event occurs. `start_time`, `end_time`, /// `soft_start_time` and `soft_end_time` should be within the global time limits /// (see \[ShipmentModel.global_start_time][google.cloud.optimization.v1.ShipmentModel.global_start_time\] and /// \[ShipmentModel.global_end_time][google.cloud.optimization.v1.ShipmentModel.global_end_time\]) and should respect: /// ``` /// 0 <= `start_time` <= `soft_start_time` <= `end_time` and /// 0 <= `start_time` <= `soft_end_time` <= `end_time`. /// ``` #[derive(Clone, PartialEq, ::prost::Message)] pub struct TimeWindow { /// The hard time window start time. If unspecified it will be set to /// `ShipmentModel.global_start_time`. #[prost(message, optional, tag="1")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// The hard time window end time. If unspecified it will be set to /// `ShipmentModel.global_end_time`. #[prost(message, optional, tag="2")] pub end_time: ::core::option::Option<::prost_types::Timestamp>, /// The soft start time of the time window. #[prost(message, optional, tag="3")] pub soft_start_time: ::core::option::Option<::prost_types::Timestamp>, /// The soft end time of the time window. #[prost(message, optional, tag="4")] pub soft_end_time: ::core::option::Option<::prost_types::Timestamp>, /// A cost per hour added to other costs in the model if the event occurs /// before soft_start_time, computed as: /// /// ``` /// max(0, soft_start_time - t.seconds) /// * cost_per_hour_before_soft_start_time / 3600, /// t being the time of the event. /// ``` /// /// This cost must be positive, and the field can only be set if /// soft_start_time has been set. #[prost(double, optional, tag="5")] pub cost_per_hour_before_soft_start_time: ::core::option::Option<f64>, /// A cost per hour added to other costs in the model if the event occurs after /// `soft_end_time`, computed as: /// /// ``` /// max(0, t.seconds - soft_end_time.seconds) /// * cost_per_hour_after_soft_end_time / 3600, /// t being the time of the event. /// ``` /// /// This cost must be positive, and the field can only be set if /// `soft_end_time` has been set. #[prost(double, optional, tag="6")] pub cost_per_hour_after_soft_end_time: ::core::option::Option<f64>, } /// Deprecated: Use \[Shipment.Load][\], \[Vehicle.LoadLimit][\] and \[ShipmentRoute.VehicleLoad][\] instead. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CapacityQuantity { #[prost(string, tag="1")] pub r#type: ::prost::alloc::string::String, #[prost(int64, tag="2")] pub value: i64, } /// Deprecated: Use \[Vehicle.LoadLimit.Interval][\] instead. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CapacityQuantityInterval { #[prost(string, tag="1")] pub r#type: ::prost::alloc::string::String, #[prost(int64, optional, tag="2")] pub min_value: ::core::option::Option<i64>, #[prost(int64, optional, tag="3")] pub max_value: ::core::option::Option<i64>, } /// A limit defining a maximum distance which can be traveled. It can be either /// hard or soft. /// /// If a soft limit is defined, both `soft_max_meters` and /// `cost_per_kilometer_above_soft_max` must be defined and be nonnegative. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DistanceLimit { /// A hard limit constraining the distance to be at most max_meters. The limit /// must be nonnegative. #[prost(int64, optional, tag="1")] pub max_meters: ::core::option::Option<i64>, /// A soft limit not enforcing a maximum distance limit, but when violated /// results in a cost which adds up to other costs defined in the model, /// with the same unit. /// /// If defined soft_max_meters must be less than max_meters and must be /// nonnegative. #[prost(int64, optional, tag="2")] pub soft_max_meters: ::core::option::Option<i64>, /// Cost per kilometer incurred if `soft_max_meters` limit is violated. The /// additional cost is 0 if the distance is under the limit, otherwise the /// formula used to compute the cost is the following: /// ``` /// (distance_meters - soft_max_meters) / 1000.0 * /// cost_per_kilometer_above_soft_max. /// ``` /// The cost must be nonnegative. #[prost(double, optional, tag="3")] pub cost_per_kilometer_above_soft_max: ::core::option::Option<f64>, } /// Specifies attributes of transitions between two consecutive visits on a /// route. Several `TransitionAttributes` may apply to the same transition: in /// that case, all extra costs add up and the strictest constraint or limit /// applies (following natural "AND" semantics). #[derive(Clone, PartialEq, ::prost::Message)] pub struct TransitionAttributes { /// Tags defining the set of (src->dst) transitions these attributes apply to. /// /// A source visit or vehicle start matches iff its /// \[VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags\] /// or \[Vehicle.start_tags][google.cloud.optimization.v1.Vehicle.start_tags\] /// either contains `src_tag` or does not contain `excluded_src_tag` (depending /// on which of these two fields is non-empty). #[prost(string, tag="1")] pub src_tag: ::prost::alloc::string::String, /// See `src_tag`. Exactly one of `src_tag` and `excluded_src_tag` must be /// non-empty. #[prost(string, tag="2")] pub excluded_src_tag: ::prost::alloc::string::String, /// A destination visit or vehicle end matches iff its /// \[VisitRequest.tags][google.cloud.optimization.v1.Shipment.VisitRequest.tags\] /// or \[Vehicle.end_tags][google.cloud.optimization.v1.Vehicle.end_tags\] either contains `dst_tag` or does not contain /// `excluded_dst_tag` (depending on which of these two fields is non-empty). #[prost(string, tag="3")] pub dst_tag: ::prost::alloc::string::String, /// See `dst_tag`. Exactly one of `dst_tag` and `excluded_dst_tag` must be /// non-empty. #[prost(string, tag="4")] pub excluded_dst_tag: ::prost::alloc::string::String, /// Specifies a cost for performing this transition. This is in the same unit /// as all other costs in the model and must not be negative. It is applied on /// top of all other existing costs. #[prost(double, tag="5")] pub cost: f64, /// Specifies a cost per kilometer applied to the distance traveled while /// performing this transition. It adds up to any /// \[Vehicle.cost_per_kilometer][google.cloud.optimization.v1.Vehicle.cost_per_kilometer\] specified on vehicles. #[prost(double, tag="6")] pub cost_per_kilometer: f64, /// Specifies a limit on the distance traveled while performing this /// transition. /// /// As of 2021/06, only soft limits are supported. #[prost(message, optional, tag="7")] pub distance_limit: ::core::option::Option<DistanceLimit>, /// Specifies a delay incurred when performing this transition. /// /// This delay always occurs *after* finishing the source visit and *before* /// starting the destination visit. #[prost(message, optional, tag="8")] pub delay: ::core::option::Option<::prost_types::Duration>, } /// Encapsulates a waypoint. Waypoints mark arrival and departure locations of /// VisitRequests, and start and end locations of Vehicles. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Waypoint { /// Indicates that the location of this waypoint is meant to have a preference /// for the vehicle to stop at a particular side of road. When you set this /// value, the route will pass through the location so that the vehicle can /// stop at the side of road that the location is biased towards from the /// center of the road. This option works only for the 'DRIVING' travel mode, /// and when the 'location_type' is set to 'location'. #[prost(bool, tag="3")] pub side_of_road: bool, /// Different ways to represent a location. #[prost(oneof="waypoint::LocationType", tags="1, 2")] pub location_type: ::core::option::Option<waypoint::LocationType>, } /// Nested message and enum types in `Waypoint`. pub mod waypoint { /// Different ways to represent a location. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum LocationType { /// A point specified using geographic coordinates, including an optional /// heading. #[prost(message, tag="1")] Location(super::Location), /// The POI Place ID associated with the waypoint. #[prost(string, tag="2")] PlaceId(::prost::alloc::string::String), } } /// Encapsulates a location (a geographic point, and an optional heading). #[derive(Clone, PartialEq, ::prost::Message)] pub struct Location { /// The waypoint's geographic coordinates. #[prost(message, optional, tag="1")] pub lat_lng: ::core::option::Option<super::super::super::r#type::LatLng>, /// The compass heading associated with the direction of the flow of traffic. /// This value is used to specify the side of the road to use for pickup and /// drop-off. Heading values can be from 0 to 360, where 0 specifies a heading /// of due North, 90 specifies a heading of due East, etc. #[prost(int32, optional, tag="2")] pub heading: ::core::option::Option<i32>, } /// Rules to generate time breaks for a vehicle (e.g. lunch breaks). A break /// is a contiguous period of time during which the vehicle remains idle at its /// current position and cannot perform any visit. A break may occur: /// /// * during the travel between two visits (which includes the time right /// before or right after a visit, but not in the middle of a visit), in /// which case it extends the corresponding transit time between the visits, /// * or before the vehicle start (the vehicle may not start in the middle of /// a break), in which case it does not affect the vehicle start time. /// * or after the vehicle end (ditto, with the vehicle end time). #[derive(Clone, PartialEq, ::prost::Message)] pub struct BreakRule { /// Sequence of breaks. See the `BreakRequest` message. #[prost(message, repeated, tag="1")] pub break_requests: ::prost::alloc::vec::Vec<break_rule::BreakRequest>, /// Several `FrequencyConstraint` may apply. They must all be satisfied by /// the `BreakRequest`s of this `BreakRule`. See `FrequencyConstraint`. #[prost(message, repeated, tag="2")] pub frequency_constraints: ::prost::alloc::vec::Vec<break_rule::FrequencyConstraint>, } /// Nested message and enum types in `BreakRule`. pub mod break_rule { /// The sequence of breaks (i.e. their number and order) that apply to each /// vehicle must be known beforehand. The repeated `BreakRequest`s define /// that sequence, in the order in which they must occur. Their time windows /// (`earliest_start_time` / `latest_start_time`) may overlap, but they must /// be compatible with the order (this is checked). #[derive(Clone, PartialEq, ::prost::Message)] pub struct BreakRequest { /// Required. Lower bound (inclusive) on the start of the break. #[prost(message, optional, tag="1")] pub earliest_start_time: ::core::option::Option<::prost_types::Timestamp>, /// Required. Upper bound (inclusive) on the start of the break. #[prost(message, optional, tag="2")] pub latest_start_time: ::core::option::Option<::prost_types::Timestamp>, /// Required. Minimum duration of the break. Must be positive. #[prost(message, optional, tag="3")] pub min_duration: ::core::option::Option<::prost_types::Duration>, } /// One may further constrain the frequency and duration of the breaks /// specified above, by enforcing a minimum break frequency, such as /// "There must be a break of at least 1 hour every 12 hours". Assuming that /// this can be interpreted as "Within any sliding time window of 12h, there /// must be at least one break of at least one hour", that example would /// translate to the following `FrequencyConstraint`: /// ``` /// { /// min_break_duration { seconds: 3600 } # 1 hour. /// max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). /// } /// ``` /// /// The timing and duration of the breaks in the solution will respect all /// such constraints, in addition to the time windows and minimum durations /// already specified in the `BreakRequest`. /// /// A `FrequencyConstraint` may in practice apply to non-consecutive breaks. /// For example, the following schedule honors the "1h every 12h" example: /// ``` /// 04:00 vehicle start /// .. performing travel and visits .. /// 09:00 1 hour break /// 10:00 end of the break /// .. performing travel and visits .. /// 12:00 20-min lunch break /// 12:20 end of the break /// .. performing travel and visits .. /// 21:00 1 hour break /// 22:00 end of the break /// .. performing travel and visits .. /// 23:59 vehicle end /// ``` #[derive(Clone, PartialEq, ::prost::Message)] pub struct FrequencyConstraint { /// Required. Minimum break duration for this constraint. Nonnegative. /// See description of `FrequencyConstraint`. #[prost(message, optional, tag="1")] pub min_break_duration: ::core::option::Option<::prost_types::Duration>, /// Required. Maximum allowed span of any interval of time in the route that does not /// include at least partially a break of `duration >= /// min_break_duration`. Must be positive. #[prost(message, optional, tag="2")] pub max_inter_break_duration: ::core::option::Option<::prost_types::Duration>, } } /// A vehicle's route can be decomposed, along the time axis, like this (we /// assume there are n visits): /// ``` /// | | | | | T\[2\], | | | /// | Transition | Visit #0 | | | V\[2\], | | | /// | #0 | aka | T\[1\] | V\[1\] | ... | V\[n-1\] | T\[n\] | /// | aka T\[0\] | V\[0\] | | | V\[n-2\],| | | /// | | | | | T\[n-1\] | | | /// ^ ^ ^ ^ ^ ^ ^ ^ /// vehicle V\[0\].start V\[0\].end V\[1\]. V\[1\]. V\[n\]. V\[n\]. vehicle /// start (arrival) (departure) start end start end end /// ``` /// Note that we make a difference between: /// /// * "punctual events", such as the vehicle start and end and each visit's start /// and end (aka arrival and departure). They happen at a given second. /// * "time intervals", such as the visits themselves, and the transition between /// visits. Though time intervals can sometimes have zero duration, i.e. start /// and end at the same second, they often have a positive duration. /// /// Invariants: /// /// * If there are n visits, there are n+1 transitions. /// * A visit is always surrounded by a transition before it (same index) and a /// transition after it (index + 1). /// * The vehicle start is always followed by transition #0. /// * The vehicle end is always preceded by transition #n. /// /// Zooming in, here is what happens during a `Transition` and a `Visit`: /// ``` /// ---+-------------------------------------+-----------------------------+--> /// | TRANSITION\[i\] | VISIT\[i\] | /// | | | /// | * TRAVEL: the vehicle moves from | PERFORM the visit: | /// | VISIT\[i-1\].departure_location to | | /// | VISIT\[i\].arrival_location, which | * Spend some time: | /// | takes a given travel duration | the "visit duration". | /// | and distance | | /// | | * Load or unload | /// | * BREAKS: the driver may have | some quantities from the | /// | breaks (e.g. lunch break). | vehicle: the "demand". | /// | | | /// | * WAIT: the driver/vehicle does | | /// | nothing. This can happen for | | /// | many reasons, for example when | | /// | the vehicle reaches the next | | /// | event's destination before the | | /// | start of its time window | | /// | | | /// | * DELAY: *right before* the next | | /// | arrival. E.g. the vehicle and/or | | /// | driver spends time unloading. | | /// | | | /// ---+-------------------------------------+-----------------------------+--> /// ^ ^ ^ /// V\[i-1\].end V\[i\].start V\[i\].end /// ``` /// Lastly, here is how the TRAVEL, BREAKS, DELAY and WAIT can be arranged /// during a transition. /// /// * They don't overlap. /// * The DELAY is unique and *must* be a contiguous period of time right /// before the next visit (or vehicle end). Thus, it suffice to know the /// delay duration to know its start and end time. /// * The BREAKS are contiguous, non-overlapping periods of time. The /// response specifies the start time and duration of each break. /// * TRAVEL and WAIT are "preemptable": they can be interrupted several times /// during this transition. Clients can assume that travel happens "as soon as /// possible" and that "wait" fills the remaining time. /// /// A (complex) example: /// ``` /// TRANSITION\[i\] /// --++-----+-----------------------------------------------------------++--> /// || | | | | | | || /// || T | B | T | | B | | D || /// || r | r | r | W | r | W | e || /// || a | e | a | a | e | a | l || /// || v | a | v | i | a | i | a || /// || e | k | e | t | k | t | y || /// || l | | l | | | | || /// || | | | | | | || /// --++-----------------------------------------------------------------++--> /// ``` #[derive(Clone, PartialEq, ::prost::Message)] pub struct ShipmentRoute { /// Vehicle performing the route, identified by its index in the source /// `ShipmentModel`. #[prost(int32, tag="1")] pub vehicle_index: i32, /// Label of the vehicle performing this route, equal to /// `ShipmentModel.vehicles(vehicle_index).label`, if specified. #[prost(string, tag="2")] pub vehicle_label: ::prost::alloc::string::String, /// Time at which the vehicle starts its route. #[prost(message, optional, tag="5")] pub vehicle_start_time: ::core::option::Option<::prost_types::Timestamp>, /// Time at which the vehicle finishes its route. #[prost(message, optional, tag="6")] pub vehicle_end_time: ::core::option::Option<::prost_types::Timestamp>, /// Ordered sequence of visits representing a route. /// visits\[i\] is the i-th visit in the route. /// If this field is empty, the vehicle is considered as unused. #[prost(message, repeated, tag="7")] pub visits: ::prost::alloc::vec::Vec<shipment_route::Visit>, /// Ordered list of transitions for the route. #[prost(message, repeated, tag="8")] pub transitions: ::prost::alloc::vec::Vec<shipment_route::Transition>, /// When /// \[OptimizeToursRequest.consider_road_traffic][google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic\], /// is set to true, this field indicates that inconsistencies in route timings /// are predicted using traffic-based travel duration estimates. There may be /// insufficient time to complete traffic-adjusted travel, delays, and breaks /// between visits, before the first visit, or after the last visit, while /// still satisfying the visit and vehicle time windows. For example, /// /// ```start_time(previous_visit) + duration(previous_visit) + /// travel_duration(previous_visit, next_visit) > start_time(next_visit)``` /// /// Arrival at next_visit will likely happen later than its current /// time window due the increased estimate of travel time /// `travel_duration(previous_visit, next_visit)` due to traffic. Also, a break /// may be forced to overlap with a visit due to an increase in travel time /// estimates and visit or break time window restrictions. #[prost(bool, tag="9")] pub has_traffic_infeasibilities: bool, /// The encoded polyline representation of the route. /// This field is only populated if /// \[OptimizeToursRequest.populate_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_polylines\] /// is set to true. #[prost(message, optional, tag="10")] pub route_polyline: ::core::option::Option<shipment_route::EncodedPolyline>, /// Breaks scheduled for the vehicle performing this route. /// The `breaks` sequence represents time intervals, each starting at the /// corresponding `start_time` and lasting `duration` seconds. #[prost(message, repeated, tag="11")] pub breaks: ::prost::alloc::vec::Vec<shipment_route::Break>, /// Duration, distance and load metrics for this route. The fields of /// \[AggregatedMetrics][google.cloud.optimization.v1.AggregatedMetrics\] are summed over all \[ShipmentRoute.transitions][google.cloud.optimization.v1.ShipmentRoute.transitions\] or /// \[ShipmentRoute.visits][google.cloud.optimization.v1.ShipmentRoute.visits\], depending on the context. #[prost(message, optional, tag="12")] pub metrics: ::core::option::Option<AggregatedMetrics>, /// Cost of the route, broken down by cost-related request fields. /// The keys are proto paths, relative to the input OptimizeToursRequest, e.g. /// "model.shipments.pickups.cost", and the values are the total cost /// generated by the corresponding cost field, aggregated over the whole route. /// In other words, costs\["model.shipments.pickups.cost"\] is the sum of all /// pickup costs over the route. All costs defined in the model are reported in /// detail here with the exception of costs related to TransitionAttributes /// that are only reported in an aggregated way as of 2022/01. #[prost(btree_map="string, double", tag="17")] pub route_costs: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, f64>, /// Total cost of the route. The sum of all costs in the cost map. #[prost(double, tag="18")] pub route_total_cost: f64, /// Deprecated: Use \[ShipmentRoute.Transition.loads][\] instead. /// Vehicle loads upon arrival at its end location, for each /// type specified in \[Vehicle.capacities][google.cloud.optimization.v1.Vehicle.capacities\], /// `start_load_intervals`, `end_load_intervals` or demands. Exception: we omit /// loads for quantity types unconstrained by intervals and that don't have any /// non-zero demand on the route. #[deprecated] #[prost(message, repeated, tag="13")] pub end_loads: ::prost::alloc::vec::Vec<CapacityQuantity>, /// Deprecated: Use \[ShipmentRoute.Transition][\] instead. /// Ordered list of travel steps for the route. #[deprecated] #[prost(message, repeated, tag="14")] pub travel_steps: ::prost::alloc::vec::Vec<shipment_route::TravelStep>, /// Deprecated: No longer used. /// This field will only be populated at the /// \[ShipmentRoute.Visit][google.cloud.optimization.v1.ShipmentRoute.Visit\] level. /// Extra detour time due to the shipments visited on the route. /// /// It is equal to `vehicle_end_time` - `vehicle_start_time` - travel duration /// from the vehicle's start_location to its `end_location`. #[deprecated] #[prost(message, optional, tag="15")] pub vehicle_detour: ::core::option::Option<::prost_types::Duration>, /// Deprecated: Use \[ShipmentRoute.Transition.delay_duration][\] instead. /// Delay occurring before the vehicle end. See /// \[TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay\]. #[deprecated] #[prost(message, optional, tag="16")] pub delay_before_vehicle_end: ::core::option::Option<shipment_route::Delay>, } /// Nested message and enum types in `ShipmentRoute`. pub mod shipment_route { /// Deprecated: Use \[ShipmentRoute.Transition.delay_duration][\] instead. /// Time interval spent on the route resulting from a /// \[TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay\]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Delay { /// Start of the delay. #[prost(message, optional, tag="1")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Duration of the delay. #[prost(message, optional, tag="2")] pub duration: ::core::option::Option<::prost_types::Duration>, } /// A visit performed during a route. This visit corresponds to a pickup or a /// delivery of a `Shipment`. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Visit { /// Index of the `shipments` field in the source \[ShipmentModel][google.cloud.optimization.v1.ShipmentModel\]. #[prost(int32, tag="1")] pub shipment_index: i32, /// If true the visit corresponds to a pickup of a `Shipment`. Otherwise, it /// corresponds to a delivery. #[prost(bool, tag="2")] pub is_pickup: bool, /// Index of `VisitRequest` in either the pickup or delivery field of the /// `Shipment` (see `is_pickup`). #[prost(int32, tag="3")] pub visit_request_index: i32, /// Time at which the visit starts. Note that the vehicle may arrive earlier /// than this at the visit location. Times are consistent with the /// `ShipmentModel`. #[prost(message, optional, tag="4")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Total visit load demand as the sum of the shipment and the visit request /// `load_demands`. The values are negative if the visit is a delivery. /// Demands are reported for the same types as the /// \[Transition.loads][google.cloud.optimization.v1.ShipmentRoute.Transition\] /// (see this field). #[prost(btree_map="string, message", tag="11")] pub load_demands: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, super::shipment::Load>, /// Extra detour time due to the shipments visited on the route before the /// visit and to the potential waiting time induced by time windows. /// If the visit is a delivery, the detour is computed from the corresponding /// pickup visit and is equal to: /// ``` /// start_time(delivery) - start_time(pickup) /// - (duration(pickup) + travel duration from the pickup location /// to the delivery location). /// ``` /// Otherwise, it is computed from the vehicle `start_location` and is equal /// to: /// ``` /// start_time - vehicle_start_time - travel duration from /// the vehicle's `start_location` to the visit. /// ``` #[prost(message, optional, tag="6")] pub detour: ::core::option::Option<::prost_types::Duration>, /// Copy of the corresponding `Shipment.label`, if specified in the /// `Shipment`. #[prost(string, tag="7")] pub shipment_label: ::prost::alloc::string::String, /// Copy of the corresponding /// \[VisitRequest.label][google.cloud.optimization.v1.Shipment.VisitRequest.label\], /// if specified in the `VisitRequest`. #[prost(string, tag="8")] pub visit_label: ::prost::alloc::string::String, /// Deprecated: Use \[ShipmentRoute.Transition.loads][\] instead. /// Vehicle loads upon arrival at the visit location, for each /// type specified in \[Vehicle.capacities][google.cloud.optimization.v1.Vehicle.capacities\], `start_load_intervals`, /// `end_load_intervals` or `demands`. /// /// Exception: we omit loads for quantity types unconstrained by intervals /// and that don't have any non-zero demand on the route. #[deprecated] #[prost(message, repeated, tag="9")] pub arrival_loads: ::prost::alloc::vec::Vec<super::CapacityQuantity>, /// Deprecated: Use \[ShipmentRoute.Transition.delay_duration][\] instead. #[deprecated] #[prost(message, optional, tag="10")] pub delay_before_start: ::core::option::Option<Delay>, /// Deprecated: Use \[Visit.load_demands][\] instead. #[deprecated] #[prost(message, repeated, tag="5")] pub demands: ::prost::alloc::vec::Vec<super::CapacityQuantity>, } /// Transition between two events on the route. See the description of /// \[ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute\]. /// /// If the vehicle does not have a `start_location` and/or `end_location`, the /// corresponding travel metrics are 0. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Transition { /// Travel duration during this transition. #[prost(message, optional, tag="1")] pub travel_duration: ::core::option::Option<::prost_types::Duration>, /// Distance traveled during the transition. #[prost(double, tag="2")] pub travel_distance_meters: f64, /// When traffic is requested via /// \[OptimizeToursRequest.consider_road_traffic\] /// \[google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic\], /// and the traffic info couldn't be retrieved for a `Transition`, this /// boolean is set to true. This may be temporary (rare hiccup in the /// realtime traffic servers) or permanent (no data for this location). #[prost(bool, tag="3")] pub traffic_info_unavailable: bool, /// Sum of the delay durations applied to this transition. If any, the delay /// starts exactly `delay_duration` seconds before the next event (visit or /// vehicle end). See /// \[TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay\]. #[prost(message, optional, tag="4")] pub delay_duration: ::core::option::Option<::prost_types::Duration>, /// Sum of the duration of the breaks occurring during this transition, if /// any. Details about each break's start time and duration are stored in /// \[ShipmentRoute.breaks][google.cloud.optimization.v1.ShipmentRoute.breaks\]. #[prost(message, optional, tag="5")] pub break_duration: ::core::option::Option<::prost_types::Duration>, /// Time spent waiting during this transition. Wait duration corresponds to /// idle time and does not include break time. Also note that this wait time /// may be split into several non-contiguous intervals. #[prost(message, optional, tag="6")] pub wait_duration: ::core::option::Option<::prost_types::Duration>, /// Total duration of the transition, provided for convenience. It is equal /// to: /// /// * next visit `start_time` (or `vehicle_end_time` if this is the last /// transition) - this transition's `start_time`; /// * if `ShipmentRoute.has_traffic_infeasibilities` is false, the following /// additionally holds: `total_duration = travel_duration + delay_duration /// + break_duration + wait_duration`. #[prost(message, optional, tag="7")] pub total_duration: ::core::option::Option<::prost_types::Duration>, /// Start time of this transition. #[prost(message, optional, tag="8")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// The encoded polyline representation of the route followed during the /// transition. /// This field is only populated if \[populate_transition_polylines\] /// \[google.cloud.optimization.v1.OptimizeToursRequest.populate_transition_polylines\] /// is set to true. #[prost(message, optional, tag="9")] pub route_polyline: ::core::option::Option<EncodedPolyline>, /// Vehicle loads during this transition, for each type that either appears /// in this vehicle's \[Vehicle.load_limits][google.cloud.optimization.v1.Vehicle.load_limits\], or that have non-zero /// \[Shipment.load_demands][google.cloud.optimization.v1.Shipment.load_demands\] on some shipment performed on this route. /// /// The loads during the first transition are the starting loads of the /// vehicle route. Then, after each visit, the visit's `load_demands` are /// either added or subtracted to get the next transition's loads, depending /// on whether the visit was a pickup or a delivery. #[prost(btree_map="string, message", tag="11")] pub vehicle_loads: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, VehicleLoad>, /// Deprecated: Use \[Transition.vehicle_loads][\] instead. #[deprecated] #[prost(message, repeated, tag="10")] pub loads: ::prost::alloc::vec::Vec<super::CapacityQuantity>, } /// Reports the actual load of the vehicle at some point along the route, /// for a given type (see \[Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads\]). #[derive(Clone, PartialEq, ::prost::Message)] pub struct VehicleLoad { /// The amount of load on the vehicle, for the given type. The unit of load /// is usually indicated by the type. See \[Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads\]. #[prost(int64, tag="1")] pub amount: i64, } /// The encoded representation of a polyline. More information on polyline /// encoding can be found here: /// <https://developers.google.com/maps/documentation/utilities/polylinealgorithm> /// <https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding.> #[derive(Clone, PartialEq, ::prost::Message)] pub struct EncodedPolyline { /// String representing encoded points of the polyline. #[prost(string, tag="1")] pub points: ::prost::alloc::string::String, } /// Data representing the execution of a break. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Break { /// Start time of a break. #[prost(message, optional, tag="1")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Duration of a break. #[prost(message, optional, tag="2")] pub duration: ::core::option::Option<::prost_types::Duration>, } /// Deprecated: Use \[ShipmentRoute.transitions][\] instead. /// Travel between each visit, along the route: from the /// vehicle's `start_location` to the first visit's `arrival_location`, then /// from the first visit's `departure_location` to the second visit's /// `arrival_location`, and so on until the vehicle's `end_location`. This /// accounts only for the actual travel between visits, not counting the /// waiting time, the time spent performing a visit, nor the distance covered /// during a visit. /// /// Invariant: `travel_steps_size() == visits_size() + 1`. /// /// If the vehicle does not have a start_ and/or end_location, the /// corresponding travel metrics are 0 and/or empty. #[derive(Clone, PartialEq, ::prost::Message)] pub struct TravelStep { /// Duration of the travel step. #[prost(message, optional, tag="1")] pub duration: ::core::option::Option<::prost_types::Duration>, /// Distance traveled during the step. #[prost(double, tag="2")] pub distance_meters: f64, /// When traffic is requested via /// \[OptimizeToursRequest.consider_road_traffic][google.cloud.optimization.v1.OptimizeToursRequest.consider_road_traffic\], /// and the traffic info couldn't be retrieved for a TravelStep, this boolean /// is set to true. This may be temporary (rare hiccup in the realtime /// traffic servers) or permanent (no data for this location). #[prost(bool, tag="3")] pub traffic_info_unavailable: bool, /// The encoded polyline representation of the route followed during the /// step. /// /// This field is only populated if /// \[OptimizeToursRequest.populate_travel_step_polylines][google.cloud.optimization.v1.OptimizeToursRequest.populate_travel_step_polylines\] /// is set to true. #[prost(message, optional, tag="4")] pub route_polyline: ::core::option::Option<EncodedPolyline>, } } /// Specifies details of unperformed shipments in a solution. For trivial cases /// and/or if we are able to identify the cause for skipping, we report the /// reason here. #[derive(Clone, PartialEq, ::prost::Message)] pub struct SkippedShipment { /// The index corresponds to the index of the shipment in the source /// `ShipmentModel`. #[prost(int32, tag="1")] pub index: i32, /// Copy of the corresponding \[Shipment.label][google.cloud.optimization.v1.Shipment.label\], if specified in the /// `Shipment`. #[prost(string, tag="2")] pub label: ::prost::alloc::string::String, /// A list of reasons that explain why the shipment was skipped. See comment /// above `Reason`. #[prost(message, repeated, tag="3")] pub reasons: ::prost::alloc::vec::Vec<skipped_shipment::Reason>, } /// Nested message and enum types in `SkippedShipment`. pub mod skipped_shipment { /// If we can explain why the shipment was skipped, reasons will be listed /// here. If the reason is not the same for all vehicles, `reason` will have /// more than 1 element. A skipped shipment cannot have duplicate reasons, /// i.e. where all fields are the same except for `example_vehicle_index`. /// Example: /// ``` /// reasons { /// code: DEMAND_EXCEEDS_VEHICLE_CAPACITY /// example_vehicle_index: 1 /// example_exceeded_capacity_type: "Apples" /// } /// reasons { /// code: DEMAND_EXCEEDS_VEHICLE_CAPACITY /// example_vehicle_index: 3 /// example_exceeded_capacity_type: "Pears" /// } /// reasons { /// code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT /// example_vehicle_index: 1 /// } /// ``` /// The skipped shipment is incompatible with all vehicles. The reasons may /// be different for all vehicles but at least one vehicle's "Apples" /// capacity would be exceeded (including vehicle 1), at least one vehicle's /// "Pears" capacity would be exceeded (including vehicle 3) and at least one /// vehicle's distance limit would be exceeded (including vehicle 1). #[derive(Clone, PartialEq, ::prost::Message)] pub struct Reason { /// Refer to the comments of Code. #[prost(enumeration="reason::Code", tag="1")] pub code: i32, /// If the reason is related to a shipment-vehicle incompatibility, this /// field provides the index of one relevant vehicle. #[prost(int32, optional, tag="2")] pub example_vehicle_index: ::core::option::Option<i32>, /// If the reason code is `DEMAND_EXCEEDS_VEHICLE_CAPACITY`, documents one /// capacity type that is exceeded. #[prost(string, tag="3")] pub example_exceeded_capacity_type: ::prost::alloc::string::String, } /// Nested message and enum types in `Reason`. pub mod reason { /// Code identifying the reason type. The order here is meaningless. In /// particular, it gives no indication of whether a given reason will /// appear before another in the solution, if both apply. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum Code { /// This should never be used. If we are unable to understand why a /// shipment was skipped, we simply return an empty set of reasons. Unspecified = 0, /// There is no vehicle in the model making all shipments infeasible. NoVehicle = 1, /// The demand of the shipment exceeds a vehicle's capacity for some /// capacity types, one of which is `example_exceeded_capacity_type`. DemandExceedsVehicleCapacity = 2, /// The minimum distance necessary to perform this shipment, i.e. from /// the vehicle's `start_location` to the shipment's pickup and/or delivery /// locations and to the vehicle's end location exceeds the vehicle's /// `route_distance_limit`. /// /// Note that for this computation we use the geodesic distances. CannotBePerformedWithinVehicleDistanceLimit = 3, /// The minimum time necessary to perform this shipment, including travel /// time, wait time and service time exceeds the vehicle's /// `route_duration_limit`. /// /// Note: travel time is computed in the best-case scenario, namely as /// geodesic distance x 36 m/s (roughly 130 km/hour). CannotBePerformedWithinVehicleDurationLimit = 4, /// Same as above but we only compare minimum travel time and the /// vehicle's `travel_duration_limit`. CannotBePerformedWithinVehicleTravelDurationLimit = 5, /// The vehicle cannot perform this shipment in the best-case scenario /// (see `CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT` for time /// computation) if it starts at its earliest start time: the total time /// would make the vehicle end after its latest end time. CannotBePerformedWithinVehicleTimeWindows = 6, /// The `allowed_vehicle_indices` field of the shipment is not empty and /// this vehicle does not belong to it. VehicleNotAllowed = 7, } } } /// Aggregated metrics for \[ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute\] (resp. for \[OptimizeToursResponse][google.cloud.optimization.v1.OptimizeToursResponse\] /// over all \[Transition][google.cloud.optimization.v1.ShipmentRoute.Transition\] /// and/or \[Visit][google.cloud.optimization.v1.ShipmentRoute.Visit\] (resp. over /// all \[ShipmentRoute][google.cloud.optimization.v1.ShipmentRoute\]) elements. #[derive(Clone, PartialEq, ::prost::Message)] pub struct AggregatedMetrics { /// Number of shipments performed. Note that a pickup and delivery pair only /// counts once. #[prost(int32, tag="1")] pub performed_shipment_count: i32, /// Total travel duration for a route or a solution. #[prost(message, optional, tag="2")] pub travel_duration: ::core::option::Option<::prost_types::Duration>, /// Total wait duration for a route or a solution. #[prost(message, optional, tag="3")] pub wait_duration: ::core::option::Option<::prost_types::Duration>, /// Total delay duration for a route or a solution. #[prost(message, optional, tag="4")] pub delay_duration: ::core::option::Option<::prost_types::Duration>, /// Total break duration for a route or a solution. #[prost(message, optional, tag="5")] pub break_duration: ::core::option::Option<::prost_types::Duration>, /// Total visit duration for a route or a solution. #[prost(message, optional, tag="6")] pub visit_duration: ::core::option::Option<::prost_types::Duration>, /// The total duration should be equal to the sum of all durations above. /// For routes, it also corresponds to \[ShipmentRoute.vehicle_end_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_end_time\] - /// \[ShipmentRoute.vehicle_start_time][google.cloud.optimization.v1.ShipmentRoute.vehicle_start_time\]. #[prost(message, optional, tag="7")] pub total_duration: ::core::option::Option<::prost_types::Duration>, /// Total travel distance for a route or a solution. #[prost(double, tag="8")] pub travel_distance_meters: f64, /// Maximum load achieved over the entire route (resp. solution), for each of /// the quantities on this route (resp. solution), computed as the maximum over /// all /// \[Transition.vehicle_loads][google.cloud.optimization.v1.ShipmentRoute.Transition.vehicle_loads\] /// (resp. /// \[ShipmentRoute.metrics.max_loads][google.cloud.optimization.v1.AggregatedMetrics.max_loads\]. #[prost(btree_map="string, message", tag="9")] pub max_loads: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, shipment_route::VehicleLoad>, /// Deprecated: Use \[ShipmentRoute.route_costs][\] and \[OptimizeToursResponse.Metrics.costs][\] instead. #[prost(btree_map="string, double", tag="10")] pub costs: ::prost::alloc::collections::BTreeMap<::prost::alloc::string::String, f64>, /// Deprecated: Use \[ShipmentRoute.route_total_cost][\] and \[OptimizeToursResponse.Metrics.total_cost][\] instead. #[deprecated] #[prost(double, tag="11")] pub total_cost: f64, } /// Solution injected in the request including information about which visits /// must be constrained and how they must be constrained. #[derive(Clone, PartialEq, ::prost::Message)] pub struct InjectedSolutionConstraint { /// Routes of the solution to inject. Some routes may be omitted from the /// original solution. The routes and skipped shipments must satisfy the basic /// validity assumptions listed for `injected_first_solution_routes`. #[prost(message, repeated, tag="1")] pub routes: ::prost::alloc::vec::Vec<ShipmentRoute>, /// Skipped shipments of the solution to inject. Some may be omitted from the /// original solution. See the `routes` field. #[prost(message, repeated, tag="2")] pub skipped_shipments: ::prost::alloc::vec::Vec<SkippedShipment>, /// For zero or more groups of vehicles, specifies when and how much to relax /// constraints. If this field is empty, all non-empty vehicle routes are /// fully constrained. #[prost(message, repeated, tag="3")] pub constraint_relaxations: ::prost::alloc::vec::Vec<injected_solution_constraint::ConstraintRelaxation>, } /// Nested message and enum types in `InjectedSolutionConstraint`. pub mod injected_solution_constraint { /// For a group of vehicles, specifies at what threshold(s) constraints on /// visits will be relaxed and to which level. Shipments listed in /// the `skipped_shipment` field are constrained to be skipped; i.e., they /// cannot be performed. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ConstraintRelaxation { /// All the visit constraint relaxations that will apply to visits on /// routes with vehicles in `vehicle_indices`. #[prost(message, repeated, tag="1")] pub relaxations: ::prost::alloc::vec::Vec<constraint_relaxation::Relaxation>, /// Specifies the vehicle indices to which the visit constraint /// `relaxations` apply. If empty, this is considered the default and the /// `relaxations` apply to all vehicles that are not specified in other /// `constraint_relaxations`. There can be at most one default, i.e., at /// most one constraint relaxation field is allowed empty /// `vehicle_indices`. A vehicle index can only be listed once, even within /// several `constraint_relaxations`. /// /// A vehicle index is mapped the same as \[ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index\], if /// `interpret_injected_solutions_using_labels` is true (see `fields` /// comment). #[prost(int32, repeated, tag="2")] pub vehicle_indices: ::prost::alloc::vec::Vec<i32>, } /// Nested message and enum types in `ConstraintRelaxation`. pub mod constraint_relaxation { /// If `relaxations` is empty, the start time and sequence of all visits /// on `routes` are fully constrained and no new visits may be inserted or /// added to those routes. Also, a vehicle's start and end time in /// `routes` is fully constrained, unless the vehicle is empty (i.e., has no /// visits and has `used_if_route_is_empty` set to false in the model). /// /// `relaxations(i).level` specifies the constraint relaxation level applied /// to a visit #j that satisfies: /// /// * `route.visits(j).start_time >= relaxations(i).threshold_time` AND /// * `j + 1 >= relaxations(i).threshold_visit_count` /// /// Similarly, the vehicle start is relaxed to `relaxations(i).level` if it /// satisfies: /// /// * `vehicle_start_time >= relaxations(i).threshold_time` AND /// * `relaxations(i).threshold_visit_count == 0` /// and the vehicle end is relaxed to `relaxations(i).level` if it satisfies: /// * `vehicle_end_time >= relaxations(i).threshold_time` AND /// * `route.visits_size() + 1 >= relaxations(i).threshold_visit_count` /// /// To apply a relaxation level if a visit meets the `threshold_visit_count` /// OR the `threshold_time` add two `relaxations` with the same `level`: /// one with only `threshold_visit_count` set and the other with only /// `threshold_time` set. If a visit satisfies the conditions of multiple /// `relaxations`, the most relaxed level applies. As a result, from the /// vehicle start through the route visits in order to the vehicle end, the /// relaxation level becomes more relaxed: i.e., the relaxation level is /// non-decreasing as the route progresses. /// /// The timing and sequence of route visits that do not satisfy the /// threshold conditions of any `relaxations` are fully constrained /// and no visits may be inserted into these sequences. Also, if a /// vehicle start or end does not satisfy the conditions of any /// relaxation the time is fixed, unless the vehicle is empty. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Relaxation { /// The constraint relaxation level that applies when the conditions /// at or after `threshold_time` AND at least `threshold_visit_count` are /// satified. #[prost(enumeration="relaxation::Level", tag="1")] pub level: i32, /// The time at or after which the relaxation `level` may be applied. #[prost(message, optional, tag="2")] pub threshold_time: ::core::option::Option<::prost_types::Timestamp>, /// The number of visits at or after which the relaxation `level` may be /// applied. If `threshold_visit_count` is 0 (or unset), the `level` may be /// applied directly at the vehicle start. /// /// If it is `route.visits_size() + 1`, the `level` may only be applied to /// the vehicle end. If it is more than `route.visits_size() + 1`, /// `level` is not applied at all for that route. #[prost(int32, tag="3")] pub threshold_visit_count: i32, } /// Nested message and enum types in `Relaxation`. pub mod relaxation { /// Expresses the different constraint relaxation levels, which are /// applied for a visit and those that follow when it satifies the /// threshold conditions. /// /// The enumeration below is in order of increasing relaxation. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum Level { /// Implicit default relaxation level: no constraints are relaxed, /// i.e., all visits are fully constrained. /// /// This value must not be explicly used in `level`. Unspecified = 0, /// Visit start times and vehicle start/end times will be relaxed, but /// each visit remains bound to the same vehicle and the visit sequence /// must be observed: no visit can be inserted between them or before /// them. RelaxVisitTimesAfterThreshold = 1, /// Same as `RELAX_VISIT_TIMES_AFTER_THRESHOLD`, but the visit sequence /// is also relaxed: visits remain simply bound to their vehicle. RelaxVisitTimesAndSequenceAfterThreshold = 2, /// Same as `RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD`, but the /// vehicle is also relaxed: visits are completely free at or after the /// threshold time and can potentially become unperformed. RelaxAllAfterThreshold = 3, } } } } /// Describes an error encountered when validating an `OptimizeToursRequest`. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OptimizeToursValidationError { /// A validation error is defined by the pair (`code`, `display_name`) which /// are always present. /// /// Other fields (below) provide more context about the error. /// /// *MULTIPLE ERRORS*: /// When there are multiple errors, the validation process tries to output /// several of them. Much like a compiler, this is an imperfect process. Some /// validation errors will be "fatal", meaning that they stop the entire /// validation process. This is the case for `display_name="UNSPECIFIED"` /// errors, among others. Some may cause the validation process to skip other /// errors. /// /// *STABILITY*: /// `code` and `display_name` should be very stable. But new codes and /// display names may appear over time, which may cause a given (invalid) /// request to yield a different (`code`, `display_name`) pair because the new /// error hid the old one (see "MULTIPLE ERRORS"). /// /// *REFERENCE*: A list of all (code, name) pairs: /// /// * UNSPECIFIED = 0; /// * VALIDATION_TIMEOUT_ERROR = 10; Validation couldn't be completed within /// the deadline. /// /// * REQUEST_OPTIONS_ERROR = 12; /// * REQUEST_OPTIONS_INVALID_SOLVING_MODE = 1201; /// * REQUEST_OPTIONS_INVALID_MAX_VALIDATION_ERRORS = 1203; /// * REQUEST_OPTIONS_INVALID_GEODESIC_METERS_PER_SECOND = 1204; /// * REQUEST_OPTIONS_GEODESIC_METERS_PER_SECOND_TOO_SMALL = 1205; /// * REQUEST_OPTIONS_MISSING_GEODESIC_METERS_PER_SECOND = 1206; /// * REQUEST_OPTIONS_POPULATE_PATHFINDER_TRIPS_AND_GEODESIC_DISTANCE /// = 1207; /// * REQUEST_OPTIONS_COST_MODEL_OPTIONS_AND_GEODESIC_DISTANCE = 1208; /// * REQUEST_OPTIONS_TRAVEL_MODE_INCOMPATIBLE_WITH_TRAFFIC = 1211; /// * REQUEST_OPTIONS_MULTIPLE_TRAFFIC_FLAVORS = 1212; /// * REQUEST_OPTIONS_INVALID_TRAFFIC_FLAVOR = 1213; /// * REQUEST_OPTIONS_TRAFFIC_ENABLED_WITHOUT_GLOBAL_START_TIME = 1214; /// * REQUEST_OPTIONS_TRAFFIC_ENABLED_WITH_PRECEDENCES = 1215; /// * REQUEST_OPTIONS_TRAFFIC_PREFILL_MODE_INVALID = 1216; /// * REQUEST_OPTIONS_TRAFFIC_PREFILL_ENABLED_WITHOUT_TRAFFIC = 1217; /// * INJECTED_SOLUTION_ERROR = 20; /// * INJECTED_SOLUTION_MISSING_LABEL = 2000; /// * INJECTED_SOLUTION_DUPLICATE_LABEL = 2001; /// * INJECTED_SOLUTION_AMBIGUOUS_INDEX = 2002; /// * SHIPMENT_MODEL_ERROR = 22; /// * SHIPMENT_MODEL_TOO_LARGE = 2200; /// * SHIPMENT_MODEL_TOO_MANY_CAPACITY_TYPES = 2201; /// * SHIPMENT_MODEL_GLOBAL_START_TIME_NEGATIVE_OR_NAN = 2202; /// * SHIPMENT_MODEL_GLOBAL_END_TIME_TOO_LARGE_OR_NAN = 2203; /// * SHIPMENT_MODEL_GLOBAL_START_TIME_AFTER_GLOBAL_END_TIME = 2204; /// * SHIPMENT_MODEL_GLOBAL_DURATION_TOO_LONG = 2205; /// * INDEX_ERROR = 24; /// * TAG_ERROR = 26; /// * TIME_WINDOW_ERROR = 28; /// * TIME_WINDOW_INVALID_START_TIME = 2800; /// * TIME_WINDOW_INVALID_END_TIME = 2801; /// * TIME_WINDOW_INVALID_SOFT_START_TIME = 2802; /// * TIME_WINDOW_INVALID_SOFT_END_TIME = 2803; /// * TIME_WINDOW_OUTSIDE_GLOBAL_TIME_WINDOW = 2804; /// * TIME_WINDOW_START_TIME_AFTER_END_TIME = 2805; /// * TIME_WINDOW_INVALID_COST_PER_HOUR_BEFORE_SOFT_START_TIME = 2806; /// * TIME_WINDOW_INVALID_COST_PER_HOUR_AFTER_SOFT_END_TIME = 2807; /// * TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_WITHOUT_SOFT_START_TIME /// = 2808; /// * TIME_WINDOW_COST_AFTER_SOFT_END_TIME_WITHOUT_SOFT_END_TIME = 2809; /// * TIME_WINDOW_SOFT_START_TIME_WITHOUT_COST_BEFORE_SOFT_START_TIME /// = 2810; /// * TIME_WINDOW_SOFT_END_TIME_WITHOUT_COST_AFTER_SOFT_END_TIME = 2811; /// * TIME_WINDOW_OVERLAPPING_ADJACENT_OR_EARLIER_THAN_PREVIOUS = 2812; /// * TIME_WINDOW_START_TIME_AFTER_SOFT_START_TIME = 2813; /// * TIME_WINDOW_SOFT_START_TIME_AFTER_END_TIME = 2814; /// * TIME_WINDOW_START_TIME_AFTER_SOFT_END_TIME = 2815; /// * TIME_WINDOW_SOFT_END_TIME_AFTER_END_TIME = 2816; /// * TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_SET_AND_MULTIPLE_WINDOWS /// = 2817; /// * TIME_WINDOW_COST_AFTER_SOFT_END_TIME_SET_AND_MULTIPLE_WINDOWS = 2818; /// * TRANSITION_ATTRIBUTES_ERROR = 30; /// * TRANSITION_ATTRIBUTES_INVALID_COST = 3000; /// * TRANSITION_ATTRIBUTES_INVALID_COST_PER_KILOMETER = 3001; /// * TRANSITION_ATTRIBUTES_DUPLICATE_TAG_PAIR = 3002; /// * TRANSITION_ATTRIBUTES_DISTANCE_LIMIT_MAX_METERS_UNSUPPORTED = 3003; /// * TRANSITION_ATTRIBUTES_UNSPECIFIED_SOURCE_TAGS = 3004; /// * TRANSITION_ATTRIBUTES_CONFLICTING_SOURCE_TAGS_FIELDS = 3005; /// * TRANSITION_ATTRIBUTES_UNSPECIFIED_DESTINATION_TAGS = 3006; /// * TRANSITION_ATTRIBUTES_CONFLICTING_DESTINATION_TAGS_FIELDS = 3007; /// * TRANSITION_ATTRIBUTES_DELAY_DURATION_NEGATIVE_OR_NAN = 3008; /// * TRANSITION_ATTRIBUTES_DELAY_DURATION_EXCEEDS_GLOBAL_DURATION = 3009; /// * AMOUNT_ERROR = 31; /// * AMOUNT_NEGATIVE_VALUE = 3100; /// * LOAD_LIMIT_ERROR = 33; /// * LOAD_LIMIT_INVALID_COST_ABOVE_SOFT_MAX = 3303; /// * LOAD_LIMIT_SOFT_MAX_WITHOUT_COST_ABOVE_SOFT_MAX = 3304; /// * LOAD_LIMIT_COST_ABOVE_SOFT_MAX_WITHOUT_SOFT_MAX = 3305; /// * LOAD_LIMIT_NEGATIVE_SOFT_MAX = 3306; /// * LOAD_LIMIT_MIXED_DEMAND_TYPE = 3307; /// * LOAD_LIMIT_MAX_LOAD_NEGATIVE_VALUE = 3308; /// * LOAD_LIMIT_SOFT_MAX_ABOVE_MAX = 3309; /// * INTERVAL_ERROR = 34; /// * INTERVAL_MIN_EXCEEDS_MAX = 3401; /// * INTERVAL_NEGATIVE_MIN = 3402; /// * INTERVAL_NEGATIVE_MAX = 3403; /// * INTERVAL_MIN_EXCEEDS_CAPACITY = 3404; /// * INTERVAL_MAX_EXCEEDS_CAPACITY = 3405; /// * DISTANCE_LIMIT_ERROR = 36; /// * DISTANCE_LIMIT_INVALID_COST_AFTER_SOFT_MAX = 3601; /// * DISTANCE_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = 3602; /// * DISTANCE_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = 3603; /// * DISTANCE_LIMIT_NEGATIVE_MAX = 3604; /// * DISTANCE_LIMIT_NEGATIVE_SOFT_MAX = 3605; /// * DISTANCE_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3606; /// * DURATION_LIMIT_ERROR = 38; /// * DURATION_LIMIT_MAX_DURATION_NEGATIVE_OR_NAN = 3800; /// * DURATION_LIMIT_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = 3801; /// * DURATION_LIMIT_INVALID_COST_PER_HOUR_AFTER_SOFT_MAX = 3802; /// * DURATION_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = 3803; /// * DURATION_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = 3804; /// * DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = 3805; /// * DURATION_LIMIT_INVALID_COST_AFTER_QUADRATIC_SOFT_MAX = 3806; /// * DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_COST_PER_SQUARE_HOUR /// = 3807; /// * DURATION_LIMIT_COST_PER_SQUARE_HOUR_WITHOUT_QUADRATIC_SOFT_MAX /// = 3808; /// * DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_MAX = 3809; /// * DURATION_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3810; /// * DURATION_LIMIT_QUADRATIC_SOFT_MAX_LARGER_THAN_MAX = 3811; /// * DURATION_LIMIT_DIFF_BETWEEN_MAX_AND_QUADRATIC_SOFT_MAX_TOO_LARGE /// = 3812; /// * DURATION_LIMIT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = 3813; /// * DURATION_LIMIT_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = 3814; /// * DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION /// = 3815; /// * SHIPMENT_ERROR = 40; /// * SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_NEGATIVE_OR_NAN = 4000; /// * SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION /// = 4001; /// * SHIPMENT_PD_TIME_LIMIT_DURATION_NEGATIVE_OR_NAN = 4002; /// * SHIPMENT_PD_TIME_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION = 4003; /// * SHIPMENT_EMPTY_SHIPMENT_TYPE = 4004; /// * SHIPMENT_NO_PICKUP_NO_DELIVERY = 4005; /// * SHIPMENT_INVALID_PENALTY_COST = 4006; /// * SHIPMENT_ALLOWED_VEHICLE_INDEX_OUT_OF_BOUNDS = 4007; /// * SHIPMENT_DUPLICATE_ALLOWED_VEHICLE_INDEX = 4008; /// * SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITHOUT_INDEX = 4009; /// * SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITH_INDEX = 4010; /// * SHIPMENT_INVALID_COST_FOR_VEHICLE = 4011; /// * SHIPMENT_COST_FOR_VEHICLE_INDEX_OUT_OF_BOUNDS = 4012; /// * SHIPMENT_DUPLICATE_COST_FOR_VEHICLE_INDEX = 4013; /// * SHIPMENT_DETOUR_WITHOUT_PICKUP_AND_DELIVERY = 4014; /// * VEHICLE_ERROR = 42; /// * VEHICLE_EMPTY_REQUIRED_OPERATOR_TYPE = 4200; /// * VEHICLE_DUPLICATE_REQUIRED_OPERATOR_TYPE = 4201; /// * VEHICLE_NO_OPERATOR_WITH_REQUIRED_OPERATOR_TYPE = 4202; /// * VEHICLE_EMPTY_START_TAG = 4203; /// * VEHICLE_DUPLICATE_START_TAG = 4204; /// * VEHICLE_EMPTY_END_TAG = 4205; /// * VEHICLE_DUPLICATE_END_TAG = 4206; /// * VEHICLE_EXTRA_VISIT_DURATION_NEGATIVE_OR_NAN = 4207; /// * VEHICLE_EXTRA_VISIT_DURATION_EXCEEDS_GLOBAL_DURATION = 4208; /// * VEHICLE_EXTRA_VISIT_DURATION_EMPTY_KEY = 4209; /// * VEHICLE_FIRST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4210; /// * VEHICLE_FIRST_SHIPMENT_IGNORED = 4211; /// * VEHICLE_FIRST_SHIPMENT_NOT_BOUND = 4212; /// * VEHICLE_LAST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4213; /// * VEHICLE_LAST_SHIPMENT_IGNORED = 4214; /// * VEHICLE_LAST_SHIPMENT_NOT_BOUND = 4215; /// * VEHICLE_IGNORED_WITH_USED_IF_ROUTE_IS_EMPTY = 4216; /// * VEHICLE_INVALID_COST_PER_KILOMETER = 4217; /// * VEHICLE_INVALID_COST_PER_HOUR = 4218; /// * VEHICLE_INVALID_COST_PER_TRAVELED_HOUR = 4219; /// * VEHICLE_INVALID_FIXED_COST = 4220; /// * VEHICLE_INVALID_TRAVEL_DURATION_MULTIPLE = 4221; /// * VEHICLE_MINIMUM_DURATION_LONGER_THAN_DURATION_LIMIT = 4222; /// * VISIT_REQUEST_ERROR = 44; /// * VISIT_REQUEST_EMPTY_TAG = 4400; /// * VISIT_REQUEST_DUPLICATE_TAG = 4401; /// * VISIT_REQUEST_DURATION_NEGATIVE_OR_NAN = 4404; /// * VISIT_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4405; /// * PRECEDENCE_ERROR = 46; /// * BREAK_ERROR = 48; /// * BREAK_RULE_EMPTY = 4800; /// * BREAK_REQUEST_UNSPECIFIED_DURATION = 4801; /// * BREAK_REQUEST_UNSPECIFIED_EARLIEST_START_TIME = 4802; /// * BREAK_REQUEST_UNSPECIFIED_LATEST_START_TIME = 4803; /// * BREAK_REQUEST_DURATION_NEGATIVE_OR_NAN = 4804; = 4804; /// * BREAK_REQUEST_LATEST_START_TIME_BEFORE_EARLIEST_START_TIME = 4805; /// * BREAK_REQUEST_EARLIEST_START_TIME_BEFORE_GLOBAL_START_TIME = 4806; /// * BREAK_REQUEST_LATEST_END_TIME_AFTER_GLOBAL_END_TIME = 4807; /// * BREAK_REQUEST_NON_SCHEDULABLE = 4808; /// * BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_NEGATIVE_OR_NAN = 4809; /// * BREAK_FREQUENCY_MIN_BREAK_DURATION_NEGATIVE_OR_NAN = 4810; /// * BREAK_FREQUENCY_MIN_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION = 4811; /// * BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION /// = 4812; /// * BREAK_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4813; /// * BREAK_FREQUENCY_MISSING_MAX_INTER_BREAK_DURATION = 4814; /// * BREAK_FREQUENCY_MISSING_MIN_BREAK_DURATION = 4815; /// * SHIPMENT_TYPE_INCOMPATIBILITY_ERROR = 50; /// * SHIPMENT_TYPE_INCOMPATIBILITY_EMPTY_TYPE = 5001; /// * SHIPMENT_TYPE_INCOMPATIBILITY_LESS_THAN_TWO_TYPES = 5002; /// * SHIPMENT_TYPE_INCOMPATIBILITY_DUPLICATE_TYPE = 5003; /// * SHIPMENT_TYPE_INCOMPATIBILITY_INVALID_INCOMPATIBILITY_MODE = 5004; /// * SHIPMENT_TYPE_INCOMPATIBILITY_TOO_MANY_INCOMPATIBILITIES = 5005; /// * SHIPMENT_TYPE_REQUIREMENT_ERROR = 52; /// * SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE = 52001; /// * SHIPMENT_TYPE_REQUIREMENT_NO_DEPENDENT_TYPE = 52002; /// * SHIPMENT_TYPE_REQUIREMENT_INVALID_REQUIREMENT_MODE = 52003; /// * SHIPMENT_TYPE_REQUIREMENT_TOO_MANY_REQUIREMENTS = 52004; /// * SHIPMENT_TYPE_REQUIREMENT_EMPTY_REQUIRED_TYPE = 52005; /// * SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_REQUIRED_TYPE = 52006; /// * SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE_FOUND = 52007; /// * SHIPMENT_TYPE_REQUIREMENT_EMPTY_DEPENDENT_TYPE = 52008; /// * SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_DEPENDENT_TYPE = 52009; /// * SHIPMENT_TYPE_REQUIREMENT_SELF_DEPENDENT_TYPE = 52010; /// * SHIPMENT_TYPE_REQUIREMENT_GRAPH_HAS_CYCLES = 52011; /// * VEHICLE_OPERATOR_ERROR = 54; /// * VEHICLE_OPERATOR_EMPTY_TYPE = 5400; /// * VEHICLE_OPERATOR_MULTIPLE_START_TIME_WINDOWS = 5401; /// * VEHICLE_OPERATOR_SOFT_START_TIME_WINDOW = 5402; /// * VEHICLE_OPERATOR_MULTIPLE_END_TIME_WINDOWS = 5403; /// * VEHICLE_OPERATOR_SOFT_END_TIME_WINDOW = 5404; /// * DURATION_SECONDS_MATRIX_ERROR = 56; /// * DURATION_SECONDS_MATRIX_DURATION_NEGATIVE_OR_NAN = 5600; /// * DURATION_SECONDS_MATRIX_DURATION_EXCEEDS_GLOBAL_DURATION = 5601; /// * GRAPH_ARC_ERROR = 58; /// * GRAPH_ARC_DURATION_NEGATIVE_OR_NAN = 5800; /// * GRAPH_ARC_DURATION_EXCEEDS_GLOBAL_DURATION = 5801; #[prost(int32, tag="1")] pub code: i32, /// The error display name. #[prost(string, tag="2")] pub display_name: ::prost::alloc::string::String, /// An error context may involve 0, 1 (most of the time) or more fields. For /// example, referring to vehicle #4 and shipment #2's first pickup can be /// done as follows: /// ``` /// fields { name: "vehicles" index: 4} /// fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} } /// ``` /// Note, however, that the cardinality of `fields` should not change for a /// given error code. #[prost(message, repeated, tag="3")] pub fields: ::prost::alloc::vec::Vec<optimize_tours_validation_error::FieldReference>, /// Human-readable string describing the error. There is a 1:1 mapping /// between `code` and `error_message` (when code != "UNSPECIFIED"). /// /// *STABILITY*: Not stable: the error message associated to a given `code` may /// change (hopefully to clarify it) over time. Please rely on the /// `display_name` and `code` instead. #[prost(string, tag="4")] pub error_message: ::prost::alloc::string::String, /// May contain the value(s) of the field(s). This is not always available. You /// should absolutely not rely on it and use it only for manual model /// debugging. #[prost(string, tag="5")] pub offending_values: ::prost::alloc::string::String, } /// Nested message and enum types in `OptimizeToursValidationError`. pub mod optimize_tours_validation_error { /// Specifies a context for the validation error. A `FieldReference` always /// refers to a given field in this file and follows the same hierarchical /// structure. For example, we may specify element #2 of `start_time_windows` /// of vehicle #5 using: /// ``` /// name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 } /// ``` /// We however omit top-level entities such as `OptimizeToursRequest` or /// `ShipmentModel` to avoid crowding the message. #[derive(Clone, PartialEq, ::prost::Message)] pub struct FieldReference { /// Name of the field, e.g., "vehicles". #[prost(string, tag="1")] pub name: ::prost::alloc::string::String, /// Recursively nested sub-field, if needed. #[prost(message, optional, boxed, tag="3")] pub sub_field: ::core::option::Option<::prost::alloc::boxed::Box<FieldReference>>, #[prost(oneof="field_reference::IndexOrKey", tags="2, 4")] pub index_or_key: ::core::option::Option<field_reference::IndexOrKey>, } /// Nested message and enum types in `FieldReference`. pub mod field_reference { #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum IndexOrKey { /// Index of the field if repeated. #[prost(int32, tag="2")] Index(i32), /// Key if the field is a map. #[prost(string, tag="4")] Key(::prost::alloc::string::String), } } } /// Generated client implementations. pub mod fleet_routing_client { #![allow(unused_variables, dead_code, missing_docs, clippy::let_unit_value)] use tonic::codegen::*; /// A service for optimizing vehicle tours. /// /// Validity of certain types of fields: /// /// * `google.protobuf.Timestamp` /// * Times are in Unix time: seconds since 1970-01-01T00:00:00+00:00. /// * seconds must be in [0, 253402300799], /// i.e. in [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. /// * nanos must be unset or set to 0. /// * `google.protobuf.Duration` /// * seconds must be in [0, 253402300799], /// i.e. in [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. /// * nanos must be unset or set to 0. /// * `google.type.LatLng` /// * latitude must be in [-90.0, 90.0]. /// * longitude must be in [-180.0, 180.0]. /// * at least one of latitude and longitude must be non-zero. #[derive(Debug, Clone)] pub struct FleetRoutingClient<T> { inner: tonic::client::Grpc<T>, } impl<T> FleetRoutingClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::Error: Into<StdError>, T::ResponseBody: Body<Data = Bytes> + Send + 'static, <T::ResponseBody as Body>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor<F>( inner: T, interceptor: F, ) -> FleetRoutingClient<InterceptedService<T, F>> where F: tonic::service::Interceptor, T::ResponseBody: Default, T: tonic::codegen::Service< http::Request<tonic::body::BoxBody>, Response = http::Response< <T as tonic::client::GrpcService<tonic::body::BoxBody>>::ResponseBody, >, >, <T as tonic::codegen::Service< http::Request<tonic::body::BoxBody>, >>::Error: Into<StdError> + Send + Sync, { FleetRoutingClient::new(InterceptedService::new(inner, interceptor)) } /// Compress requests with `gzip`. /// /// This requires the server to support it otherwise it might respond with an /// error. #[must_use] pub fn send_gzip(mut self) -> Self { self.inner = self.inner.send_gzip(); self } /// Enable decompressing responses with `gzip`. #[must_use] pub fn accept_gzip(mut self) -> Self { self.inner = self.inner.accept_gzip(); self } /// Sends an `OptimizeToursRequest` containing a `ShipmentModel` and returns an /// `OptimizeToursResponse` containing `ShipmentRoute`s, which are a set of /// routes to be performed by vehicles minimizing the overall cost. /// /// A `ShipmentModel` model consists mainly of `Shipment`s that need to be /// carried out and `Vehicle`s that can be used to transport the `Shipment`s. /// The `ShipmentRoute`s assign `Shipment`s to `Vehicle`s. More specifically, /// they assign a series of `Visit`s to each vehicle, where a `Visit` /// corresponds to a `VisitRequest`, which is a pickup or delivery for a /// `Shipment`. /// /// The goal is to provide an assignment of `ShipmentRoute`s to `Vehicle`s that /// minimizes the total cost where cost has many components defined in the /// `ShipmentModel`. pub async fn optimize_tours( &mut self, request: impl tonic::IntoRequest<super::OptimizeToursRequest>, ) -> Result<tonic::Response<super::OptimizeToursResponse>, tonic::Status> { self.inner .ready() .await .map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.optimization.v1.FleetRouting/OptimizeTours", ); self.inner.unary(request.into_request(), path, codec).await } /// Optimizes vehicle tours for one or more `OptimizeToursRequest` /// messages as a batch. /// /// This method is a Long Running Operation (LRO). The inputs for optimization /// (`OptimizeToursRequest` messages) and outputs (`OptimizeToursResponse` /// messages) are read/written from/to Cloud Storage in user-specified /// format. Like the `OptimizeTours` method, each `OptimizeToursRequest` /// contains a `ShipmentModel` and returns an `OptimizeToursResponse` /// containing `ShipmentRoute`s, which are a set of routes to be performed by /// vehicles minimizing the overall cost. pub async fn batch_optimize_tours( &mut self, request: impl tonic::IntoRequest<super::BatchOptimizeToursRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner .ready() .await .map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.optimization.v1.FleetRouting/BatchOptimizeTours", ); self.inner.unary(request.into_request(), path, codec).await } } }
schema.py
import graphene from ..core.fields import PrefetchingConnectionField from ..descriptions import DESCRIPTIONS from ..translations.mutations import PageTranslate from .bulk_mutations import PageBulkDelete from .mutations import PageCreate, PageDelete, PageUpdate from .resolvers import resolve_page, resolve_pages from .types import Page class PageQueries(graphene.ObjectType): page = graphene.Field( Page, id=graphene.Argument(graphene.ID), slug=graphene.String(), description='Lookup a page by ID or by slug.') pages = PrefetchingConnectionField( Page, query=graphene.String( description=DESCRIPTIONS['page']), description='List of the shop\'s pages.') def resolve_page(self, info, id=None, slug=None): return resolve_page(info, id, slug) def
(self, info, query=None, **kwargs): return resolve_pages(info, query=query) class PageMutations(graphene.ObjectType): page_create = PageCreate.Field() page_delete = PageDelete.Field() page_bulk_delete = PageBulkDelete.Field() page_update = PageUpdate.Field() page_translate = PageTranslate.Field()
resolve_pages
RPCConstants.py
# A part of NonVisual Desktop Access (NVDA) # Copyright (C) 2009-2021 NV Access Limited # This file may be used under the terms of the GNU General Public License, version 2 or later. # For more details see: https://www.gnu.org/licenses/gpl-2.0.html import enum class
(enum.IntEnum): E_CALL_CANCELED = -2147418110 S_SERVER_UNAVAILABLE = 1722 S_CALL_FAILED_DNE = 1727 E_CALL_REJECTED = -2147418111 E_DISCONNECTED = -2147417848
RPC
dense_argmethods_tests.go
package main import ( "fmt" "io" "reflect" "text/template" ) type ArgMethodTestData struct { Kind reflect.Kind Data []int } var data = []int{ 3, 4, 2, 4, 3, 8, 3, 9, 7, 4, 3, 0, 3, 9, 9, 0, 6, 7, 3, 9, 4, 8, 5, 1, 1, 9, 4, 0, 4, 1, 6, 6, 4, 9, 3, 8, 1, 7, 0, 7, 4, 0, 6, 8, 2, 8, 0, 6, 1, 6, 2, 3, 7, 5, 7, 3, 0, 8, 6, 5, 6, 9, 7, 5, 6, 8, 7, 9, 5, 0, 8, 1, 4, 0, 6, 6, 3, 3, 8, 1, 1, 3, 2, 5, 9, 0, 4, 5, 3, 1, 9, 1, 9, 3, 9, 3, 3, 4, 5, 9, 4, 2, 2, 7, 9, 8, 1, 6, 9, 4, 4, 1, 8, 9, 8, 0, 9, 9, 4, 6, 7, 5, 9, 9, 4, 8, 5, 8, 2, 4, 8, 2, 7, 2, 8, 7, 2, 3, 7, 0, 9, 9, 8, 9, 2, 1, 7, 0, 7, 9, 0, 2, 4, 8, 7, 9, 6, 8, 3, 3, 7, 2, 9, 2, 8, 2, 3, 6, 0, 8, 7, 7, 0, 9, 0, 9, 3, 2, 6, 9, 5, 8, 6, 9, 5, 6, 1, 8, 7, 8, 1, 9, 9, 3, 7, 7, 6, 8, 2, 1, 1, 5, 1, 4, 0, 5, 1, 7, 9, 5, 6, 6, 8, 7, 5, 1, 3, 4, 0, 1, 8, 0, 2, 6, 9, 1, 4, 8, 0, 5, 6, 2, 9, 4, 4, 2, 4, 4, 4, 3, } const argMethodsDataRaw = `var basicDense{{short .Kind}} = New(WithShape(2,3,4,5,2), WithBacking([]{{asType .Kind}}{ {{range .Data -}}{{.}}, {{end -}} })) ` const argmaxCorrect = `var argmaxCorrect = []struct { shape Shape data []int }{ {Shape{3,4,5,2}, []int{ 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, }}, {Shape{2,4,5,2}, []int{ 1, 0, 1, 1, 2, 0, 2, 0, 0, 1, 2, 1, 2, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 2, 2, 0, 1, 1, 2, 2, 1, 0, 2, 0, 2, 0, 2, 2, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 1, 0, 1, 2, 1, 0, 1, 1, 2, 0, 1, 0, 0, 0, 0, 2, 1, 0, 1, 0, 0, 2, 1, 1, 0, 0, 0, 0, 0, 2, 0, }}, {Shape{2,3,5,2}, []int{ 3, 2, 2, 1, 1, 2, 1, 0, 0, 1, 3, 2, 1, 0, 1, 0, 2, 2, 3, 0, 1, 0, 1, 3, 0, 2, 3, 3, 2, 1, 2, 2, 0, 0, 1, 3, 2, 0, 1, 2, 0, 3, 0, 1, 0, 1, 3, 2, 2, 1, 2, 1, 3, 1, 2, 0, 2, 2, 0, 0, }}, {Shape{2,3,4,2}, []int{ 4, 3, 2, 1, 1, 2, 0, 1, 1, 1, 1, 3, 1, 0, 0, 2, 2, 1, 0, 4, 2, 2, 3, 1, 1, 1, 0, 2, 0, 0, 2, 2, 1, 4, 0, 1, 4, 1, 1, 0, 4, 3, 1, 1, 2, 3, 1, 1, }}, {Shape{2,3,4,5}, []int{ 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, }}, } ` const argminCorrect = `var argminCorrect = []struct { shape Shape data []int }{ {Shape{3,4,5,2}, []int{ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, }}, {Shape{2,4,5,2}, []int{ 2, 1, 0, 0, 1, 2, 1, 2, 1, 2, 1, 0, 0, 2, 1, 0, 1, 2, 0, 1, 0, 2, 2, 0, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 0, 2, 0, 1, 0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 0, 2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 2, 2, 0, 0, 1, 0, 2, 2, 0, 0, 0, 1, 2, 2, 2, 2, 1, 1, }}, {Shape{2,3,5,2}, []int{ 0, 1, 0, 2, 2, 1, 3, 2, 3, 2, 1, 0, 3, 3, 0, 1, 0, 3, 0, 2, 0, 1, 0, 1, 3, 0, 2, 1, 0, 0, 3, 1, 3, 1, 2, 2, 1, 2, 0, 1, 3, 0, 1, 0, 1, 0, 2, 1, 0, 3, 0, 2, 0, 0, 0, 1, 0, 1, 1, 1, }}, {Shape{2,3,4,2}, []int{ 1, 0, 0, 0, 2, 3, 4, 0, 3, 0, 3, 0, 4, 4, 3, 1, 0, 2, 3, 0, 3, 0, 0, 2, 4, 4, 3, 4, 2, 3, 0, 0, 4, 0, 1, 3, 3, 2, 0, 4, 2, 1, 4, 2, 4, 0, 2, 0, }}, {Shape{2,3,4,5}, []int{ 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, }}, } ` type ArgMethodTest struct { Kind reflect.Kind ArgMethod string ArgAllAxes int } const testArgMethodsRaw = `func TestDense_{{title .ArgMethod}}_{{short .Kind}}(t *testing.T){ assert := assert.New(t) var T, {{.ArgMethod}} *Dense var err error T = basicDense{{short .Kind}}.Clone().(*Dense) for i:= 0; i < T.Dims(); i++ { if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(i); err != nil { t.Error(err) continue } assert.True({{.ArgMethod}}Correct[i].shape.Eq({{.ArgMethod}}.Shape()), "{{title .ArgMethod}}(%d) error. Want shape %v. Got %v", i, {{.ArgMethod}}Correct[i].shape) assert.Equal({{.ArgMethod}}Correct[i].data, {{.ArgMethod}}.Data(), "{{title .ArgMethod}}(%d) error. ", i) } // test all axes if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(AllAxes); err != nil { t.Error(err) return } assert.True({{.ArgMethod}}.IsScalar()) assert.Equal({{.ArgAllAxes}}, {{.ArgMethod}}.ScalarValue()) {{if hasPrefix .Kind.String "float" -}} // test with NaN T = New(WithShape(4), WithBacking([]{{asType .Kind}}{1,2,{{mathPkg .Kind}}NaN(), 4})) if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(AllAxes); err != nil { t.Errorf("Failed test with NaN: %v", err) } assert.True({{.ArgMethod}}.IsScalar()) assert.Equal(2, {{.ArgMethod}}.ScalarValue(), "NaN test") // test with Mask and Nan T = New(WithShape(4), WithBacking([]{{asType .Kind}}{1,{{if eq .ArgMethod "argmax"}}9{{else}}-9{{end}},{{mathPkg .Kind}}NaN(), 4}, []bool{false,true,true,false})) if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(AllAxes); err != nil { t.Errorf("Failed test with NaN: %v", err) } assert.True({{.ArgMethod}}.IsScalar()) assert.Equal({{if eq .ArgMethod "argmin"}}0{{else}}3{{end}}, {{.ArgMethod}}.ScalarValue(), "Masked NaN test") // test with +Inf T = New(WithShape(4), WithBacking([]{{asType .Kind}}{1,2,{{mathPkg .Kind}}Inf(1),4})) if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(AllAxes); err != nil { t.Errorf("Failed test with +Inf: %v", err) } assert.True({{.ArgMethod}}.IsScalar()) assert.Equal({{if eq .ArgMethod "argmax"}}2{{else}}0{{end}}, {{.ArgMethod}}.ScalarValue(), "+Inf test") // test with Mask and +Inf T = New(WithShape(4), WithBacking([]{{asType .Kind}}{1,{{if eq .ArgMethod "argmax"}}9{{else}}-9{{end}},{{mathPkg .Kind}}Inf(1), 4}, []bool{false,true,true,false})) if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(AllAxes); err != nil { t.Errorf("Failed test with NaN: %v", err) } assert.True({{.ArgMethod}}.IsScalar()) assert.Equal({{if eq .ArgMethod "argmin"}}0{{else}}3{{end}}, {{.ArgMethod}}.ScalarValue(), "Masked NaN test") // test with -Inf T = New(WithShape(4), WithBacking([]{{asType .Kind}}{1,2,{{mathPkg .Kind}}Inf(-1),4 })) if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(AllAxes); err != nil { t.Errorf("Failed test with -Inf: %v", err) } assert.True({{.ArgMethod}}.IsScalar()) assert.Equal({{if eq .ArgMethod "argmin"}}2{{else}}3{{end}}, {{.ArgMethod}}.ScalarValue(), "+Inf test") // test with Mask and -Inf T = New(WithShape(4), WithBacking([]{{asType .Kind}}{1,{{if eq .ArgMethod "argmax"}}9{{else}}-9{{end}},{{mathPkg .Kind}}Inf(-1), 4}, []bool{false,true,true,false})) if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(AllAxes); err != nil { t.Errorf("Failed test with NaN: %v", err) } assert.True({{.ArgMethod}}.IsScalar()) assert.Equal({{if eq .ArgMethod "argmin"}}0{{else}}3{{end}}, {{.ArgMethod}}.ScalarValue(), "Masked -Inf test") {{end -}} // with different engine T = basicDense{{short .Kind}}.Clone().(*Dense) WithEngine(dummyEngine2{})(T) for i:= 0; i < T.Dims(); i++ { if {{.ArgMethod}}, err = T.{{title .ArgMethod}}(i); err != nil { t.Error(err) continue } assert.True({{.ArgMethod}}Correct[i].shape.Eq({{.ArgMethod}}.Shape()), "{{title .ArgMethod}}(%d) error. Want shape %v. Got %v", i, {{.ArgMethod}}Correct[i].shape) assert.Equal({{.ArgMethod}}Correct[i].data, {{.ArgMethod}}.Data(), "{{title .ArgMethod}}(%d) error. ", i) } // idiotsville _, err = T.{{title .ArgMethod}}(10000) assert.NotNil(err) } ` var ( argMethodsData *template.Template testArgMethods *template.Template ) func init() {
} func generateArgmethodsTests(f io.Writer, generic Kinds) { fmt.Fprintf(f, "/* Test data */\n\n") for _, k := range generic.Kinds { if isNumber(k) && isOrd(k) { op := ArgMethodTestData{k, data} argMethodsData.Execute(f, op) } } fmt.Fprintf(f, "\n%s\n%s\n", argmaxCorrect, argminCorrect) for _, k := range generic.Kinds { if isNumber(k) && isOrd(k) { op := ArgMethodTest{k, "argmax", 7} testArgMethods.Execute(f, op) op = ArgMethodTest{k, "argmin", 11} testArgMethods.Execute(f, op) } } }
argMethodsData = template.Must(template.New("argmethodsData").Funcs(funcs).Parse(argMethodsDataRaw)) testArgMethods = template.Must(template.New("testArgMethod").Funcs(funcs).Parse(testArgMethodsRaw))
rpc.ts
import assert from "assert"; import { AccountInfo, AccountMeta, Connection, PublicKey, TransactionSignature, Transaction, TransactionInstruction, } from "@gemachain/web3.js"; import { Address, translateAddress } from "../program/common"; import Provider, { getProvider } from "../provider"; /** * Sends a transaction to a program with the given accounts and instruction * data. */ export async function invoke( programId: Address, accounts?: Array<AccountMeta>, data?: Buffer, provider?: Provider ): Promise<TransactionSignature> { programId = translateAddress(programId); if (!provider) { provider = getProvider(); } const tx = new Transaction(); tx.add( new TransactionInstruction({ programId, keys: accounts ?? [], data, }) ); return await provider.send(tx); } export async function getMultipleAccounts( connection: Connection, publicKeys: PublicKey[] ): Promise< Array<null | { publicKey: PublicKey; account: AccountInfo<Buffer> }> > { const args = [publicKeys.map((k) => k.toBase58()), { commitment: "recent" }]; // @ts-ignore const res = await connection._rpcRequest("getMultipleAccounts", args); if (res.error) { throw new Error( "failed to get info about accounts " + publicKeys.map((k) => k.toBase58()).join(", ") + ": " + res.error.message ); } assert(typeof res.result !== "undefined");
data: Buffer; }> = []; for (const account of res.result.value) { let value: { executable: any; owner: PublicKey; carats: any; data: Buffer; } | null = null; if (account === null) { accounts.push(null); continue; } if (res.result.value) { const { executable, owner, carats, data } = account; assert(data[1] === "base64"); value = { executable, owner: new PublicKey(owner), carats, data: Buffer.from(data[0], "base64"), }; } if (value === null) { throw new Error("Invalid response"); } accounts.push(value); } return accounts.map((account, idx) => { if (account === null) { return null; } return { publicKey: publicKeys[idx], account, }; }); }
const accounts: Array<null | { executable: any; owner: PublicKey; carats: any;