prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>sponsors.module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MdButtonModule, MdCardModule, MdProgressSpinnerModule, MdIconModule } from '@angular/material'; import { AvailableSponsorsComponent } from './available-sponsors/available-sponsors.component'; import { SponsorsRoutingModule } from '../sponsors/sponsors-routing.module'; import { MediaTypeModule } from '../shared/media-type/media-type.module'; @NgModule({<|fim▁hole|> imports: [ CommonModule, SponsorsRoutingModule, MdButtonModule, MdCardModule, MdProgressSpinnerModule, MdIconModule, MediaTypeModule ], declarations: [AvailableSponsorsComponent] }) export class SponsorsModule { }<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict'; var mongoose = require('mongoose'), async = require('async'); var DeleteChildrenPlugin = function(schema, options) { schema.pre('remove', function(done) { var parentField = options.parentField; var childModel = options.childModel; if (!parentField) { var err = new Error('parentField not defined'); return done(err); } if (!childModel) { var err = new Error('childModel not defined'); return done(err); } // must delete all campuses console.log('model::', parentField, '>', childModel, '::pre::remove::enter'); var Model = mongoose.model(childModel); var conditions = {}; conditions[parentField] = this._id; Model.find(conditions).exec(function(err, results) { console.log('model::', parentField, '>', childModel, '::pre::remove::find::enter'); if (err) { return done(err); } async.each(results, function(campus, deleteNextModel) { console.log('model::', parentField, '>', childModel, '::pre::remove::find::each::enter'); campus.remove(deleteNextModel); }, done); }); }); }; var ParentAttachPlugin = function(schema, options) { schema.pre('save', function(doneAttaching) { var doc = this; var parentField = options.parentField; var parentModel = options.parentModel; var childCollection = options.childCollection; if (!doc[parentField]) return doneAttaching(); var Parent = mongoose.model(parentModel); var push = {}; push[childCollection] = doc._id; Parent.findByIdAndUpdate(doc[parentField], { $push: push }).exec(function(err) { if (err) { console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::err', err); return doneAttaching(err); } console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::exit'); doneAttaching(); }); }); schema.pre('remove', function(doneRemoving) { var doc = this; var parentField = options.parentField; var parentModel = options.parentModel; var childCollection = options.childCollection; if (!doc[parentField]) return doneRemoving(); var Parent = mongoose.model(parentModel); var pull = {}; pull[childCollection] = doc._id; Parent.findByIdAndUpdate(doc[parentField], { $pull: pull }).exec(function(err) { if (err) { console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::err', err); return doneRemoving(err); } console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::exit'); doneRemoving(); }); }); }; <|fim▁hole|>exports.deleteChildren = DeleteChildrenPlugin;<|fim▁end|>
exports.parentAttach = ParentAttachPlugin;
<|file_name|>context.rs<|end_file_name|><|fim▁begin|>use criterion::Criterion; use lucet_runtime_internals::context::{Context, ContextHandle}; /// Time the initialization of a context. fn context_init(c: &mut Criterion) { extern "C" fn f() {} let mut stack = vec![0u64; 1024].into_boxed_slice(); c.bench_function("context_init", move |b| { b.iter(|| { ContextHandle::create_and_init(&mut *stack, f as usize, &[]).unwrap(); }) }); } /// Time the swap from an already-initialized context to a guest function and back. fn context_swap_return(c: &mut Criterion) { extern "C" fn f() {} c.bench_function("context_swap_return", move |b| { b.iter_batched( || { let mut stack = vec![0u64; 1024].into_boxed_slice(); let child = ContextHandle::create_and_init(&mut *stack, f as usize, &[]).unwrap(); (stack, child) }, |(stack, mut child)| unsafe { let mut parent = ContextHandle::new(); Context::swap(&mut parent, &mut child); stack }, criterion::BatchSize::PerIteration, ) }); } /// Time initialization plus swap and return. fn context_init_swap_return(c: &mut Criterion) { extern "C" fn f() {} c.bench_function("context_init_swap_return", move |b| { b.iter_batched( || vec![0u64; 1024].into_boxed_slice(), |mut stack| { let mut parent = ContextHandle::new(); let mut child = ContextHandle::create_and_init(&mut *stack, f as usize, &[]).unwrap(); unsafe { Context::swap(&mut parent, &mut child) }; stack },<|fim▁hole|>} /// Swap to a trivial guest function that takes a bunch of arguments. fn context_init_swap_return_many_args(c: &mut Criterion) { extern "C" fn f( _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, _: u8, _: u16, _: u32, _: u64, _: f32, _: f64, ) { } let args = vec![ 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), 0xAFu8.into(), 0xAFu16.into(), 0xAFu32.into(), 0xAFu64.into(), 175.0f32.into(), 175.0f64.into(), ]; c.bench_function("context_init_swap_return_many_args", move |b| { b.iter_batched( || vec![0u64; 1024].into_boxed_slice(), |mut stack| { let mut parent = ContextHandle::new(); let mut child = ContextHandle::create_and_init(&mut *stack, f as usize, &args).unwrap(); unsafe { Context::swap(&mut parent, &mut child) }; stack }, criterion::BatchSize::PerIteration, ) }); } /// Time the call to pthread_sigmask as used in `Context::init()`. fn context_pthread_sigmask(c: &mut Criterion) { use nix::sys::signal; c.bench_function("context_pthread_sigmask", |b| { b.iter_batched( || signal::SigSet::empty(), |mut sigset| { signal::pthread_sigmask(signal::SigmaskHow::SIG_SETMASK, None, Some(&mut sigset)) .unwrap() }, criterion::BatchSize::PerIteration, ) }); } pub fn context_benches(c: &mut Criterion) { context_init(c); context_swap_return(c); context_init_swap_return(c); context_init_swap_return_many_args(c); context_pthread_sigmask(c); }<|fim▁end|>
criterion::BatchSize::PerIteration, ) });
<|file_name|>resources.py<|end_file_name|><|fim▁begin|>import requests import platform from authy import __version__, AuthyFormatException from urllib.parse import quote # import json try: import json except ImportError: try: import simplejson as json except ImportError: from django.utils import simplejson as json class Resource(object): def __init__(self, api_uri, api_key): self.api_uri = api_uri self.api_key = api_key self.def_headers = self.__default_headers() def post(self, path, data=None): return self.request("POST", path, data, {'Content-Type': 'application/json'}) def get(self, path, data=None): return self.request("GET", path, data) def put(self, path, data=None): return self.request("PUT", path, data, {'Content-Type': 'application/json'}) def delete(self, path, data=None): return self.request("DELETE", path, data) def request(self, method, path, data=None, req_headers=None): if data is None: data = {} if req_headers is None: req_headers = {} url = self.api_uri + path params = {"api_key": self.api_key} headers = self.def_headers headers.update(req_headers) if method == "GET": params.update(data) return requests.request(method, url, headers=headers, params=params) else: return requests.request(method, url, headers=headers, params=params, data=json.dumps(data)) def __default_headers(self): return { 'User-Agent': "AuthyPython/{0} ({1}; Python {2})".format( __version__, platform.platform(True), platform.python_version() )} class Instance(object): def __init__(self, resource, response): self.resource = resource self.response = response try: self.content = self.response.json() except ValueError: self.content = self.response.text def ok(self): return self.response.status_code == 200 def errors(self): if self.ok(): return {} errors = self.content if(not isinstance(errors, dict)): errors = {"error": errors} elif('errors' in errors): errors = errors['errors'] return errors def __getitem__(self, key): return self.content[key] class Sms(Instance): def ignored(self): try: self.content['ignored'] return True except KeyError: return False class User(Instance): def __init__(self, resource, response): super(User, self).__init__(resource, response) if(isinstance(self.content, dict) and 'user' in self.content): self.id = self.content['user']['id'] else: self.id = None class Users(Resource): def create(self, email, phone, country_code=1): data = { "user": { "email": email, "cellphone": phone, "country_code": country_code } } resp = self.post("/protected/json/users/new", data) return User(self, resp) def request_sms(self, user_id, options={}): resp = self.get("/protected/json/sms/"+quote(str(user_id)), options) return Sms(self, resp) def status(self, user_id): resp = self.get("/protected/json/users/{0}/status".format(user_id)) return User(self, resp) def delete(self, user_id): resp = self.post("/protected/json/users/{0}/delete".format(user_id)) return User(self, resp) class Token(Instance): def ok(self): if super(Token, self).ok(): return '"token":"is valid"' in str(self.response.content) return False class Tokens(Resource): def verify(self, device_id, token, options={}): self.__validate(token, device_id) if 'force' not in options: options['force'] = "true" url = "/protected/json/verify/" url += quote(str(token))+"/"+quote(str(device_id)) resp = self.get(url, options) return Token(self, resp) def __validate(self, token, device_id): self.__validate_digit(token, "Invalid Token. Only digits accepted.") self.__validate_digit(device_id, "Invalid Authy id. Only digits accepted.") length = len(str(token)) if length < 6 or length > 10: raise AuthyFormatException("Invalid Token. Unexpected length.") def __validate_digit(self, var, message): # PEP 0237: Essentially, long renamed to int. if not isinstance(var, int) and not var.isdigit(): raise AuthyFormatException(message) class App(Instance): pass class Apps(Resource): def fetch(self): resp = self.get("/protected/json/app/details") return App(self, resp) class Stats(Instance): pass class StatsResource(Resource): def fetch(self): resp = self.get("/protected/json/app/stats") return Stats(self, resp) class Phone(Instance): pass class Phones(Resource): def verification_start(self, phone_number, country_code, via = 'sms'): options = {<|fim▁hole|> resp = self.post("/protected/json/phones/verification/start", options) return Phone(self, resp) def verification_check(self, phone_number, country_code, verification_code): options = { 'phone_number': phone_number, 'country_code': country_code, 'verification_code': verification_code } resp = self.get("/protected/json/phones/verification/check", options) return Phone(self, resp) def info(self, phone_number, country_code): options = { 'phone_number': phone_number, 'country_code': country_code } resp = self.get("/protected/json/phones/info", options) return Phone(self, resp)<|fim▁end|>
'phone_number': phone_number, 'country_code': country_code, 'via': via }
<|file_name|>tileset2fj.go<|end_file_name|><|fim▁begin|>/* Copyright (C) 2015 Curoverse, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Take in an ordered tileset represented as a CSV of: // // path.step,tag_sequence // // along with a sequence and create a FastJ file. // // example usage: // ./tileset2fj -i 'actcat....gcat' -t mytileset.csv --build-prefix 'hg19 chr17' -o out.fj // package main import "fmt" import "os" import "runtime" import "runtime/pprof" import "strings" import _ "bufio" import "github.com/abeconnelly/autoio" import "github.com/codegangsta/cli" import "sort" import "crypto/md5" var VERSION_STR string = "0.1.0" var gVerboseFlag bool var gProfileFlag bool var gProfileFile string = "tileset2fj.pprof" var gMemProfileFlag bool var gMemProfileFile string = "tileset2fj.mprof" var g_tagset map[string]string var g_tagseq map[string]string var g_seq string var g_build_prefix string var g_seq_start int func init() { g_build_prefix = "unknown" g_tagset = make(map[string]string) g_tagseq = make(map[string]string) } func md5sum_str(seq string) string { ta := make([]string, 0, 32) s := md5.Sum([]byte(seq)) for i:=0; i<len(s); i++ { ta = append(ta, fmt.Sprintf("%02x", s[i])) } return strings.Join(ta, "") } func load_tagset(h autoio.AutoioHandle) error { line_no:=0 for h.ReadScan() { line_no++ l := h.ReadText() if len(l)==0 { continue } fields := strings.Split(l, ",") if len(fields) != 2 { return fmt.Errorf("bad read on line %s", line_no) } g_tagset[fields[0]] = fields[1] g_tagseq[fields[1]] = fields[0] } return nil } func load_seq(h autoio.AutoioHandle) { //fold := 50 for h.ReadScan() { l := h.ReadText() if len(l) == 0 { continue } g_seq = l } g_seq = strings.ToLower(g_seq) } func find_tag_positions() { //for tilepos := range tagpos_ind { fmt.Printf("%s >> %d\n", tilepos, tagpos_ind[tilepos]) } } func print_fold(seq string, fold int) { if len(seq)==0 { return } p:=0 for ; p<(len(seq)-fold); p+=fold { fmt.Printf("%s\n", seq[p:p+fold]) } fmt.Printf("%s\n", seq[p:]) } type LexOrder []string func (s LexOrder) Len() int { return len(s) } func (s LexOrder) Swap(i,j int) { s[i],s[j] = s[j],s[i] } func (s LexOrder) Less(i,j int) bool { return s[i] < s[j] } func gen_tiling() { tagpos_ind := make(map[string]int) for tilepos := range g_tagset { seq := g_tagset[tilepos] tagpos_ind[tilepos] = strings.Index(g_seq, seq) } tagpos := make([]string, 0, len(g_tagset)) for tilepos := range g_tagset { tagpos = append(tagpos, tilepos) } sort.Sort(LexOrder(tagpos)) for i:=0; i<len(tagpos); i++ { if (tagpos_ind[tagpos[i]]<0) { continue } n:=1 for ; (i+n)<len(tagpos); n++ { if tagpos_ind[tagpos[i+n]]>=0 { break } } if (i+n)==len(tagpos) { continue } sp := tagpos_ind[tagpos[i]] ep := tagpos_ind[tagpos[i+n]] + 24 seq := g_seq[sp:ep] tagpos_parts := strings.Split(tagpos[i], ".") tileid := fmt.Sprintf("%03s.00.%04s.000", tagpos_parts[0], tagpos_parts[1]) m5 := md5sum_str(seq) s := sp + g_seq_start e := ep + g_seq_start - 1 json_str := fmt.Sprintf(`{ "tileID" : "%s", "md5sum":"%s", "locus":[{"build":"%s %d %d"}], "n":%d, "seedTileLength":%d, ` + `"startTile":false, "endTile":false, "startSeq":"%s", "endSeq":"%s", ` + `"startTag":"%s", "endTag":"%s", "nocallCount":%d, "notes":[] }`, tileid, m5, g_build_prefix, s, e, len(seq), n, seq[0:24], seq[len(seq)-24:], seq[0:24], seq[len(seq)-24:], 0) fmt.Printf("> %s\n", json_str) print_fold(seq, 50) fmt.Printf("\n") } } func _main( c *cli.Context ) { g_build_prefix = c.String("build-prefix") g_seq_start = c.Int("seq-start") if c.String("input") == "" { fmt.Fprintf( os.Stderr, "Input required, exiting\n" ) cli.ShowAppHelp( c ) os.Exit(1) } seq_fp,err := autoio.OpenReadScannerSimple( c.String("input") ) ; _ = seq_fp if err!=nil { fmt.Fprintf(os.Stderr, "%v", err) os.Exit(1) } defer seq_fp.Close() tileset_fp,err := autoio.OpenReadScannerSimple( c.String("tileset") ) ; _ = tileset_fp if err!=nil { fmt.Fprintf(os.Stderr, "%v", err) os.Exit(1) } defer tileset_fp.Close() load_tagset(tileset_fp) load_seq(seq_fp) find_tag_positions() gen_tiling() if c.Bool( "pprof" ) { gProfileFlag = true gProfileFile = c.String("pprof-file") } if c.Bool( "mprof" ) { gMemProfileFlag = true gMemProfileFile = c.String("mprof-file") } gVerboseFlag = c.Bool("Verbose") if c.Int("max-procs") > 0 { runtime.GOMAXPROCS( c.Int("max-procs") ) } if gProfileFlag { prof_f,err := os.Create( gProfileFile ) if err != nil { fmt.Fprintf( os.Stderr, "Could not open profile file %s: %v\n", gProfileFile, err ) os.Exit(2) } pprof.StartCPUProfile( prof_f ) defer pprof.StopCPUProfile() } } func main() { app := cli.NewApp() app.Name = "tileset2fj" app.Usage = "Convert a sequence to FastJ from a tileset" app.Version = VERSION_STR app.Author = "Curoverse, Inc." app.Email = "[email protected]" app.Action = func( c *cli.Context ) { _main(c) } app.Flags = []cli.Flag{ cli.StringFlag{ Name: "input, i", Usage: "INPUT sequence", }, cli.StringFlag{ Name: "tileset, t", Usage: "TileSet as a CSV path.step,tag_sequence", }, cli.StringFlag{ Name: "build-prefix", Usage: "Prefix to put in build note (e.g. 'grch38 chr17')", }, cli.IntFlag{ Name: "seq-start", Usage: "Offset of sequence, used for build-prefix calculations. 0 reference.", }, cli.StringFlag{ Name: "output, o", Value: "-", Usage: "OUTPUT", }, cli.IntFlag{ Name: "max-procs, N", Value: -1, Usage: "MAXPROCS", }, cli.BoolFlag{ Name: "Verbose, V", Usage: "Verbose flag", }, cli.BoolFlag{ Name: "pprof", Usage: "Profile usage", }, cli.StringFlag{ Name: "pprof-file", Value: gProfileFile, Usage: "Profile File", }, cli.BoolFlag{ Name: "mprof", Usage: "Profile memory usage", }, cli.StringFlag{ Name: "mprof-file", Value: gMemProfileFile, Usage: "Profile Memory File", }, } <|fim▁hole|> app.Run( os.Args ) if gMemProfileFlag { fmem,err := os.Create( gMemProfileFile ) if err!=nil { panic(fmem) } pprof.WriteHeapProfile(fmem) fmem.Close() } }<|fim▁end|>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod api; use gcrypt; use hyper; use rustc_serialize::base64; use rustc_serialize::hex; use rustc_serialize::json; use crypto;<|fim▁hole|> use std::fmt; use std::io; use rustc_serialize::base64::FromBase64; use rustc_serialize::hex::FromHex; use rustc_serialize::hex::ToHex; #[derive(Debug)] pub enum KeybaseError { Http(String), Api(api::Status), FromBase64(base64::FromBase64Error), FromHex(hex::FromHexError), Gcrypt(gcrypt::error::Error), Hyper(hyper::Error), Io(io::Error), Json(json::DecoderError), } impl From<api::Status> for KeybaseError { fn from(err: api::Status) -> KeybaseError { KeybaseError::Api(err) } } impl From<base64::FromBase64Error> for KeybaseError { fn from(err: base64::FromBase64Error) -> KeybaseError { KeybaseError::FromBase64(err) } } impl From<hex::FromHexError> for KeybaseError { fn from(err: hex::FromHexError) -> KeybaseError { KeybaseError::FromHex(err) } } impl From<gcrypt::error::Error> for KeybaseError { fn from(err: gcrypt::error::Error) -> KeybaseError { KeybaseError::Gcrypt(err) } } impl From<hyper::Error> for KeybaseError { fn from(err: hyper::Error) -> KeybaseError { KeybaseError::Hyper(err) } } impl From<io::Error> for KeybaseError { fn from(err: io::Error) -> KeybaseError { KeybaseError::Io(err) } } impl From<json::DecoderError> for KeybaseError { fn from(err: json::DecoderError) -> KeybaseError { KeybaseError::Json(err) } } impl fmt::Display for KeybaseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { KeybaseError::Http(ref msg) => write!(f, "Keybase API Error: {}", msg), KeybaseError::Api(ref err) => match err.desc.as_ref() { Some(ref desc) => write!(f, "Keybase API error: {} ({})", desc, err.name), None => write!(f, "Keybase API error: {}", err.name), }, KeybaseError::FromBase64(ref err) => err.fmt(f), KeybaseError::FromHex(ref err) => err.fmt(f), KeybaseError::Gcrypt(ref err) => err.fmt(f), KeybaseError::Hyper(ref err) => err.fmt(f), KeybaseError::Io(ref err) => err.fmt(f), KeybaseError::Json(ref err) => err.fmt(f), } } } pub type KeybaseResult<T> = Result<T, KeybaseError>; #[allow(dead_code)] pub struct Keybase { session: String, csrf_token: String, } impl Keybase { pub fn login(user: &str, password: &str, token: gcrypt::Token) -> KeybaseResult<Keybase> { let getsalt = try!(api::getsalt(user)); let salt = &getsalt.salt.unwrap(); let login_session = &getsalt.login_session.unwrap(); let salt_bytes = try!(salt.from_hex()); let mut pwh = vec![0; 224]; try!(crypto::scrypt(password, &salt_bytes, &mut pwh, token)); let session = try!(login_session.from_base64()); let hmac_pwh = try!(crypto::hmac_sha512(&session, &pwh[192..224], token)); let key = hmac_pwh.to_hex(); let login = try!(api::login(user, &key, login_session)); Ok(Keybase{session : login.session.unwrap(), csrf_token: login.csrf_token.unwrap()}) } } #[cfg(test)] mod tests { use gcrypt; use super::*; use std::env; #[test] #[allow(unused_variables)] fn can_login() { let token = gcrypt::init(|mut gcry| { gcry.enable_secmem(16384).unwrap(); }); let username = &env::var("HEDWIG_TEST_KEYBASE_USERNAME").unwrap(); let password = &env::var("HEDWIG_TEST_KEYBASE_PASSWORD").unwrap(); let keybase_session = Keybase::login(&username, &password, token).unwrap(); } }<|fim▁end|>
<|file_name|>DataAdapter.java<|end_file_name|><|fim▁begin|>package com.creativecub.iotarduino; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Switch; import android.widget.TextView; import java.util.List; public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> { private List<Data> moviesList; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView title, year, genre; public ImageView ivIcon; public Switch aSwitch; public MyViewHolder(View view) { super(view); title = (TextView) view.findViewById(R.id.title); genre = (TextView) view.findViewById(R.id.genre); year = (TextView) view.findViewById(R.id.year); <|fim▁hole|> aSwitch = (Switch) view.findViewById(R.id.switch1); } } public DataAdapter(List<Data> moviesList) { this.moviesList = moviesList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_row, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { Data data = moviesList.get(position); holder.title.setText(data.getTitle()); holder.genre.setText(data.getGenre()); holder.year.setText(data.getYear()); holder.ivIcon.setImageBitmap(data.getIvIcon()); holder.aSwitch.setChecked(data.gettoggle()); } @Override public int getItemCount() { return moviesList.size(); } }<|fim▁end|>
ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
<|file_name|>status-tweet.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # This script will tweet the text that is passed as an argument # Requires Twython, API credentials set as env vars # Usage: python status-tweet.py "Hello Everyone, this is my Raspberry Pi tweeting you more nonsense" import sys import os from twython import Twython import twitter_api_creds # Set Twitter Credentials from environment variables CONSUMER_KEY = os.getenv("CONSUMER_KEY") CONSUMER_SECRET = os.getenv("CONSUMER_SECRET") ACCESS_KEY = os.getenv("ACCESS_KEY") ACCESS_SECRET = os.getenv("ACCESS_SECRET") api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) <|fim▁hole|><|fim▁end|>
# Tweet api.update_status(status=sys.argv[1][:140])
<|file_name|>majority_voting_test.py<|end_file_name|><|fim▁begin|>#to get some base functionality for free, including the methods get_params and set_params #to set and return the classifier's parameters as well as the score method to calculate the #prediction accuracy,respectively from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin from sklearn.preprocessing import LabelEncoder #import six too make the MajorityVoteClassifier compatible with python2.7 from sklearn.externals import six from sklearn.base import clone from sklearn.pipeline import _name_estimators import numpy as np import operator class MajorityVoteClassifier(BaseEstimator,ClassifierMixin): """ A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} Default: 'classlabel' If 'classlabel' the prediction is based on the argmax of class labels. Else if 'probability', the argmax of the sum of probabilities is used to predict the class label (recommended for calibrated classifiers). weights : array-like, shape = [n_classifiers] Optional, default: None If a list of `int` or `float` values are provided , the classifiers are weithed by importance; Uses uniform weights if 'weights = None' """ def __init__(self, classifiers,vote='classlabel', weights=None): self.classifiers = classifiers self.named_classifiers = {key: value for key, value in _name_estimators(classifiers)} self.vote = vote self.weights = weights def fit(self, X, y): """ Fit classifiers. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Matrix of training samples. y : array-like, shape = [n_samples] Vector of target class labels. Returns ------- self : object """ # Use LabelEncoder to ensure class labels start # with 0, which is important for np.argmax # call in self.predict self.lablenc_ = LabelEncoder() self.lablenc_.fit(y) self.classes_ = self.lablenc_.classes_ self.classifiers_ = [] for clf in self.classifiers: fitted_clf = clone(clf).fit(X,self.lablenc_.transform(y)) self.classifiers_.append(fitted_clf) return self def predict(self, X): """ Predict class labels for X. Parameters ---------- X : {array-like, sparse matrix}, Shape = [n_samples, n_features] Matrix of training samples Returns ---------- maj_vote : array-like, shape = [n_samples] Predicted class labels. """ if self.vote == 'probability': maj_vote = np.argmax(self.predict_proba(X),axis=1) else: # 'classlabel' vote # Collect results from clf.predict calls predictions = np.asarray([clf.predict(X) for clf in self.classifiers_]).T maj_vote = np.apply_along_axis(lambda x: np.argmax(np.bincount(x,weights=self.weights)),axis=1,arr=predictions) maj_vote = self.lablenc_.inverse_transform(maj_vote) return maj_vote def predict_proba(self, X): """ Predict class probabilities for X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ---------- avg_proba : array-like, shape = [n_samples, n_classes] Weighted average probability for each class per sample. """ probas = np.asarray([clf.predict_proba(X) for clf in self.classifiers_]) avg_proba = np.average(probas,axis=0, weights=self.weights) return avg_proba def get_params(self, deep=True): """ Get classifier parameter names for GridSearch""" if not deep: return super(MajorityVoteClassifier,self).get_params(deep=False) else: out = self.named_classifiers.copy() for name, step in six.iteritems(self.named_classifiers): for key, value in six.iteritems(step.get_params(deep=True)): out['%s__%s' % (name, key)] = value return out #get datas from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder iris = datasets.load_iris() X,y = iris.data[50:,[1,2]],iris.target[50:] le = LabelEncoder()<|fim▁hole|> X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.5,random_state = 1) #train logistic regression classifier, decision tree, k-nearest neightbor respectively from sklearn.cross_validation import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline import numpy as np clf1 = LogisticRegression(penalty = 'l2',C = 0.001,random_state = 0) clf2 = DecisionTreeClassifier(max_depth = 1,criterion = 'entropy',random_state = 0) clf3 = KNeighborsClassifier(n_neighbors = 1,p=2,metric = 'minkowski') pipe1 = Pipeline([['sc',StandardScaler()],['clf',clf1]]) pipe3 = Pipeline([['sc',StandardScaler()],['clf',clf3]]) clf_labels = ['Logistic Regression','Decision Tree','KNN'] print('10-fold cross validation:\n') for clf,label in zip([pipe1,clf2,pipe3],clf_labels): scores = cross_val_score(estimator = clf, X=X_train, y=y_train, cv=10, scoring = 'roc_auc') print ("ROC AUC: %0.2f (+/- %0.2f) [%s]" % (scores.mean(),scores.std(),label)) #combine the individual classifiers for majority rule voting in our MajorityVoteClassifier #import os #pwd = os.getcwd() #os.chdir('E:\\machine-learning\\19-Ensemble Learning\\') #from majority_voting import MajorityVoteClassifier mv_clf = MajorityVoteClassifier(classifiers=[pipe1, clf2, pipe3]) clf_labels += ['Majority Voting'] all_clf = [pipe1, clf2, pipe3, mv_clf] for clf, label in zip(all_clf, clf_labels): scores = cross_val_score(estimator=clf,X=X_train,y=y_train,cv=10,scoring='roc_auc') print("Accuracy: %0.2f (+/- %0.2f) [%s]"% (scores.mean(), scores.std(), label)) #os.chdir(pwd) #compute the ROC curves from the test set to check if the MajorityVoteClassifier generalizes well to unseen data from sklearn.metrics import roc_curve from sklearn.metrics import auc import matplotlib.pyplot as plt colors = ['black','orange','blue','green'] linestyles = [':', '--', '-.', '-'] for clf,label,clr,ls in zip(all_clf,clf_labels,colors,linestyles): #assuming the label of the positive class is 1 y_pred = clf.fit(X_train,y_train).predict_proba(X_test)[:,1] fpr,tpr,thresholds = roc_curve(y_true = y_test,y_score = y_pred) roc_auc = auc(x= fpr,y=tpr) plt.plot(fpr,tpr,color = clr,linestyle = ls,label = '%s (auc = %0.2f)' % (label,roc_auc)) plt.legend(loc = 'lower right') plt.plot([0, 1], [0, 1],linestyle='--',color='gray',linewidth=2) plt.xlim([-0.1, 1.1]) plt.ylim([-0.1, 1.1]) plt.grid() plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.show() #tune the inverse regularization parameter C of the logistic regression classifier and the decision tree #depth via a grid search for demonstration purposes from sklearn.grid_search import GridSearchCV params = {'decisiontreeclassifier__max_depth':[1,2],'pipeline-1__clf__C':[0.001,0.1,100.0]} grid = GridSearchCV(estimator = mv_clf,param_grid=params,cv = 10,scoring = 'roc_auc') grid.fit(X_train,y_train) for params,mean_score,scores in grid.grid_scores_: print('%0.3f +/- %0.2f %r' % (mean_score,scores.std()/2,params)) print('Best parameters : %s' % grid.best_params_) print('Accuracy: %.2f' % grid.best_score_)<|fim▁end|>
y = le.fit_transform(y)
<|file_name|>sanitizeUri.js<|end_file_name|><|fim▁begin|>'use strict'; /** * @description * Private service to sanitize uris for links and images. Used by $compile and $sanitize. */ function $$SanitizeUriProvider() { var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;<|fim▁hole|> * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { aHrefSanitizationWhitelist = regexp; return this; } return aHrefSanitizationWhitelist; }; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { imgSrcSanitizationWhitelist = regexp; return this; } return imgSrcSanitizationWhitelist; }; this.$get = function() { return function sanitizeUri(uri, isImage) { var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; var normalizedVal; // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. if (!msie || msie >= 8 ) { normalizedVal = urlResolve(uri).href; if (normalizedVal !== '' && !normalizedVal.match(regex)) { return 'unsafe:'+normalizedVal; } } return uri; }; }; }<|fim▁end|>
/**
<|file_name|>config.js<|end_file_name|><|fim▁begin|><|fim▁hole|> module.exports = { type: 'error', error: { line: 1, column: 3, message: 'Unexpected character \'💩\'.', }, };<|fim▁end|>
'use strict';
<|file_name|>qualityControl.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
# TODO implement a smoothing function perhaps # (Ie only accept frames within x distance of previous frame)
<|file_name|>firefox.d.ts<|end_file_name|><|fim▁begin|>interface ContentScriptPort { emit(method :string, data ?:Object) :void; on(method :string, handler :Function) :void; once(method :string, handler :Function) :void; removeListener(method :string, handler :Function) :void;<|fim▁hole|><|fim▁end|>
}
<|file_name|>test_c_agf2.py<|end_file_name|><|fim▁begin|># Copyright 2014-2020 The PySCF Developers. 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. # # Author: Oliver J. Backhouse <[email protected]> # George H. Booth <[email protected]> # import unittest import numpy as np from pyscf.agf2 import aux, _agf2 class KnownValues(unittest.TestCase): @classmethod def setUpClass(self): self.nmo = 100 self.nocc = 20 self.nvir = 80 self.naux = 400 np.random.seed(1) @classmethod def tearDownClass(self): del self.nmo, self.nocc, self.nvir, self.naux np.random.seed() <|fim▁hole|> gf_vir = aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)) vv1, vev1 = _agf2.build_mats_ragf2_outcore(xija, gf_occ.energy, gf_vir.energy) vv2, vev2 = _agf2.build_mats_ragf2_incore(xija, gf_occ.energy, gf_vir.energy) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) def test_c_dfragf2(self): qxi = np.random.random((self.naux, self.nmo*self.nocc)) / self.naux qja = np.random.random((self.naux, self.nocc*self.nvir)) / self.naux gf_occ = aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc)) gf_vir = aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)) vv1, vev1 = _agf2.build_mats_dfragf2_outcore(qxi, qja, gf_occ.energy, gf_vir.energy) vv2, vev2 = _agf2.build_mats_dfragf2_incore(qxi, qja, gf_occ.energy, gf_vir.energy) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) def test_c_uagf2(self): xija = np.random.random((2, self.nmo, self.nocc, self.nocc, self.nvir)) gf_occ = (aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc)), aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc))) gf_vir = (aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)), aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir))) vv1, vev1 = _agf2.build_mats_uagf2_outcore(xija, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) vv2, vev2 = _agf2.build_mats_uagf2_incore(xija, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) def test_c_dfuagf2(self): qxi = np.random.random((2, self.naux, self.nmo*self.nocc)) / self.naux qja = np.random.random((2, self.naux, self.nocc*self.nvir)) / self.naux gf_occ = (aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc)), aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc))) gf_vir = (aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir)), aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir))) vv1, vev1 = _agf2.build_mats_dfuagf2_outcore(qxi, qja, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) vv2, vev2 = _agf2.build_mats_dfuagf2_incore(qxi, qja, (gf_occ[0].energy, gf_occ[1].energy), (gf_vir[0].energy, gf_vir[1].energy)) self.assertAlmostEqual(np.max(np.absolute(vv1-vv2)), 0.0, 10) self.assertAlmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10) if __name__ == '__main__': print('AGF2 C implementations') unittest.main()<|fim▁end|>
def test_c_ragf2(self): xija = np.random.random((self.nmo, self.nocc, self.nocc, self.nvir)) gf_occ = aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc))
<|file_name|>split.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os,re,sys,pprint,shutil from pathlib import Path PACKAGES_DIR = "../packages" def errorExit(msg): print(msg) sys.exit(1) def isPathDisabled(path): for part in path.parts: if part.lower().startswith("_disabled"): return True return False depsFolder = Path("_deps_split") prodFolder = Path("_prods_split") merged_deps = Path("merged_deps.py" ) merged_prods = Path("merged_prods.py") if not os.path.isfile(merged_deps): errorExit("Merged depends file does not exist") if not os.path.isfile(merged_prods):<|fim▁hole|>if not os.path.isdir(depsFolder): os.makedirs(depsFolder) else: print("Clearing old split folder:" + str(depsFolder)) shutil.rmtree(depsFolder) os.makedirs(depsFolder) if not os.path.isdir(prodFolder): os.makedirs(prodFolder) else: print("Clearing old split folder:" + str(prodFolder)) shutil.rmtree(prodFolder) os.makedirs(prodFolder) things = { "merged_deps.py" : depsFolder, "merged_prods.py" : prodFolder, } for mergefile_name in things: mergedFile = None enableWrite = False curFile = None print("Splitting " +mergefile_name+ " into seperate files in " + str(things[mergefile_name])) with open(mergefile_name, "r", encoding="utf-8") as f: mergedFile = f.read().split("\n") fileBuffer = "" for line in mergedFile: startR = re.search("^########START:\[(.+)\]$",line) endR = re.search("^########END:\[(.+)\]$",line) if endR != None: enableWrite = False curFile.write(fileBuffer.rstrip("\n")) curFile.close() if enableWrite: fileBuffer+=line+"\n" if startR != None: enableWrite = True fileBuffer = "" curFile = open(os.path.join(things[mergefile_name],startR.groups()[0]) ,"w",encoding="utf-8") print("Done")<|fim▁end|>
errorExit("Merged products file does not exist")
<|file_name|>pe288-an-enormous-factorial.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding=utf-8 """288. An enormous factorial https://projecteuler.net/problem=288 For any prime p the number N(p,q) is defined by N(p,q) = ∑n=0 to q Tn*pn with Tn generated by the following random number generator: S0 = 290797 Sn+1 = Sn2 mod 50515093 Tn = Sn mod p Let Nfac(p,q) be the factorial of N(p,q). Let NF(p,q) be the number of factors p in Nfac(p,q). You are given that NF(3,10000) mod 320=624955285. <|fim▁hole|><|fim▁end|>
Find NF(61,107) mod 6110 """
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin from .models import EssNutr, FoodCategory<|fim▁hole|>admin.site.register(EssNutr) admin.site.register(FoodCategory)<|fim▁end|>
# Register your models here.
<|file_name|>pickletools.py<|end_file_name|><|fim▁begin|>'''"Executable documentation" for the pickle module. Extensive comments about the pickle protocols and pickle-machine opcodes can be found here. Some functions meant for external use: genops(pickle) Generate all the opcodes in a pickle, as (opcode, arg, position) triples. dis(pickle, out=None, memo=None, indentlevel=4) Print a symbolic disassembly of a pickle. ''' import codecs import io import pickle import re import sys __all__ = ['dis', 'genops', 'optimize'] bytes_types = pickle.bytes_types # Other ideas: # # - A pickle verifier: read a pickle and check it exhaustively for # well-formedness. dis() does a lot of this already. # # - A protocol identifier: examine a pickle and return its protocol number # (== the highest .proto attr value among all the opcodes in the pickle). # dis() already prints this info at the end. # # - A pickle optimizer: for example, tuple-building code is sometimes more # elaborate than necessary, catering for the possibility that the tuple # is recursive. Or lots of times a PUT is generated that's never accessed # by a later GET. # "A pickle" is a program for a virtual pickle machine (PM, but more accurately # called an unpickling machine). It's a sequence of opcodes, interpreted by the # PM, building an arbitrarily complex Python object. # # For the most part, the PM is very simple: there are no looping, testing, or # conditional instructions, no arithmetic and no function calls. Opcodes are # executed once each, from first to last, until a STOP opcode is reached. # # The PM has two data areas, "the stack" and "the memo". # # Many opcodes push Python objects onto the stack; e.g., INT pushes a Python # integer object on the stack, whose value is gotten from a decimal string # literal immediately following the INT opcode in the pickle bytestream. Other # opcodes take Python objects off the stack. The result of unpickling is # whatever object is left on the stack when the final STOP opcode is executed. # # The memo is simply an array of objects, or it can be implemented as a dict # mapping little integers to objects. The memo serves as the PM's "long term # memory", and the little integers indexing the memo are akin to variable # names. Some opcodes pop a stack object into the memo at a given index, # and others push a memo object at a given index onto the stack again. # # At heart, that's all the PM has. Subtleties arise for these reasons: # # + Object identity. Objects can be arbitrarily complex, and subobjects # may be shared (for example, the list [a, a] refers to the same object a # twice). It can be vital that unpickling recreate an isomorphic object # graph, faithfully reproducing sharing. # # + Recursive objects. For example, after "L = []; L.append(L)", L is a # list, and L[0] is the same list. This is related to the object identity # point, and some sequences of pickle opcodes are subtle in order to # get the right result in all cases. # # + Things pickle doesn't know everything about. Examples of things pickle # does know everything about are Python's builtin scalar and container # types, like ints and tuples. They generally have opcodes dedicated to # them. For things like module references and instances of user-defined # classes, pickle's knowledge is limited. Historically, many enhancements # have been made to the pickle protocol in order to do a better (faster, # and/or more compact) job on those. # # + Backward compatibility and micro-optimization. As explained below, # pickle opcodes never go away, not even when better ways to do a thing # get invented. The repertoire of the PM just keeps growing over time. # For example, protocol 0 had two opcodes for building Python integers (INT # and LONG), protocol 1 added three more for more-efficient pickling of short # integers, and protocol 2 added two more for more-efficient pickling of # long integers (before protocol 2, the only ways to pickle a Python long # took time quadratic in the number of digits, for both pickling and # unpickling). "Opcode bloat" isn't so much a subtlety as a source of # wearying complication. # # # Pickle protocols: # # For compatibility, the meaning of a pickle opcode never changes. Instead new # pickle opcodes get added, and each version's unpickler can handle all the # pickle opcodes in all protocol versions to date. So old pickles continue to # be readable forever. The pickler can generally be told to restrict itself to # the subset of opcodes available under previous protocol versions too, so that # users can create pickles under the current version readable by older # versions. However, a pickle does not contain its version number embedded # within it. If an older unpickler tries to read a pickle using a later # protocol, the result is most likely an exception due to seeing an unknown (in # the older unpickler) opcode. # # The original pickle used what's now called "protocol 0", and what was called # "text mode" before Python 2.3. The entire pickle bytestream is made up of # printable 7-bit ASCII characters, plus the newline character, in protocol 0. # That's why it was called text mode. Protocol 0 is small and elegant, but # sometimes painfully inefficient. # # The second major set of additions is now called "protocol 1", and was called # "binary mode" before Python 2.3. This added many opcodes with arguments # consisting of arbitrary bytes, including NUL bytes and unprintable "high bit" # bytes. Binary mode pickles can be substantially smaller than equivalent # text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte # int as 4 bytes following the opcode, which is cheaper to unpickle than the # (perhaps) 11-character decimal string attached to INT. Protocol 1 also added # a number of opcodes that operate on many stack elements at once (like APPENDS # and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE). # # The third major set of additions came in Python 2.3, and is called "protocol # 2". This added: # # - A better way to pickle instances of new-style classes (NEWOBJ). # # - A way for a pickle to identify its protocol (PROTO). # # - Time- and space- efficient pickling of long ints (LONG{1,4}). # # - Shortcuts for small tuples (TUPLE{1,2,3}}. # # - Dedicated opcodes for bools (NEWTRUE, NEWFALSE). # # - The "extension registry", a vector of popular objects that can be pushed # efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but # the registry contents are predefined (there's nothing akin to the memo's # PUT). # # Another independent change with Python 2.3 is the abandonment of any # pretense that it might be safe to load pickles received from untrusted # parties -- no sufficient security analysis has been done to guarantee # this and there isn't a use case that warrants the expense of such an # analysis. # # To this end, all tests for __safe_for_unpickling__ or for # copyreg.safe_constructors are removed from the unpickling code. # References to these variables in the descriptions below are to be seen # as describing unpickling in Python 2.2 and before. # Meta-rule: Descriptions are stored in instances of descriptor objects, # with plain constructors. No meta-language is defined from which # descriptors could be constructed. If you want, e.g., XML, write a little # program to generate XML from the objects. ############################################################################## # Some pickle opcodes have an argument, following the opcode in the # bytestream. An argument is of a specific type, described by an instance # of ArgumentDescriptor. These are not to be confused with arguments taken # off the stack -- ArgumentDescriptor applies only to arguments embedded in # the opcode stream, immediately following an opcode. # Represents the number of bytes consumed by an argument delimited by the # next newline character. UP_TO_NEWLINE = -1 # Represents the number of bytes consumed by a two-argument opcode where # the first argument gives the number of bytes in the second argument. TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int TAKEN_FROM_ARGUMENT4U = -4 # num bytes is 4-byte unsigned little-endian int TAKEN_FROM_ARGUMENT8U = -5 # num bytes is 8-byte unsigned little-endian int class ArgumentDescriptor(object): __slots__ = ( # name of descriptor record, also a module global name; a string 'name', # length of argument, in bytes; an int; UP_TO_NEWLINE and # TAKEN_FROM_ARGUMENT{1,4,8} are negative values for variable-length # cases 'n', # a function taking a file-like object, reading this kind of argument # from the object at the current position, advancing the current # position by n bytes, and returning the value of the argument 'reader', # human-readable docs for this arg descriptor; a string 'doc', ) def __init__(self, name, n, reader, doc): assert isinstance(name, str) self.name = name assert isinstance(n, int) and (n >= 0 or n in (UP_TO_NEWLINE, TAKEN_FROM_ARGUMENT1, TAKEN_FROM_ARGUMENT4, TAKEN_FROM_ARGUMENT4U, TAKEN_FROM_ARGUMENT8U)) self.n = n self.reader = reader assert isinstance(doc, str) self.doc = doc from struct import unpack as _unpack def read_uint1(f): r""" >>> import io >>> read_uint1(io.BytesIO(b'\xff')) 255 """ data = f.read(1) if data: return data[0] raise ValueError("not enough data in stream to read uint1") uint1 = ArgumentDescriptor( name='uint1', n=1, reader=read_uint1, doc="One-byte unsigned integer.") def read_uint2(f): r""" >>> import io >>> read_uint2(io.BytesIO(b'\xff\x00')) 255 >>> read_uint2(io.BytesIO(b'\xff\xff')) 65535 """ data = f.read(2) if len(data) == 2: return _unpack("<H", data)[0] raise ValueError("not enough data in stream to read uint2") uint2 = ArgumentDescriptor( name='uint2', n=2, reader=read_uint2, doc="Two-byte unsigned integer, little-endian.") def read_int4(f): r""" >>> import io >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00')) 255 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31) True """ data = f.read(4) if len(data) == 4: return _unpack("<i", data)[0] raise ValueError("not enough data in stream to read int4") int4 = ArgumentDescriptor( name='int4', n=4, reader=read_int4, doc="Four-byte signed integer, little-endian, 2's complement.") def read_uint4(f): r""" >>> import io >>> read_uint4(io.BytesIO(b'\xff\x00\x00\x00')) 255 >>> read_uint4(io.BytesIO(b'\x00\x00\x00\x80')) == 2**31 True """ data = f.read(4) if len(data) == 4: return _unpack("<I", data)[0] raise ValueError("not enough data in stream to read uint4") uint4 = ArgumentDescriptor( name='uint4', n=4, reader=read_uint4, doc="Four-byte unsigned integer, little-endian.") def read_uint8(f): r""" >>> import io >>> read_uint8(io.BytesIO(b'\xff\x00\x00\x00\x00\x00\x00\x00')) 255 >>> read_uint8(io.BytesIO(b'\xff' * 8)) == 2**64-1 True """ data = f.read(8) if len(data) == 8: return _unpack("<Q", data)[0] raise ValueError("not enough data in stream to read uint8") uint8 = ArgumentDescriptor( name='uint8', n=8, reader=read_uint8, doc="Eight-byte unsigned integer, little-endian.") def read_stringnl(f, decode=True, stripquotes=True): r""" >>> import io >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n")) 'abcd' >>> read_stringnl(io.BytesIO(b"\n")) Traceback (most recent call last): ... ValueError: no string quotes around b'' >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False) '' >>> read_stringnl(io.BytesIO(b"''\n")) '' >>> read_stringnl(io.BytesIO(b'"abcd"')) Traceback (most recent call last): ... ValueError: no newline found when trying to read stringnl Embedded escapes are undone in the result. >>> read_stringnl(io.BytesIO(br"'a\n\\b\x00c\td'" + b"\n'e'")) 'a\n\\b\x00c\td' """ data = f.readline() if not data.endswith(b'\n'): raise ValueError("no newline found when trying to read stringnl") data = data[:-1] # lose the newline if stripquotes: for q in (b'"', b"'"): if data.startswith(q): if not data.endswith(q): raise ValueError("strinq quote %r not found at both " "ends of %r" % (q, data)) data = data[1:-1] break else: raise ValueError("no string quotes around %r" % data) if decode: data = codecs.escape_decode(data)[0].decode("ascii") return data stringnl = ArgumentDescriptor( name='stringnl', n=UP_TO_NEWLINE, reader=read_stringnl, doc="""A newline-terminated string. This is a repr-style string, with embedded escapes, and bracketing quotes. """) def read_stringnl_noescape(f): return read_stringnl(f, stripquotes=False) stringnl_noescape = ArgumentDescriptor( name='stringnl_noescape', n=UP_TO_NEWLINE, reader=read_stringnl_noescape, doc="""A newline-terminated string. This is a str-style string, without embedded escapes, or bracketing quotes. It should consist solely of printable ASCII characters. """) def read_stringnl_noescape_pair(f): r""" >>> import io >>> read_stringnl_noescape_pair(io.BytesIO(b"Queue\nEmpty\njunk")) 'Queue Empty' """ return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f)) stringnl_noescape_pair = ArgumentDescriptor( name='stringnl_noescape_pair', n=UP_TO_NEWLINE, reader=read_stringnl_noescape_pair, doc="""A pair of newline-terminated strings. These are str-style strings, without embedded escapes, or bracketing quotes. They should consist solely of printable ASCII characters. The pair is returned as a single string, with a single blank separating the two strings. """) def read_string1(f): r""" >>> import io >>> read_string1(io.BytesIO(b"\x00")) '' >>> read_string1(io.BytesIO(b"\x03abcdef")) 'abc' """ n = read_uint1(f) assert n >= 0 data = f.read(n) if len(data) == n: return data.decode("latin-1") raise ValueError("expected %d bytes in a string1, but only %d remain" % (n, len(data))) string1 = ArgumentDescriptor( name="string1", n=TAKEN_FROM_ARGUMENT1, reader=read_string1, doc="""A counted string. The first argument is a 1-byte unsigned int giving the number of bytes in the string, and the second argument is that many bytes. """) def read_string4(f): r""" >>> import io >>> read_string4(io.BytesIO(b"\x00\x00\x00\x00abc")) '' >>> read_string4(io.BytesIO(b"\x03\x00\x00\x00abcdef")) 'abc' >>> read_string4(io.BytesIO(b"\x00\x00\x00\x03abcdef")) Traceback (most recent call last): ... ValueError: expected 50331648 bytes in a string4, but only 6 remain """ n = read_int4(f) if n < 0: raise ValueError("string4 byte count < 0: %d" % n) data = f.read(n) if len(data) == n: return data.decode("latin-1") raise ValueError("expected %d bytes in a string4, but only %d remain" % (n, len(data))) string4 = ArgumentDescriptor( name="string4", n=TAKEN_FROM_ARGUMENT4, reader=read_string4, doc="""A counted string. The first argument is a 4-byte little-endian signed int giving the number of bytes in the string, and the second argument is that many bytes. """) def read_bytes1(f): r""" >>> import io >>> read_bytes1(io.BytesIO(b"\x00")) b'' >>> read_bytes1(io.BytesIO(b"\x03abcdef")) b'abc' """ n = read_uint1(f) assert n >= 0 data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a bytes1, but only %d remain" % (n, len(data))) bytes1 = ArgumentDescriptor( name="bytes1", n=TAKEN_FROM_ARGUMENT1, reader=read_bytes1, doc="""A counted bytes string. The first argument is a 1-byte unsigned int giving the number of bytes in the string, and the second argument is that many bytes. """) def read_bytes1(f): r""" >>> import io >>> read_bytes1(io.BytesIO(b"\x00")) b'' >>> read_bytes1(io.BytesIO(b"\x03abcdef")) b'abc' """ n = read_uint1(f) assert n >= 0 data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a bytes1, but only %d remain" % (n, len(data))) bytes1 = ArgumentDescriptor( name="bytes1", n=TAKEN_FROM_ARGUMENT1, reader=read_bytes1, doc="""A counted bytes string. The first argument is a 1-byte unsigned int giving the number of bytes, and the second argument is that many bytes. """) def read_bytes4(f): r""" >>> import io >>> read_bytes4(io.BytesIO(b"\x00\x00\x00\x00abc")) b'' >>> read_bytes4(io.BytesIO(b"\x03\x00\x00\x00abcdef")) b'abc' >>> read_bytes4(io.BytesIO(b"\x00\x00\x00\x03abcdef")) Traceback (most recent call last): ... ValueError: expected 50331648 bytes in a bytes4, but only 6 remain """ n = read_uint4(f) assert n >= 0 if n > sys.maxsize: raise ValueError("bytes4 byte count > sys.maxsize: %d" % n) data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a bytes4, but only %d remain" % (n, len(data))) bytes4 = ArgumentDescriptor( name="bytes4", n=TAKEN_FROM_ARGUMENT4U, reader=read_bytes4, doc="""A counted bytes string. The first argument is a 4-byte little-endian unsigned int giving the number of bytes, and the second argument is that many bytes. """) def read_bytes8(f): r""" >>> import io, struct, sys >>> read_bytes8(io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00abc")) b'' >>> read_bytes8(io.BytesIO(b"\x03\x00\x00\x00\x00\x00\x00\x00abcdef")) b'abc' >>> bigsize8 = struct.pack("<Q", sys.maxsize//3) >>> read_bytes8(io.BytesIO(bigsize8 + b"abcdef")) #doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: expected ... bytes in a bytes8, but only 6 remain """ n = read_uint8(f) assert n >= 0 if n > sys.maxsize: raise ValueError("bytes8 byte count > sys.maxsize: %d" % n) data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a bytes8, but only %d remain" % (n, len(data))) bytes8 = ArgumentDescriptor( name="bytes8", n=TAKEN_FROM_ARGUMENT8U, reader=read_bytes8, doc="""A counted bytes string. The first argument is an 8-byte little-endian unsigned int giving the number of bytes, and the second argument is that many bytes. """) def read_unicodestringnl(f): r""" >>> import io >>> read_unicodestringnl(io.BytesIO(b"abc\\uabcd\njunk")) == 'abc\uabcd' True """ data = f.readline() if not data.endswith(b'\n'): raise ValueError("no newline found when trying to read " "unicodestringnl") data = data[:-1] # lose the newline return str(data, 'raw-unicode-escape') unicodestringnl = ArgumentDescriptor( name='unicodestringnl', n=UP_TO_NEWLINE, reader=read_unicodestringnl, doc="""A newline-terminated Unicode string. This is raw-unicode-escape encoded, so consists of printable ASCII characters, and may contain embedded escape sequences. """) def read_unicodestring1(f): r""" >>> import io >>> s = 'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc b'abcd\xea\xaf\x8d' >>> n = bytes([len(enc)]) # little-endian 1-byte length >>> t = read_unicodestring1(io.BytesIO(n + enc + b'junk')) >>> s == t True >>> read_unicodestring1(io.BytesIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring1, but only 6 remain """ n = read_uint1(f) assert n >= 0 data = f.read(n) if len(data) == n: return str(data, 'utf-8', 'surrogatepass') raise ValueError("expected %d bytes in a unicodestring1, but only %d " "remain" % (n, len(data))) unicodestring1 = ArgumentDescriptor( name="unicodestring1", n=TAKEN_FROM_ARGUMENT1, reader=read_unicodestring1, doc="""A counted Unicode string. The first argument is a 1-byte little-endian signed int giving the number of bytes in the string, and the second argument-- the UTF-8 encoding of the Unicode string -- contains that many bytes. """) def read_unicodestring4(f): r""" >>> import io >>> s = 'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc b'abcd\xea\xaf\x8d' >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk')) >>> s == t True >>> read_unicodestring4(io.BytesIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring4, but only 6 remain """ n = read_uint4(f) assert n >= 0 if n > sys.maxsize: raise ValueError("unicodestring4 byte count > sys.maxsize: %d" % n) data = f.read(n) if len(data) == n: return str(data, 'utf-8', 'surrogatepass') raise ValueError("expected %d bytes in a unicodestring4, but only %d " "remain" % (n, len(data))) unicodestring4 = ArgumentDescriptor( name="unicodestring4", n=TAKEN_FROM_ARGUMENT4U, reader=read_unicodestring4, doc="""A counted Unicode string. The first argument is a 4-byte little-endian signed int giving the number of bytes in the string, and the second argument-- the UTF-8 encoding of the Unicode string -- contains that many bytes. """) def read_unicodestring8(f): r""" >>> import io >>> s = 'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc b'abcd\xea\xaf\x8d' >>> n = bytes([len(enc)]) + b'\0' * 7 # little-endian 8-byte length >>> t = read_unicodestring8(io.BytesIO(n + enc + b'junk')) >>> s == t True >>> read_unicodestring8(io.BytesIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring8, but only 6 remain """ n = read_uint8(f) assert n >= 0 if n > sys.maxsize: raise ValueError("unicodestring8 byte count > sys.maxsize: %d" % n) data = f.read(n) if len(data) == n: return str(data, 'utf-8', 'surrogatepass') raise ValueError("expected %d bytes in a unicodestring8, but only %d " "remain" % (n, len(data))) unicodestring8 = ArgumentDescriptor( name="unicodestring8", n=TAKEN_FROM_ARGUMENT8U, reader=read_unicodestring8, doc="""A counted Unicode string. The first argument is an 8-byte little-endian signed int giving the number of bytes in the string, and the second argument-- the UTF-8 encoding of the Unicode string -- contains that many bytes. """) def read_decimalnl_short(f): r""" >>> import io >>> read_decimalnl_short(io.BytesIO(b"1234\n56")) 1234 >>> read_decimalnl_short(io.BytesIO(b"1234L\n56")) Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: b'1234L' """ s = read_stringnl(f, decode=False, stripquotes=False) # There's a hack for True and False here. if s == b"00": return False elif s == b"01": return True return int(s) def read_decimalnl_long(f): r""" >>> import io >>> read_decimalnl_long(io.BytesIO(b"1234L\n56")) 1234 >>> read_decimalnl_long(io.BytesIO(b"123456789012345678901234L\n6")) 123456789012345678901234 """ s = read_stringnl(f, decode=False, stripquotes=False) if s[-1:] == b'L': s = s[:-1] return int(s) decimalnl_short = ArgumentDescriptor( name='decimalnl_short', n=UP_TO_NEWLINE, reader=read_decimalnl_short, doc="""A newline-terminated decimal integer literal. This never has a trailing 'L', and the integer fit in a short Python int on the box where the pickle was written -- but there's no guarantee it will fit in a short Python int on the box where the pickle is read. """) decimalnl_long = ArgumentDescriptor( name='decimalnl_long', n=UP_TO_NEWLINE, reader=read_decimalnl_long, doc="""A newline-terminated decimal integer literal. This has a trailing 'L', and can represent integers of any size. """) def read_floatnl(f): r""" >>> import io >>> read_floatnl(io.BytesIO(b"-1.25\n6")) -1.25 """ s = read_stringnl(f, decode=False, stripquotes=False) return float(s) floatnl = ArgumentDescriptor( name='floatnl', n=UP_TO_NEWLINE, reader=read_floatnl, doc="""A newline-terminated decimal floating literal. In general this requires 17 significant digits for roundtrip identity, and pickling then unpickling infinities, NaNs, and minus zero doesn't work across boxes, or on some boxes even on itself (e.g., Windows can't read the strings it produces for infinities or NaNs). """) def read_float8(f): r""" >>> import io, struct >>> raw = struct.pack(">d", -1.25) >>> raw b'\xbf\xf4\x00\x00\x00\x00\x00\x00' >>> read_float8(io.BytesIO(raw + b"\n")) -1.25 """ data = f.read(8) if len(data) == 8: return _unpack(">d", data)[0] raise ValueError("not enough data in stream to read float8") float8 = ArgumentDescriptor( name='float8', n=8, reader=read_float8, doc="""An 8-byte binary representation of a float, big-endian. The format is unique to Python, and shared with the struct module (format string '>d') "in theory" (the struct and pickle implementations don't share the code -- they should). It's strongly related to the IEEE-754 double format, and, in normal cases, is in fact identical to the big-endian 754 double format. On other boxes the dynamic range is limited to that of a 754 double, and "add a half and chop" rounding is used to reduce the precision to 53 bits. However, even on a 754 box, infinities, NaNs, and minus zero may not be handled correctly (may not survive roundtrip pickling intact). """) # Protocol 2 formats from pickle import decode_long def read_long1(f): r""" >>> import io >>> read_long1(io.BytesIO(b"\x00")) 0 >>> read_long1(io.BytesIO(b"\x02\xff\x00")) 255 >>> read_long1(io.BytesIO(b"\x02\xff\x7f")) 32767 >>> read_long1(io.BytesIO(b"\x02\x00\xff")) -256 >>> read_long1(io.BytesIO(b"\x02\x00\x80")) -32768 """ n = read_uint1(f) data = f.read(n) if len(data) != n: raise ValueError("not enough data in stream to read long1") return decode_long(data) long1 = ArgumentDescriptor( name="long1", n=TAKEN_FROM_ARGUMENT1, reader=read_long1, doc="""A binary long, little-endian, using 1-byte size. This first reads one byte as an unsigned size, then reads that many bytes and interprets them as a little-endian 2's-complement long. If the size is 0, that's taken as a shortcut for the long 0L. """) def read_long4(f): r""" >>> import io >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x00")) 255 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x7f")) 32767 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\xff")) -256 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\x80")) -32768 >>> read_long1(io.BytesIO(b"\x00\x00\x00\x00")) 0 """ n = read_int4(f) if n < 0: raise ValueError("long4 byte count < 0: %d" % n) data = f.read(n) if len(data) != n: raise ValueError("not enough data in stream to read long4") return decode_long(data) long4 = ArgumentDescriptor( name="long4", n=TAKEN_FROM_ARGUMENT4, reader=read_long4, doc="""A binary representation of a long, little-endian. This first reads four bytes as a signed size (but requires the size to be >= 0), then reads that many bytes and interprets them as a little-endian 2's-complement long. If the size is 0, that's taken as a shortcut for the int 0, although LONG1 should really be used then instead (and in any case where # of bytes < 256). """) ############################################################################## # Object descriptors. The stack used by the pickle machine holds objects, # and in the stack_before and stack_after attributes of OpcodeInfo # descriptors we need names to describe the various types of objects that can # appear on the stack. class StackObject(object): __slots__ = ( # name of descriptor record, for info only 'name', # type of object, or tuple of type objects (meaning the object can # be of any type in the tuple) 'obtype', # human-readable docs for this kind of stack object; a string 'doc', ) def __init__(self, name, obtype, doc): assert isinstance(name, str) self.name = name assert isinstance(obtype, type) or isinstance(obtype, tuple) if isinstance(obtype, tuple): for contained in obtype: assert isinstance(contained, type) self.obtype = obtype assert isinstance(doc, str) self.doc = doc def __repr__(self): return self.name pyint = pylong = StackObject( name='int', obtype=int, doc="A Python integer object.") pyinteger_or_bool = StackObject( name='int_or_bool', obtype=(int, bool), doc="A Python integer or boolean object.") pybool = StackObject( name='bool', obtype=bool, doc="A Python boolean object.") pyfloat = StackObject( name='float', obtype=float, doc="A Python float object.") pybytes_or_str = pystring = StackObject( name='bytes_or_str', obtype=(bytes, str), doc="A Python bytes or (Unicode) string object.") pybytes = StackObject( name='bytes', obtype=bytes, doc="A Python bytes object.") pyunicode = StackObject( name='str', obtype=str, doc="A Python (Unicode) string object.") pynone = StackObject( name="None", obtype=type(None), doc="The Python None object.") pytuple = StackObject( name="tuple", obtype=tuple, doc="A Python tuple object.") pylist = StackObject( name="list", obtype=list, doc="A Python list object.") pydict = StackObject( name="dict", obtype=dict, doc="A Python dict object.") pyset = StackObject( name="set", obtype=set, doc="A Python set object.") pyfrozenset = StackObject( name="frozenset", obtype=set, doc="A Python frozenset object.") anyobject = StackObject( name='any', obtype=object, doc="Any kind of object whatsoever.") markobject = StackObject( name="mark", obtype=StackObject, doc="""'The mark' is a unique object. Opcodes that operate on a variable number of objects generally don't embed the count of objects in the opcode, or pull it off the stack. Instead the MARK opcode is used to push a special marker object on the stack, and then some other opcodes grab all the objects from the top of the stack down to (but not including) the topmost marker object. """) stackslice = StackObject( name="stackslice", obtype=StackObject, doc="""An object representing a contiguous slice of the stack. This is used in conjunction with markobject, to represent all of the stack following the topmost markobject. For example, the POP_MARK opcode changes the stack from [..., markobject, stackslice] to [...] No matter how many object are on the stack after the topmost markobject, POP_MARK gets rid of all of them (including the topmost markobject too). """) ############################################################################## # Descriptors for pickle opcodes. class OpcodeInfo(object): __slots__ = ( # symbolic name of opcode; a string 'name', # the code used in a bytestream to represent the opcode; a # one-character string 'code', # If the opcode has an argument embedded in the byte string, an # instance of ArgumentDescriptor specifying its type. Note that # arg.reader(s) can be used to read and decode the argument from # the bytestream s, and arg.doc documents the format of the raw # argument bytes. If the opcode doesn't have an argument embedded # in the bytestream, arg should be None. 'arg', # what the stack looks like before this opcode runs; a list 'stack_before', # what the stack looks like after this opcode runs; a list 'stack_after', # the protocol number in which this opcode was introduced; an int 'proto', # human-readable docs for this opcode; a string 'doc', ) def __init__(self, name, code, arg, stack_before, stack_after, proto, doc): assert isinstance(name, str) self.name = name assert isinstance(code, str) assert len(code) == 1 self.code = code assert arg is None or isinstance(arg, ArgumentDescriptor) self.arg = arg assert isinstance(stack_before, list) for x in stack_before: assert isinstance(x, StackObject) self.stack_before = stack_before assert isinstance(stack_after, list) for x in stack_after: assert isinstance(x, StackObject) self.stack_after = stack_after assert isinstance(proto, int) and 0 <= proto <= pickle.HIGHEST_PROTOCOL self.proto = proto assert isinstance(doc, str) self.doc = doc I = OpcodeInfo opcodes = [ # Ways to spell integers. I(name='INT', code='I', arg=decimalnl_short, stack_before=[], stack_after=[pyinteger_or_bool], proto=0, doc="""Push an integer or bool. The argument is a newline-terminated decimal literal string. The intent may have been that this always fit in a short Python int, but INT can be generated in pickles written on a 64-bit box that require a Python long on a 32-bit box. The difference between this and LONG then is that INT skips a trailing 'L', and produces a short int whenever possible. Another difference is due to that, when bool was introduced as a distinct type in 2.3, builtin names True and False were also added to 2.2.2, mapping to ints 1 and 0. For compatibility in both directions, True gets pickled as INT + "I01\\n", and False as INT + "I00\\n". Leading zeroes are never produced for a genuine integer. The 2.3 (and later) unpicklers special-case these and return bool instead; earlier unpicklers ignore the leading "0" and return the int. """), I(name='BININT', code='J', arg=int4, stack_before=[], stack_after=[pyint], proto=1, doc="""Push a four-byte signed integer. This handles the full range of Python (short) integers on a 32-bit box, directly as binary bytes (1 for the opcode and 4 for the integer). If the integer is non-negative and fits in 1 or 2 bytes, pickling via BININT1 or BININT2 saves space. """), I(name='BININT1', code='K', arg=uint1, stack_before=[], stack_after=[pyint], proto=1, doc="""Push a one-byte unsigned integer. This is a space optimization for pickling very small non-negative ints, in range(256). """), I(name='BININT2', code='M', arg=uint2, stack_before=[], stack_after=[pyint], proto=1, doc="""Push a two-byte unsigned integer. This is a space optimization for pickling small positive ints, in range(256, 2**16). Integers in range(256) can also be pickled via BININT2, but BININT1 instead saves a byte. """), I(name='LONG', code='L', arg=decimalnl_long, stack_before=[], stack_after=[pyint], proto=0, doc="""Push a long integer. The same as INT, except that the literal ends with 'L', and always unpickles to a Python long. There doesn't seem a real purpose to the trailing 'L'. Note that LONG takes time quadratic in the number of digits when unpickling (this is simply due to the nature of decimal->binary conversion). Proto 2 added linear-time (in C; still quadratic-time in Python) LONG1 and LONG4 opcodes. """), I(name="LONG1", code='\x8a', arg=long1, stack_before=[], stack_after=[pyint], proto=2, doc="""Long integer using one-byte length. A more efficient encoding of a Python long; the long1 encoding says it all."""), I(name="LONG4", code='\x8b', arg=long4, stack_before=[], stack_after=[pyint], proto=2, doc="""Long integer using found-byte length. A more efficient encoding of a Python long; the long4 encoding says it all."""), # Ways to spell strings (8-bit, not Unicode). I(name='STRING', code='S', arg=stringnl, stack_before=[], stack_after=[pybytes_or_str], proto=0, doc="""Push a Python string object. The argument is a repr-style string, with bracketing quote characters, and perhaps embedded escapes. The argument extends until the next newline character. These are usually decoded into a str instance using the encoding given to the Unpickler constructor. or the default, 'ASCII'. If the encoding given was 'bytes' however, they will be decoded as bytes object instead. """), I(name='BINSTRING', code='T', arg=string4, stack_before=[], stack_after=[pybytes_or_str], proto=1, doc="""Push a Python string object. There are two arguments: the first is a 4-byte little-endian signed int giving the number of bytes in the string, and the second is that many bytes, which are taken literally as the string content. These are usually decoded into a str instance using the encoding given to the Unpickler constructor. or the default, 'ASCII'. If the encoding given was 'bytes' however, they will be decoded as bytes object instead. """), I(name='SHORT_BINSTRING', code='U', arg=string1, stack_before=[], stack_after=[pybytes_or_str], proto=1, doc="""Push a Python string object. There are two arguments: the first is a 1-byte unsigned int giving the number of bytes in the string, and the second is that many bytes, which are taken literally as the string content. These are usually decoded into a str instance using the encoding given to the Unpickler constructor. or the default, 'ASCII'. If the encoding given was 'bytes' however, they will be decoded as bytes object instead. """), # Bytes (protocol 3 only; older protocols don't support bytes at all) I(name='BINBYTES', code='B', arg=bytes4, stack_before=[], stack_after=[pybytes], proto=3, doc="""Push a Python bytes object. There are two arguments: the first is a 4-byte little-endian unsigned int giving the number of bytes, and the second is that many bytes, which are taken literally as the bytes content. """), I(name='SHORT_BINBYTES', code='C', arg=bytes1, stack_before=[], stack_after=[pybytes], proto=3, doc="""Push a Python bytes object. There are two arguments: the first is a 1-byte unsigned int giving the number of bytes, and the second is that many bytes, which are taken literally as the string content. """), I(name='BINBYTES8', code='\x8e', arg=bytes8, stack_before=[], stack_after=[pybytes], proto=4, doc="""Push a Python bytes object. There are two arguments: the first is an 8-byte unsigned int giving the number of bytes in the string, and the second is that many bytes, which are taken literally as the string content. """), # Ways to spell None. I(name='NONE', code='N', arg=None, stack_before=[], stack_after=[pynone], proto=0, doc="Push None on the stack."), # Ways to spell bools, starting with proto 2. See INT for how this was # done before proto 2. I(name='NEWTRUE', code='\x88', arg=None, stack_before=[], stack_after=[pybool], proto=2, doc="""True. Push True onto the stack."""), I(name='NEWFALSE', code='\x89', arg=None, stack_before=[], stack_after=[pybool], proto=2, doc="""True. Push False onto the stack."""), # Ways to spell Unicode strings. I(name='UNICODE', code='V', arg=unicodestringnl, stack_before=[], stack_after=[pyunicode], proto=0, # this may be pure-text, but it's a later addition doc="""Push a Python Unicode string object. The argument is a raw-unicode-escape encoding of a Unicode string, and so may contain embedded escape sequences. The argument extends until the next newline character. """), I(name='SHORT_BINUNICODE', code='\x8c', arg=unicodestring1, stack_before=[], stack_after=[pyunicode], proto=4, doc="""Push a Python Unicode string object. There are two arguments: the first is a 1-byte little-endian signed int giving the number of bytes in the string. The second is that many bytes, and is the UTF-8 encoding of the Unicode string. """), I(name='BINUNICODE', code='X', arg=unicodestring4, stack_before=[], stack_after=[pyunicode], proto=1, doc="""Push a Python Unicode string object. There are two arguments: the first is a 4-byte little-endian unsigned int giving the number of bytes in the string. The second is that many bytes, and is the UTF-8 encoding of the Unicode string. """), I(name='BINUNICODE8', code='\x8d', arg=unicodestring8, stack_before=[], stack_after=[pyunicode], proto=4, doc="""Push a Python Unicode string object. There are two arguments: the first is an 8-byte little-endian signed int giving the number of bytes in the string. The second is that many bytes, and is the UTF-8 encoding of the Unicode string. """), # Ways to spell floats. I(name='FLOAT', code='F', arg=floatnl, stack_before=[], stack_after=[pyfloat], proto=0, doc="""Newline-terminated decimal float literal. The argument is repr(a_float), and in general requires 17 significant digits for roundtrip conversion to be an identity (this is so for IEEE-754 double precision values, which is what Python float maps to on most boxes). In general, FLOAT cannot be used to transport infinities, NaNs, or minus zero across boxes (or even on a single box, if the platform C library can't read the strings it produces for such things -- Windows is like that), but may do less damage than BINFLOAT on boxes with greater precision or dynamic range than IEEE-754 double. """), I(name='BINFLOAT', code='G', arg=float8, stack_before=[], stack_after=[pyfloat], proto=1, doc="""Float stored in binary form, with 8 bytes of data. This generally requires less than half the space of FLOAT encoding. In general, BINFLOAT cannot be used to transport infinities, NaNs, or minus zero, raises an exception if the exponent exceeds the range of an IEEE-754 double, and retains no more than 53 bits of precision (if there are more than that, "add a half and chop" rounding is used to cut it back to 53 significant bits). """), # Ways to build lists. I(name='EMPTY_LIST', code=']', arg=None, stack_before=[], stack_after=[pylist], proto=1, doc="Push an empty list."), I(name='APPEND', code='a', arg=None, stack_before=[pylist, anyobject], stack_after=[pylist], proto=0, doc="""Append an object to a list. Stack before: ... pylist anyobject Stack after: ... pylist+[anyobject] although pylist is really extended in-place. """), I(name='APPENDS', code='e', arg=None, stack_before=[pylist, markobject, stackslice], stack_after=[pylist], proto=1, doc="""Extend a list by a slice of stack objects. Stack before: ... pylist markobject stackslice Stack after: ... pylist+stackslice although pylist is really extended in-place. """), I(name='LIST', code='l', arg=None, stack_before=[markobject, stackslice], stack_after=[pylist], proto=0, doc="""Build a list out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python list, which single list object replaces all of the stack from the topmost markobject onward. For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... [1, 2, 3, 'abc'] """), # Ways to build tuples. I(name='EMPTY_TUPLE', code=')', arg=None, stack_before=[], stack_after=[pytuple], proto=1, doc="Push an empty tuple."), I(name='TUPLE', code='t', arg=None, stack_before=[markobject, stackslice], stack_after=[pytuple], proto=0, doc="""Build a tuple out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python tuple, which single tuple object replaces all of the stack from the topmost markobject onward. For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... (1, 2, 3, 'abc') """), I(name='TUPLE1', code='\x85', arg=None, stack_before=[anyobject], stack_after=[pytuple], proto=2, doc="""Build a one-tuple out of the topmost item on the stack. This code pops one value off the stack and pushes a tuple of length 1 whose one item is that value back onto it. In other words: stack[-1] = tuple(stack[-1:]) """), I(name='TUPLE2', code='\x86', arg=None, stack_before=[anyobject, anyobject], stack_after=[pytuple], proto=2, doc="""Build a two-tuple out of the top two items on the stack. This code pops two values off the stack and pushes a tuple of length 2 whose items are those values back onto it. In other words: stack[-2:] = [tuple(stack[-2:])] """), I(name='TUPLE3', code='\x87', arg=None, stack_before=[anyobject, anyobject, anyobject], stack_after=[pytuple], proto=2, doc="""Build a three-tuple out of the top three items on the stack. This code pops three values off the stack and pushes a tuple of length 3 whose items are those values back onto it. In other words: stack[-3:] = [tuple(stack[-3:])] """), # Ways to build dicts. I(name='EMPTY_DICT', code='}', arg=None, stack_before=[], stack_after=[pydict], proto=1, doc="Push an empty dict."), I(name='DICT', code='d', arg=None, stack_before=[markobject, stackslice], stack_after=[pydict], proto=0, doc="""Build a dict out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python dict, which single dict object replaces all of the stack from the topmost markobject onward. The stack slice alternates key, value, key, value, .... For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... {1: 2, 3: 'abc'} """), I(name='SETITEM', code='s', arg=None, stack_before=[pydict, anyobject, anyobject], stack_after=[pydict], proto=0, doc="""Add a key+value pair to an existing dict. Stack before: ... pydict key value Stack after: ... pydict where pydict has been modified via pydict[key] = value. """), I(name='SETITEMS', code='u', arg=None, stack_before=[pydict, markobject, stackslice], stack_after=[pydict], proto=1, doc="""Add an arbitrary number of key+value pairs to an existing dict. The slice of the stack following the topmost markobject is taken as an alternating sequence of keys and values, added to the dict immediately under the topmost markobject. Everything at and after the topmost markobject is popped, leaving the mutated dict at the top of the stack. Stack before: ... pydict markobject key_1 value_1 ... key_n value_n Stack after: ... pydict where pydict has been modified via pydict[key_i] = value_i for i in 1, 2, ..., n, and in that order. """), # Ways to build sets I(name='EMPTY_SET', code='\x8f', arg=None, stack_before=[], stack_after=[pyset], proto=4, doc="Push an empty set."), I(name='ADDITEMS', code='\x90', arg=None, stack_before=[pyset, markobject, stackslice], stack_after=[pyset], proto=4, doc="""Add an arbitrary number of items to an existing set. The slice of the stack following the topmost markobject is taken as a sequence of items, added to the set immediately under the topmost markobject. Everything at and after the topmost markobject is popped, leaving the mutated set at the top of the stack. Stack before: ... pyset markobject item_1 ... item_n Stack after: ... pyset where pyset has been modified via pyset.add(item_i) = item_i for i in 1, 2, ..., n, and in that order. """), # Way to build frozensets I(name='FROZENSET', code='\x91', arg=None, stack_before=[markobject, stackslice], stack_after=[pyfrozenset], proto=4, doc="""Build a frozenset out of the topmost slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python frozenset, which single frozenset object replaces all of the stack from the topmost markobject onward. For example, Stack before: ... markobject 1 2 3 Stack after: ... frozenset({1, 2, 3}) """), # Stack manipulation. I(name='POP', code='0', arg=None, stack_before=[anyobject], stack_after=[], proto=0, doc="Discard the top stack item, shrinking the stack by one item."), I(name='DUP', code='2', arg=None, stack_before=[anyobject], stack_after=[anyobject, anyobject], proto=0, doc="Push the top stack item onto the stack again, duplicating it."), I(name='MARK', code='(', arg=None, stack_before=[], stack_after=[markobject], proto=0, doc="""Push markobject onto the stack. markobject is a unique object, used by other opcodes to identify a region of the stack containing a variable number of objects for them to work on. See markobject.doc for more detail. """), I(name='POP_MARK', code='1', arg=None, stack_before=[markobject, stackslice], stack_after=[], proto=1, doc="""Pop all the stack objects at and above the topmost markobject. When an opcode using a variable number of stack objects is done, POP_MARK is used to remove those objects, and to remove the markobject that delimited their starting position on the stack. """), # Memo manipulation. There are really only two operations (get and put), # each in all-text, "short binary", and "long binary" flavors. I(name='GET', code='g', arg=decimalnl_short, stack_before=[], stack_after=[anyobject], proto=0, doc="""Read an object from the memo and push it on the stack. The index of the memo object to push is given by the newline-terminated decimal string following. BINGET and LONG_BINGET are space-optimized versions. """), I(name='BINGET', code='h', arg=uint1, stack_before=[], stack_after=[anyobject], proto=1, doc="""Read an object from the memo and push it on the stack. The index of the memo object to push is given by the 1-byte unsigned integer following. """), I(name='LONG_BINGET', code='j', arg=uint4, stack_before=[], stack_after=[anyobject], proto=1, doc="""Read an object from the memo and push it on the stack. The index of the memo object to push is given by the 4-byte unsigned little-endian integer following. """), I(name='PUT', code='p', arg=decimalnl_short, stack_before=[], stack_after=[], proto=0, doc="""Store the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the newline- terminated decimal string following. BINPUT and LONG_BINPUT are space-optimized versions. """), I(name='BINPUT', code='q', arg=uint1, stack_before=[], stack_after=[], proto=1, doc="""Store the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the 1-byte unsigned integer following. """), I(name='LONG_BINPUT', code='r', arg=uint4, stack_before=[], stack_after=[], proto=1, doc="""Store the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the 4-byte unsigned little-endian integer following. """), I(name='MEMOIZE', code='\x94', arg=None, stack_before=[anyobject], stack_after=[anyobject], proto=4, doc="""Store the stack top into the memo. The stack is not popped. The index of the memo location to write is the number of elements currently present in the memo. """), # Access the extension registry (predefined objects). Akin to the GET # family. I(name='EXT1', code='\x82', arg=uint1, stack_before=[], stack_after=[anyobject], proto=2, doc="""Extension code. This code and the similar EXT2 and EXT4 allow using a registry of popular objects that are pickled by name, typically classes. It is envisioned that through a global negotiation and registration process, third parties can set up a mapping between ints and object names. In order to guarantee pickle interchangeability, the extension code registry ought to be global, although a range of codes may be reserved for private use. EXT1 has a 1-byte integer argument. This is used to index into the extension registry, and the object at that index is pushed on the stack. """), I(name='EXT2', code='\x83', arg=uint2, stack_before=[], stack_after=[anyobject], proto=2, doc="""Extension code. See EXT1. EXT2 has a two-byte integer argument. """), I(name='EXT4', code='\x84', arg=int4, stack_before=[], stack_after=[anyobject], proto=2, doc="""Extension code. See EXT1. EXT4 has a four-byte integer argument. """), # Push a class object, or module function, on the stack, via its module # and name. I(name='GLOBAL', code='c', arg=stringnl_noescape_pair, stack_before=[], stack_after=[anyobject], proto=0, doc="""Push a global object (module.attr) on the stack. Two newline-terminated strings follow the GLOBAL opcode. The first is taken as a module name, and the second as a class name. The class object module.class is pushed on the stack. More accurately, the object returned by self.find_class(module, class) is pushed on the stack, so unpickling subclasses can override this form of lookup. """), I(name='STACK_GLOBAL', code='\x93', arg=None, stack_before=[pyunicode, pyunicode], stack_after=[anyobject], proto=4, doc="""Push a global object (module.attr) on the stack. """), # Ways to build objects of classes pickle doesn't know about directly # (user-defined classes). I despair of documenting this accurately # and comprehensibly -- you really have to read the pickle code to # find all the special cases. I(name='REDUCE', code='R', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=0, doc="""Push an object built from a callable and an argument tuple. The opcode is named to remind of the __reduce__() method. Stack before: ... callable pytuple Stack after: ... callable(*pytuple) The callable and the argument tuple are the first two items returned by a __reduce__ method. Applying the callable to the argtuple is supposed to reproduce the original object, or at least get it started. If the __reduce__ method returns a 3-tuple, the last component is an argument to be passed to the object's __setstate__, and then the REDUCE opcode is followed by code to create setstate's argument, and then a BUILD opcode to apply __setstate__ to that argument. If not isinstance(callable, type), REDUCE complains unless the callable has been registered with the copyreg module's safe_constructors dict, or the callable has a magic '__safe_for_unpickling__' attribute with a true value. I'm not sure why it does this, but I've sure seen this complaint often enough when I didn't want to <wink>. """), I(name='BUILD', code='b', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=0, doc="""Finish building an object, via __setstate__ or dict update. Stack before: ... anyobject argument Stack after: ... anyobject where anyobject may have been mutated, as follows: If the object has a __setstate__ method, anyobject.__setstate__(argument) is called. Else the argument must be a dict, the object must have a __dict__, and the object is updated via anyobject.__dict__.update(argument) """), I(name='INST', code='i', arg=stringnl_noescape_pair, stack_before=[markobject, stackslice], stack_after=[anyobject], proto=0, doc="""Build a class instance. This is the protocol 0 version of protocol 1's OBJ opcode. INST is followed by two newline-terminated strings, giving a module and class name, just as for the GLOBAL opcode (and see GLOBAL for more details about that). self.find_class(module, name) is used to get a class object. In addition, all the objects on the stack following the topmost markobject are gathered into a tuple and popped (along with the topmost markobject), just as for the TUPLE opcode. Now it gets complicated. If all of these are true: + The argtuple is empty (markobject was at the top of the stack at the start). + The class object does not have a __getinitargs__ attribute. then we want to create an old-style class instance without invoking its __init__() method (pickle has waffled on this over the years; not calling __init__() is current wisdom). In this case, an instance of an old-style dummy class is created, and then we try to rebind its __class__ attribute to the desired class object. If this succeeds, the new instance object is pushed on the stack, and we're done. Else (the argtuple is not empty, it's not an old-style class object, or the class object does have a __getinitargs__ attribute), the code first insists that the class object have a __safe_for_unpickling__ attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE, it doesn't matter whether this attribute has a true or false value, it only matters whether it exists (XXX this is a bug). If __safe_for_unpickling__ doesn't exist, UnpicklingError is raised. Else (the class object does have a __safe_for_unpickling__ attr), the class object obtained from INST's arguments is applied to the argtuple obtained from the stack, and the resulting instance object is pushed on the stack. NOTE: checks for __safe_for_unpickling__ went away in Python 2.3. NOTE: the distinction between old-style and new-style classes does not make sense in Python 3. """), I(name='OBJ', code='o', arg=None, stack_before=[markobject, anyobject, stackslice], stack_after=[anyobject], proto=1, doc="""Build a class instance. This is the protocol 1 version of protocol 0's INST opcode, and is very much like it. The major difference is that the class object is taken off the stack, allowing it to be retrieved from the memo repeatedly if several instances of the same class are created. This can be much more efficient (in both time and space) than repeatedly embedding the module and class names in INST opcodes. Unlike INST, OBJ takes no arguments from the opcode stream. Instead the class object is taken off the stack, immediately above the topmost markobject: Stack before: ... markobject classobject stackslice Stack after: ... new_instance_object As for INST, the remainder of the stack above the markobject is gathered into an argument tuple, and then the logic seems identical, except that no __safe_for_unpickling__ check is done (XXX this is a bug). See INST for the gory details. NOTE: In Python 2.3, INST and OBJ are identical except for how they get the class object. That was always the intent; the implementations had diverged for accidental reasons. """), I(name='NEWOBJ', code='\x81', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=2, doc="""Build an object instance. The stack before should be thought of as containing a class object followed by an argument tuple (the tuple being the stack top). Call these cls and args. They are popped off the stack, and the value returned by cls.__new__(cls, *args) is pushed back onto the stack. """), I(name='NEWOBJ_EX', code='\x92', arg=None, stack_before=[anyobject, anyobject, anyobject], stack_after=[anyobject], proto=4, doc="""Build an object instance. The stack before should be thought of as containing a class object followed by an argument tuple and by a keyword argument dict (the dict being the stack top). Call these cls and args. They are popped off the stack, and the value returned by cls.__new__(cls, *args, *kwargs) is pushed back onto the stack. """), # Machine control. I(name='PROTO', code='\x80', arg=uint1, stack_before=[], stack_after=[], proto=2, doc="""Protocol version indicator. For protocol 2 and above, a pickle must start with this opcode. The argument is the protocol version, an int in range(2, 256). """), I(name='STOP', code='.', arg=None, stack_before=[anyobject], stack_after=[], proto=0, doc="""Stop the unpickling machine. Every pickle ends with this opcode. The object at the top of the stack is popped, and that's the result of unpickling. The stack should be empty then. """), # Framing support. I(name='FRAME', code='\x95', arg=uint8, stack_before=[], stack_after=[], proto=4, doc="""Indicate the beginning of a new frame. The unpickler may use this opcode to safely prefetch data from its underlying stream. """), # Ways to deal with persistent IDs. I(name='PERSID', code='P', arg=stringnl_noescape, stack_before=[], stack_after=[anyobject], proto=0, doc="""Push an object identified by a persistent ID. The pickle module doesn't define what a persistent ID means. PERSID's argument is a newline-terminated str-style (no embedded escapes, no bracketing quote characters) string, which *is* "the persistent ID". The unpickler passes this string to self.persistent_load(). Whatever object that returns is pushed on the stack. There is no implementation of persistent_load() in Python's unpickler: it must be supplied by an unpickler subclass. """), I(name='BINPERSID', code='Q', arg=None, stack_before=[anyobject], stack_after=[anyobject], proto=1, doc="""Push an object identified by a persistent ID. Like PERSID, except the persistent ID is popped off the stack (instead of being a string embedded in the opcode bytestream). The persistent ID is passed to self.persistent_load(), and whatever object that returns is pushed on the stack. See PERSID for more detail. """), ] del I # Verify uniqueness of .name and .code members. name2i = {} code2i = {} for i, d in enumerate(opcodes): if d.name in name2i: raise ValueError("repeated name %r at indices %d and %d" % (d.name, name2i[d.name], i)) if d.code in code2i: raise ValueError("repeated code %r at indices %d and %d" % (d.code, code2i[d.code], i)) name2i[d.name] = i code2i[d.code] = i del name2i, code2i, i, d ############################################################################## # Build a code2op dict, mapping opcode characters to OpcodeInfo records. # Also ensure we've got the same stuff as pickle.py, although the # introspection here is dicey. code2op = {} for d in opcodes: code2op[d.code] = d del d def assure_pickle_consistency(verbose=False): copy = code2op.copy() for name in pickle.__all__: if not re.match("[A-Z][A-Z0-9_]+$", name): if verbose: print("skipping %r: it doesn't look like an opcode name" % name) continue picklecode = getattr(pickle, name) if not isinstance(picklecode, bytes) or len(picklecode) != 1: if verbose: print(("skipping %r: value %r doesn't look like a pickle " "code" % (name, picklecode))) continue picklecode = picklecode.decode("latin-1") if picklecode in copy: if verbose: print("checking name %r w/ code %r for consistency" % ( name, picklecode)) d = copy[picklecode] if d.name != name: raise ValueError("for pickle code %r, pickle.py uses name %r " "but we're using name %r" % (picklecode, name, d.name)) # Forget this one. Any left over in copy at the end are a problem # of a different kind. del copy[picklecode] else: raise ValueError("pickle.py appears to have a pickle opcode with " "name %r and code %r, but we don't" % (name, picklecode)) if copy: msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"] for code, d in copy.items(): msg.append(" name %r with code %r" % (d.name, code)) raise ValueError("\n".join(msg)) assure_pickle_consistency() del assure_pickle_consistency ############################################################################## # A pickle opcode generator. def _genops(data, yield_end_pos=False): if isinstance(data, bytes_types): data = io.BytesIO(data) if hasattr(data, "tell"): getpos = data.tell else: getpos = lambda: None while True: pos = getpos() code = data.read(1) opcode = code2op.get(code.decode("latin-1")) if opcode is None: if code == b"": raise ValueError("pickle exhausted before seeing STOP") else: raise ValueError("at position %s, opcode %r unknown" % ( "<unknown>" if pos is None else pos, code)) if opcode.arg is None: arg = None<|fim▁hole|> arg = opcode.arg.reader(data) if yield_end_pos: yield opcode, arg, pos, getpos() else: yield opcode, arg, pos if code == b'.': assert opcode.name == 'STOP' break def genops(pickle): """Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a bytes object, it's wrapped in a BytesIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None. """ return _genops(pickle) ############################################################################## # A pickle optimizer. def optimize(p): 'Optimize a pickle string by removing unused PUT opcodes' put = 'PUT' get = 'GET' oldids = set() # set of all PUT ids newids = {} # set of ids used by a GET opcode opcodes = [] # (op, idx) or (pos, end_pos) proto = 0 protoheader = b'' for opcode, arg, pos, end_pos in _genops(p, yield_end_pos=True): if 'PUT' in opcode.name: oldids.add(arg) opcodes.append((put, arg)) elif opcode.name == 'MEMOIZE': idx = len(oldids) oldids.add(idx) opcodes.append((put, idx)) elif 'FRAME' in opcode.name: pass elif 'GET' in opcode.name: if opcode.proto > proto: proto = opcode.proto newids[arg] = None opcodes.append((get, arg)) elif opcode.name == 'PROTO': if arg > proto: proto = arg if pos == 0: protoheader = p[pos: end_pos] else: opcodes.append((pos, end_pos)) else: opcodes.append((pos, end_pos)) del oldids # Copy the opcodes except for PUTS without a corresponding GET out = io.BytesIO() # Write the PROTO header before any framing out.write(protoheader) pickler = pickle._Pickler(out, proto) if proto >= 4: pickler.framer.start_framing() idx = 0 for op, arg in opcodes: if op is put: if arg not in newids: continue data = pickler.put(idx) newids[arg] = idx idx += 1 elif op is get: data = pickler.get(newids[arg]) else: data = p[op:arg] pickler.framer.commit_frame() pickler.write(data) pickler.framer.end_framing() return out.getvalue() ############################################################################## # A symbolic pickle disassembler. def dis(pickle, out=None, memo=None, indentlevel=4, annotate=0): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg 'indentlevel' is the number of blanks by which to indent a new MARK level. It defaults to 4. Optional arg 'annotate' if nonzero instructs dis() to add short description of the opcode on each line of disassembled output. The value given to 'annotate' must be an integer and is used as a hint for the column where annotation should start. The default value is 0, meaning no annotations. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpickler memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None annocol = annotate # column hint for annotations for opcode, arg, pos in genops(pickle): if pos is not None: print("%5d:" % pos, end=' ', file=out) line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT", "MEMOIZE"): if opcode.name == "MEMOIZE": memo_idx = len(memo) markmsg = "(as %d)" % memo_idx else: assert arg is not None memo_idx = arg if memo_idx in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[memo_idx] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg if annotate: line += ' ' * (annocol - len(line)) # make a mild effort to align annotations annocol = len(line) if annocol > 50: annocol = annotate line += ' ' + opcode.doc.split('\n', 1)[0] print(line, file=out) if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print("highest protocol among opcodes =", maxproto, file=out) if stack: raise ValueError("stack not empty after STOP: %r" % stack) # For use in the doctest, simply as an example of a class to pickle. class _Example: def __init__(self, value): self.value = value _dis_test = r""" >>> import pickle >>> x = [1, 2, (3, 4), {b'abc': "def"}] >>> pkl0 = pickle.dumps(x, 0) >>> dis(pkl0) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: L LONG 1 9: a APPEND 10: L LONG 2 14: a APPEND 15: ( MARK 16: L LONG 3 20: L LONG 4 24: t TUPLE (MARK at 15) 25: p PUT 1 28: a APPEND 29: ( MARK 30: d DICT (MARK at 29) 31: p PUT 2 34: c GLOBAL '_codecs encode' 50: p PUT 3 53: ( MARK 54: V UNICODE 'abc' 59: p PUT 4 62: V UNICODE 'latin1' 70: p PUT 5 73: t TUPLE (MARK at 53) 74: p PUT 6 77: R REDUCE 78: p PUT 7 81: V UNICODE 'def' 86: p PUT 8 89: s SETITEM 90: a APPEND 91: . STOP highest protocol among opcodes = 0 Try again with a "binary" pickle. >>> pkl1 = pickle.dumps(x, 1) >>> dis(pkl1) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: K BININT1 1 6: K BININT1 2 8: ( MARK 9: K BININT1 3 11: K BININT1 4 13: t TUPLE (MARK at 8) 14: q BINPUT 1 16: } EMPTY_DICT 17: q BINPUT 2 19: c GLOBAL '_codecs encode' 35: q BINPUT 3 37: ( MARK 38: X BINUNICODE 'abc' 46: q BINPUT 4 48: X BINUNICODE 'latin1' 59: q BINPUT 5 61: t TUPLE (MARK at 37) 62: q BINPUT 6 64: R REDUCE 65: q BINPUT 7 67: X BINUNICODE 'def' 75: q BINPUT 8 77: s SETITEM 78: e APPENDS (MARK at 3) 79: . STOP highest protocol among opcodes = 1 Exercise the INST/OBJ/BUILD family. >>> import pickletools >>> dis(pickle.dumps(pickletools.dis, 0)) 0: c GLOBAL 'pickletools dis' 17: p PUT 0 20: . STOP highest protocol among opcodes = 0 >>> from pickletools import _Example >>> x = [_Example(42)] * 2 >>> dis(pickle.dumps(x, 0)) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: c GLOBAL 'copy_reg _reconstructor' 30: p PUT 1 33: ( MARK 34: c GLOBAL 'pickletools _Example' 56: p PUT 2 59: c GLOBAL '__builtin__ object' 79: p PUT 3 82: N NONE 83: t TUPLE (MARK at 33) 84: p PUT 4 87: R REDUCE 88: p PUT 5 91: ( MARK 92: d DICT (MARK at 91) 93: p PUT 6 96: V UNICODE 'value' 103: p PUT 7 106: L LONG 42 111: s SETITEM 112: b BUILD 113: a APPEND 114: g GET 5 117: a APPEND 118: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(x, 1)) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: c GLOBAL 'copy_reg _reconstructor' 29: q BINPUT 1 31: ( MARK 32: c GLOBAL 'pickletools _Example' 54: q BINPUT 2 56: c GLOBAL '__builtin__ object' 76: q BINPUT 3 78: N NONE 79: t TUPLE (MARK at 31) 80: q BINPUT 4 82: R REDUCE 83: q BINPUT 5 85: } EMPTY_DICT 86: q BINPUT 6 88: X BINUNICODE 'value' 98: q BINPUT 7 100: K BININT1 42 102: s SETITEM 103: b BUILD 104: h BINGET 5 106: e APPENDS (MARK at 3) 107: . STOP highest protocol among opcodes = 1 Try "the canonical" recursive-object test. >>> L = [] >>> T = L, >>> L.append(T) >>> L[0] is T True >>> T[0] is L True >>> L[0][0] is L True >>> T[0][0] is T True >>> dis(pickle.dumps(L, 0)) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: ( MARK 6: g GET 0 9: t TUPLE (MARK at 5) 10: p PUT 1 13: a APPEND 14: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(L, 1)) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: h BINGET 0 6: t TUPLE (MARK at 3) 7: q BINPUT 1 9: a APPEND 10: . STOP highest protocol among opcodes = 1 Note that, in the protocol 0 pickle of the recursive tuple, the disassembler has to emulate the stack in order to realize that the POP opcode at 16 gets rid of the MARK at 0. >>> dis(pickle.dumps(T, 0)) 0: ( MARK 1: ( MARK 2: l LIST (MARK at 1) 3: p PUT 0 6: ( MARK 7: g GET 0 10: t TUPLE (MARK at 6) 11: p PUT 1 14: a APPEND 15: 0 POP 16: 0 POP (MARK at 0) 17: g GET 1 20: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(T, 1)) 0: ( MARK 1: ] EMPTY_LIST 2: q BINPUT 0 4: ( MARK 5: h BINGET 0 7: t TUPLE (MARK at 4) 8: q BINPUT 1 10: a APPEND 11: 1 POP_MARK (MARK at 0) 12: h BINGET 1 14: . STOP highest protocol among opcodes = 1 Try protocol 2. >>> dis(pickle.dumps(L, 2)) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: h BINGET 0 7: \x85 TUPLE1 8: q BINPUT 1 10: a APPEND 11: . STOP highest protocol among opcodes = 2 >>> dis(pickle.dumps(T, 2)) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: h BINGET 0 7: \x85 TUPLE1 8: q BINPUT 1 10: a APPEND 11: 0 POP 12: h BINGET 1 14: . STOP highest protocol among opcodes = 2 Try protocol 3 with annotations: >>> dis(pickle.dumps(T, 3), annotate=1) 0: \x80 PROTO 3 Protocol version indicator. 2: ] EMPTY_LIST Push an empty list. 3: q BINPUT 0 Store the stack top into the memo. The stack is not popped. 5: h BINGET 0 Read an object from the memo and push it on the stack. 7: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. 8: q BINPUT 1 Store the stack top into the memo. The stack is not popped. 10: a APPEND Append an object to a list. 11: 0 POP Discard the top stack item, shrinking the stack by one item. 12: h BINGET 1 Read an object from the memo and push it on the stack. 14: . STOP Stop the unpickling machine. highest protocol among opcodes = 2 """ _memo_test = r""" >>> import pickle >>> import io >>> f = io.BytesIO() >>> p = pickle.Pickler(f, 2) >>> x = [1, 2, 3] >>> p.dump(x) >>> p.dump(x) >>> f.seek(0) 0 >>> memo = {} >>> dis(f, memo=memo) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: ( MARK 6: K BININT1 1 8: K BININT1 2 10: K BININT1 3 12: e APPENDS (MARK at 5) 13: . STOP highest protocol among opcodes = 2 >>> dis(f, memo=memo) 14: \x80 PROTO 2 16: h BINGET 0 18: . STOP highest protocol among opcodes = 2 """ __test__ = {'disassembler_test': _dis_test, 'disassembler_memo_test': _memo_test, } def _test(): import doctest return doctest.testmod() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description='disassemble one or more pickle files') parser.add_argument( 'pickle_file', type=argparse.FileType('br'), nargs='*', help='the pickle file') parser.add_argument( '-o', '--output', default=sys.stdout, type=argparse.FileType('w'), help='the file where the output should be written') parser.add_argument( '-m', '--memo', action='store_true', help='preserve memo between disassemblies') parser.add_argument( '-l', '--indentlevel', default=4, type=int, help='the number of blanks by which to indent a new MARK level') parser.add_argument( '-a', '--annotate', action='store_true', help='annotate each line with a short opcode description') parser.add_argument( '-p', '--preamble', default="==> {name} <==", help='if more than one pickle file is specified, print this before' ' each disassembly') parser.add_argument( '-t', '--test', action='store_true', help='run self-test suite') parser.add_argument( '-v', action='store_true', help='run verbosely; only affects self-test run') args = parser.parse_args() if args.test: _test() else: annotate = 30 if args.annotate else 0 if not args.pickle_file: parser.print_help() elif len(args.pickle_file) == 1: dis(args.pickle_file[0], args.output, None, args.indentlevel, annotate) else: memo = {} if args.memo else None for f in args.pickle_file: preamble = args.preamble.format(name=f.name) args.output.write(preamble + '\n') dis(f, args.output, memo, args.indentlevel, annotate)<|fim▁end|>
else:
<|file_name|>title.js<|end_file_name|><|fim▁begin|>game.TitleScreen = me.ScreenObject.extend({ init: function(){ this.font = null; },<|fim▁hole|> game.data.newHiScore = false; me.game.world.addChild(new BackgroundLayer('bg', 1)); me.input.bindKey(me.input.KEY.ENTER, "enter", true); me.input.bindKey(me.input.KEY.SPACE, "enter", true); me.input.bindMouse(me.input.mouse.LEFT, me.input.KEY.ENTER); this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) { if (action === "enter") { me.state.change(me.state.PLAY); } }); //logo var logoImg = me.loader.getImage('logo'); var logo = new me.SpriteObject ( me.game.viewport.width/2 - 170, -logoImg, logoImg ); me.game.world.addChild(logo, 10); var logoTween = new me.Tween(logo.pos).to({y: me.game.viewport.height/2 - 100}, 1000).easing(me.Tween.Easing.Exponential.InOut).start(); this.ground = new TheGround(); me.game.world.addChild(this.ground, 11); me.game.world.addChild(new (me.Renderable.extend ({ // constructor init: function() { // size does not matter, it's just to avoid having a zero size // renderable this.parent(new me.Vector2d(), 100, 100); //this.font = new me.Font('Arial Black', 20, 'black', 'left'); this.text = me.device.touch ? 'Tap to start' : 'PRESS SPACE OR CLICK LEFT MOUSE BUTTON TO START'; this.font = new me.Font('gamefont', 20, '#000'); }, update: function () { return true; }, draw: function (context) { var measure = this.font.measureText(context, this.text); this.font.draw(context, this.text, me.game.viewport.width/2 - measure.width/2, me.game.viewport.height/2 + 50); } })), 12); }, onDestroyEvent: function() { // unregister the event me.event.unsubscribe(this.handler); me.input.unbindKey(me.input.KEY.ENTER); me.input.unbindKey(me.input.KEY.SPACE); me.input.unbindMouse(me.input.mouse.LEFT); me.game.world.removeChild(this.ground); } });<|fim▁end|>
onResetEvent: function() { me.audio.stop("theme");
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>export * from './user.effects'; export * from './router.effects';<|fim▁end|>
<|file_name|>check_mq_channel.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import getopt import sys import pymqi, CMQC, CMQCFC STATE_OK = 0 STATE_WARNING = 1 STATE_CRITICAL = 2 STATE_UNKNOWN = 3 def usage(): print """Usage: rbh_check_mq_channel_status -H <HostName> -g <QMGRName> -p <PortNumber> -a <ChannelName for connection> -t <ChannelName for test>""" def show_help(): usage() print """ Checks MQ channel status -H, --host Host name -g, --qmgr Queue Manager Name -p, --port-number port number (default 1414) -a, --channel-name-conn channel name for connection -t, --channel-name channel name for test example: rbh_check_mq_channel_status.py -H host1 -g QM1 -a SYSTEM.ADMIN.SVRCONN -t nameofthechannel """ def exit_with_state(exit_code): global qmgr try: qmgr.disconnect() except: pass sys.exit(exit_code) def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hH:g:p:a:t:", ["help", "host","qmgr=","port=","channel-name=","channel-name-conn="]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) hostName=None qmgrName=None portNumber=1414 channelNameConn=None channelNameTest=None for o, a in opts: if o in ("-h", "--help"): show_help() sys.exit() elif o in ("-H", "--host"): hostName = a elif o in ("-g", "--qmgr"): qmgrName = a elif o in ("-p", "--port"): portNumber = int(a) elif o in ("-a", "--channel-name-conn"): channelNameConn = a elif o in ("-t", "--channel-name"): channelNameTest = a else: assert False, "unhandled option" if not (hostName and portNumber and channelNameTest and qmgrName and channelNameConn): usage() exit_with_state(STATE_UNKNOWN) # if len(channelNameConn) > MQ_CHANNEL_NAME_LENGTH: # print "UNKNOWN - Channel name are too long." conn_info="%s(%s)" % (hostName,portNumber) global qmgr try: qmgr = pymqi.connect(qmgrName,channelNameConn,conn_info) except pymqi.MQMIError, e: print "UNKNOWN - unable to connect to Qmanager, reason: %s" % (e) exit_with_state(STATE_UNKNOWN) channel_name = '' try: pcf = pymqi.PCFExecute(qmgr) channel_names = pcf.MQCMD_INQUIRE_CHANNEL({CMQCFC.MQCACH_CHANNEL_NAME: channelNameTest}) if channel_names[0]: channel_name = channel_names[0][CMQCFC.MQCACH_CHANNEL_NAME].rstrip() channel_type = channel_names[0][CMQCFC.MQIACH_CHANNEL_TYPE] else: print("CRITICAL - Channel %s does not exists." % (channelNameTest)) exit_with_state(STATE_UNKNOWN) except pymqi.MQMIError,e : print("UNKNOWN - Can not list MQ channels. reason: %s" % (e)) exit_with_state(STATE_UNKNOWN) status_available = True try: attrs = "MQCACH_CHANNEL_NAME MQIACH_BYTES_RCVD MQIACH_BYTES_SENT" pcf = pymqi.PCFExecute(qmgr) channels = pcf.MQCMD_INQUIRE_CHANNEL_STATUS({CMQCFC.MQCACH_CHANNEL_NAME: channelNameTest}) except pymqi.MQMIError, e: if e.comp == CMQC.MQCC_FAILED and e.reason == CMQCFC.MQRCCF_CHL_STATUS_NOT_FOUND: status_available = False pass else: print "UNKNOWN - Can not get status information, reason: %s" % (e) exit_with_state(STATE_UNKNOWN) infomsg = {CMQCFC.MQCHS_INACTIVE:"Channel is inactive", CMQCFC.MQCHS_BINDING:"Channel is negotiating with the partner.", CMQCFC.MQCHS_STARTING:"Channel is waiting to become active.", CMQCFC.MQCHS_RUNNING:"Channel is transferring or waiting for messages.", CMQCFC.MQCHS_PAUSED:"Channel is paused.", CMQCFC.MQCHS_STOPPING:"Channel is in process of stopping.", CMQCFC.MQCHS_RETRYING:"Channel is reattempting to establish connection.", CMQCFC.MQCHS_STOPPED:"Channel is stopped.", CMQCFC.MQCHS_REQUESTING:"Requester channel is requesting connection.", CMQCFC.MQCHS_INITIALIZING:"Channel is initializing."} if status_available: status = channels[0][CMQCFC.MQIACH_CHANNEL_STATUS] msg = "Channel: %s state is %s (%s)" % (channel_name,status,infomsg[status]) if (status == CMQCFC.MQCHS_RUNNING or (status == CMQCFC.MQCHS_INACTIVE and not channel_type in (CMQC.MQCHT_REQUESTER,CMQC.MQCHT_CLUSSDR))): print("OK - %s" % (msg)) exit_with_state(STATE_OK) if status in (CMQCFC.MQCHS_PAUSED,CMQCFC.MQCHS_STOPPED): print("CRITICAL - %s" % (msg)) exit_with_state(STATE_CRITICAL) else: print("WARNING - %s" % (msg)) exit_with_state(STATE_WARNING) else: if channel_type in (CMQC.MQCHT_REQUESTER,CMQC.MQCHT_CLUSSDR): print("CRITICAL - Channel %s is defined, but status is not available. As this channel is defined as CLUSDR or REQUESTER type channel, therefore it should be running." % (channelNameTest)) exit_with_state(STATE_CRITICAL) else: print("OK - Channel %s is defined, but status is not available. This may indicate that the channel has not been used." % (channelNameTest)) exit_with_state(STATE_OK) <|fim▁hole|><|fim▁end|>
if __name__ == "__main__": main()
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::WINR { #[doc = r" Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct WINR { bits: u16, } impl WINR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } } #[doc = r" Proxy"] pub struct _WINW<'a> { w: &'a mut W, } impl<'a> _WINW<'a> { #[doc = r" Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { const MASK: u16 = 4095; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:11 - Watchdog counter window value"] #[inline(always)] pub fn win(&self) -> WINR {<|fim▁hole|> ((self.bits >> OFFSET) & MASK as u32) as u16 }; WINR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline(always)] pub fn reset_value() -> W { W { bits: 4095 } } #[doc = r" Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:11 - Watchdog counter window value"] #[inline(always)] pub fn win(&mut self) -> _WINW { _WINW { w: self } } }<|fim▁end|>
let bits = { const MASK: u16 = 4095; const OFFSET: u8 = 0;
<|file_name|>mem_server.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2013 OpenStack, 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. """ In-Memory Object Server for Swift """ import os from swift import gettext_ as _ from eventlet import Timeout from swift.common.bufferedhttp import http_connect from swift.common.exceptions import ConnectionTimeout from swift.common.http import is_success<|fim▁hole|> class ObjectController(server.ObjectController): """ Implements the WSGI application for the Swift In-Memory Object Server. """ def setup(self, conf): """ Nothing specific to do for the in-memory version. :param conf: WSGI configuration parameter """ self._filesystem = InMemoryFileSystem() def get_diskfile(self, device, partition, account, container, obj, **kwargs): """ Utility method for instantiating a DiskFile object supporting a given REST API. An implementation of the object server that wants to use a different DiskFile class would simply over-ride this method to provide that behavior. """ return self._filesystem.get_diskfile(account, container, obj, **kwargs) def async_update(self, op, account, container, obj, host, partition, contdevice, headers_out, objdevice, policy_idx): """ Sends or saves an async update. :param op: operation performed (ex: 'PUT', or 'DELETE') :param account: account name for the object :param container: container name for the object :param obj: object name :param host: host that the container is on :param partition: partition that the container is on :param contdevice: device name that the container is on :param headers_out: dictionary of headers to send in the container request :param objdevice: device name that the object is in :param policy_idx: the associated storage policy index """ headers_out['user-agent'] = 'obj-server %s' % os.getpid() full_path = '/%s/%s/%s' % (account, container, obj) if all([host, partition, contdevice]): try: with ConnectionTimeout(self.conn_timeout): ip, port = host.rsplit(':', 1) conn = http_connect(ip, port, contdevice, partition, op, full_path, headers_out) with Timeout(self.node_timeout): response = conn.getresponse() response.read() if is_success(response.status): return else: self.logger.error(_( 'ERROR Container update failed: %(status)d ' 'response from %(ip)s:%(port)s/%(dev)s'), {'status': response.status, 'ip': ip, 'port': port, 'dev': contdevice}) except (Exception, Timeout): self.logger.exception(_( 'ERROR container update failed with ' '%(ip)s:%(port)s/%(dev)s'), {'ip': ip, 'port': port, 'dev': contdevice}) # FIXME: For now don't handle async updates def REPLICATE(self, request): """ Handle REPLICATE requests for the Swift Object Server. This is used by the object replicator to get hashes for directories. """ pass def app_factory(global_conf, **local_conf): """paste.deploy app factory for creating WSGI object server apps""" conf = global_conf.copy() conf.update(local_conf) return ObjectController(conf)<|fim▁end|>
from swift.obj.mem_diskfile import InMemoryFileSystem from swift.obj import server
<|file_name|>daku.cpp<|end_file_name|><|fim▁begin|>#include "daku.h" namespace daku { void bigBang() { av_register_all(); } <|fim▁hole|><|fim▁end|>
}
<|file_name|>CreateOperation.java<|end_file_name|><|fim▁begin|>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.zookeeper.operations; import java.util.List; import static java.lang.String.format; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; /** * <code>CreateOperation</code> is a basic Zookeeper operation used to create * and set the data contained in a given node */ public class CreateOperation extends ZooKeeperOperation<String> { private static final List<ACL> DEFAULT_PERMISSIONS = Ids.OPEN_ACL_UNSAFE; private static final CreateMode DEFAULT_MODE = CreateMode.EPHEMERAL; private byte[] data; private List<ACL> permissions = DEFAULT_PERMISSIONS; private CreateMode createMode = DEFAULT_MODE; public CreateOperation(ZooKeeper connection, String node) { super(connection, node); }<|fim▁hole|> String created = connection.create(node, data, permissions, createMode); if (LOG.isDebugEnabled()) { LOG.debug(format("Created node '%s' using mode '%s'", created, createMode)); } // for consistency with other operations return an empty stats set. return new OperationResult<String>(created, new Stat()); } catch (Exception e) { return new OperationResult<String>(e); } } public void setData(byte[] data) { this.data = data; } public void setPermissions(List<ACL> permissions) { this.permissions = permissions; } public void setCreateMode(CreateMode createMode) { this.createMode = createMode; } }<|fim▁end|>
@Override public OperationResult<String> getResult() { try {
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 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. #![macro_escape] pub use self::PathParsingMode::*; use self::ItemOrViewItem::*; use abi; use ast::{AssociatedType, BareFnTy, ClosureTy}; use ast::{RegionTyParamBound, TraitTyParamBound}; use ast::{ProvidedMethod, Public, FnStyle}; use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue}; use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, Block}; use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause}; use ast::{Crate, CrateConfig, Decl, DeclItem}; use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf}; use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain}; use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox}; use ast::{ExprBreak, ExprCall, ExprCast}; use ast::{ExprField, ExprTupField, ExprFnBlock, ExprIf, ExprIfLet, ExprIndex, ExprSlice}; use ast::{ExprLit, ExprLoop, ExprMac}; use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc}; use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary, ExprUnboxedFn}; use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl}; use ast::{Once, Many}; use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind}; use ast::{FnOnceUnboxedClosureKind}; use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy}; use ast::{Ident, NormalFn, Inherited, ImplItem, Item, Item_, ItemStatic}; use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst}; use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy}; use ast::{LifetimeDef, Lit, Lit_}; use ast::{LitBool, LitChar, LitByte, LitBinary}; use ast::{LitStr, LitInt, Local, LocalLet}; use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchNormal}; use ast::{Method, MutTy, BiMul, Mutability}; use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, UnNot}; use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct}; use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle}; use ast::{PolyTraitRef}; use ast::{QPath, RequiredMethod}; use ast::{Return, BiShl, BiShr, Stmt, StmtDecl}; use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField}; use ast::{StructVariantKind, BiSub}; use ast::StrStyle; use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue}; use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef}; use ast::{TtDelimited, TtSequence, TtToken}; use ast::{TupleVariantKind, Ty, Ty_}; use ast::{TypeField, TyFixedLengthVec, TyClosure, TyProc, TyBareFn}; use ast::{TyTypeof, TyInfer, TypeMethod}; use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath}; use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq}; use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind}; use ast::{UnnamedField, UnsafeBlock}; use ast::{UnsafeFn, ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse}; use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple}; use ast::{Visibility, WhereClause, WherePredicate}; use ast; use ast_util::{as_prec, ident_to_path, operator_prec}; use ast_util; use codemap::{Span, BytePos, Spanned, spanned, mk_sp}; use codemap; use diagnostic; use ext::tt::macro_parser; use parse; use parse::attr::ParserAttr; use parse::classify; use parse::common::{SeqSep, seq_sep_none}; use parse::common::{seq_sep_trailing_allowed}; use parse::lexer::Reader; use parse::lexer::TokenAndSpan; use parse::obsolete::*; use parse::token::{MatchNt, SubstNt, InternedString}; use parse::token::{keywords, special_idents}; use parse::token; use parse::{new_sub_parser_from_file, ParseSess}; use print::pprust; use ptr::P; use owned_slice::OwnedSlice; use std::collections::HashSet; use std::io::fs::PathExtensions; use std::mem::replace; use std::mem; use std::num::Float; use std::rc::Rc; use std::iter; bitflags! { flags Restrictions: u8 { const UNRESTRICTED = 0b0000, const RESTRICTION_STMT_EXPR = 0b0001, const RESTRICTION_NO_BAR_OP = 0b0010, const RESTRICTION_NO_STRUCT_LITERAL = 0b0100 } } type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >); /// How to parse a path. There are four different kinds of paths, all of which /// are parsed somewhat differently. #[deriving(PartialEq)] pub enum PathParsingMode { /// A path with no type parameters; e.g. `foo::bar::Baz` NoTypesAllowed, /// A path with a lifetime and type parameters, with no double colons /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>` LifetimeAndTypesWithoutColons, /// A path with a lifetime and type parameters with double colons before /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>` LifetimeAndTypesWithColons, /// A path with a lifetime and type parameters with bounds before the last /// set of type parameters only; e.g. `foo::bar<'a>::Baz+X+Y<T>` This /// form does not use extra double colons. LifetimeAndTypesAndBounds, } /// A path paired with optional type bounds. pub struct PathAndBounds { pub path: ast::Path, pub bounds: Option<ast::TyParamBounds>, } enum ItemOrViewItem { /// Indicates a failure to parse any kind of item. The attributes are /// returned. IoviNone(Vec<Attribute>), IoviItem(P<Item>), IoviForeignItem(P<ForeignItem>), IoviViewItem(ViewItem) } /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression /// dropped into the token stream, which happens while parsing the result of /// macro expansion). Placement of these is not as complex as I feared it would /// be. The important thing is to make sure that lookahead doesn't balk at /// `token::Interpolated` tokens. macro_rules! maybe_whole_expr ( ($p:expr) => ( { let found = match $p.token { token::Interpolated(token::NtExpr(ref e)) => { Some((*e).clone()) } token::Interpolated(token::NtPath(_)) => { // FIXME: The following avoids an issue with lexical borrowck scopes, // but the clone is unfortunate. let pt = match $p.token { token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(), _ => unreachable!() }; let span = $p.span; Some($p.mk_expr(span.lo, span.hi, ExprPath(pt))) } token::Interpolated(token::NtBlock(_)) => { // FIXME: The following avoids an issue with lexical borrowck scopes, // but the clone is unfortunate. let b = match $p.token { token::Interpolated(token::NtBlock(ref b)) => (*b).clone(), _ => unreachable!() }; let span = $p.span; Some($p.mk_expr(span.lo, span.hi, ExprBlock(b))) } _ => None }; match found { Some(e) => { $p.bump(); return e; } None => () } } ) ) /// As maybe_whole_expr, but for things other than expressions macro_rules! maybe_whole ( ($p:expr, $constructor:ident) => ( { let found = match ($p).token { token::Interpolated(token::$constructor(_)) => { Some(($p).bump_and_get()) } _ => None }; match found { Some(token::Interpolated(token::$constructor(x))) => { return x.clone() } _ => {} } } ); (no_clone $p:expr, $constructor:ident) => ( { let found = match ($p).token { token::Interpolated(token::$constructor(_)) => { Some(($p).bump_and_get()) } _ => None }; match found { Some(token::Interpolated(token::$constructor(x))) => { return x } _ => {} } } ); (deref $p:expr, $constructor:ident) => ( { let found = match ($p).token { token::Interpolated(token::$constructor(_)) => { Some(($p).bump_and_get()) } _ => None }; match found { Some(token::Interpolated(token::$constructor(x))) => { return (*x).clone() } _ => {} } } ); (Some $p:expr, $constructor:ident) => ( { let found = match ($p).token { token::Interpolated(token::$constructor(_)) => { Some(($p).bump_and_get()) } _ => None }; match found { Some(token::Interpolated(token::$constructor(x))) => { return Some(x.clone()), } _ => {} } } ); (iovi $p:expr, $constructor:ident) => ( { let found = match ($p).token { token::Interpolated(token::$constructor(_)) => { Some(($p).bump_and_get()) } _ => None }; match found { Some(token::Interpolated(token::$constructor(x))) => { return IoviItem(x.clone()) } _ => {} } } ); (pair_empty $p:expr, $constructor:ident) => ( { let found = match ($p).token { token::Interpolated(token::$constructor(_)) => { Some(($p).bump_and_get()) } _ => None }; match found { Some(token::Interpolated(token::$constructor(x))) => { return (Vec::new(), x) } _ => {} } } ) ) fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>) -> Vec<Attribute> { match rhs { Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())), None => {} } lhs } struct ParsedItemsAndViewItems { attrs_remaining: Vec<Attribute>, view_items: Vec<ViewItem>, items: Vec<P<Item>> , foreign_items: Vec<P<ForeignItem>> } /* ident is handled by common.rs */ pub struct Parser<'a> { pub sess: &'a ParseSess, /// the current token: pub token: token::Token, /// the span of the current token: pub span: Span, /// the span of the prior token: pub last_span: Span, pub cfg: CrateConfig, /// the previous token or None (only stashed sometimes). pub last_token: Option<Box<token::Token>>, pub buffer: [TokenAndSpan, ..4], pub buffer_start: int, pub buffer_end: int, pub tokens_consumed: uint, pub restrictions: Restrictions, pub quote_depth: uint, // not (yet) related to the quasiquoter pub reader: Box<Reader+'a>, pub interner: Rc<token::IdentInterner>, /// The set of seen errors about obsolete syntax. Used to suppress /// extra detail when the same error is seen twice pub obsolete_set: HashSet<ObsoleteSyntax>, /// Used to determine the path to externally loaded source files pub mod_path_stack: Vec<InternedString>, /// Stack of spans of open delimiters. Used for error message. pub open_braces: Vec<Span>, /// Flag if this parser "owns" the directory that it is currently parsing /// in. This will affect how nested files are looked up. pub owns_directory: bool, /// Name of the root module this parser originated from. If `None`, then the /// name is not known. This does not change while the parser is descending /// into modules, and sub-parsers have new values for this name. pub root_module_name: Option<String>, } fn is_plain_ident_or_underscore(t: &token::Token) -> bool { t.is_plain_ident() || *t == token::Underscore } impl<'a> Parser<'a> { pub fn new(sess: &'a ParseSess, cfg: ast::CrateConfig, mut rdr: Box<Reader+'a>) -> Parser<'a> { let tok0 = rdr.real_token(); let span = tok0.sp; let placeholder = TokenAndSpan { tok: token::Underscore, sp: span, }; Parser { reader: rdr, interner: token::get_ident_interner(), sess: sess, cfg: cfg, token: tok0.tok, span: span, last_span: span, last_token: None, buffer: [ placeholder.clone(), placeholder.clone(), placeholder.clone(), placeholder.clone(), ], buffer_start: 0, buffer_end: 0, tokens_consumed: 0, restrictions: UNRESTRICTED, quote_depth: 0, obsolete_set: HashSet::new(), mod_path_stack: Vec::new(), open_braces: Vec::new(), owns_directory: true, root_module_name: None, } } /// Convert a token to a string using self's reader pub fn token_to_string(token: &token::Token) -> String { pprust::token_to_string(token) } /// Convert the current token to a string using self's reader pub fn this_token_to_string(&mut self) -> String { Parser::token_to_string(&self.token) } pub fn unexpected_last(&mut self, t: &token::Token) -> ! { let token_str = Parser::token_to_string(t); let last_span = self.last_span; self.span_fatal(last_span, format!("unexpected token: `{}`", token_str).as_slice()); } pub fn unexpected(&mut self) -> ! { let this_token = self.this_token_to_string(); self.fatal(format!("unexpected token: `{}`", this_token).as_slice()); } /// Expect and consume the token t. Signal an error if /// the next token is not t. pub fn expect(&mut self, t: &token::Token) { if self.token == *t { self.bump(); } else { let token_str = Parser::token_to_string(t); let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", token_str, this_token_str).as_slice()) } } /// Expect next token to be edible or inedible token. If edible, /// then consume it; if inedible, then return without consuming /// anything. Signal a fatal error if next token is unexpected. pub fn expect_one_of(&mut self, edible: &[token::Token], inedible: &[token::Token]) { fn tokens_to_string(tokens: &[token::Token]) -> String { let mut i = tokens.iter(); // This might be a sign we need a connect method on Iterator. let b = i.next() .map_or("".to_string(), |t| Parser::token_to_string(t)); i.fold(b, |b,a| { let mut b = b; b.push_str("`, `"); b.push_str(Parser::token_to_string(a).as_slice()); b }) } if edible.contains(&self.token) { self.bump(); } else if inedible.contains(&self.token) { // leave it in the input } else { let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>(); expected.push_all(inedible); let expect = tokens_to_string(expected.as_slice()); let actual = self.this_token_to_string(); self.fatal( (if expected.len() != 1 { (format!("expected one of `{}`, found `{}`", expect, actual)) } else { (format!("expected `{}`, found `{}`", expect, actual)) }).as_slice() ) } } /// Check for erroneous `ident { }`; if matches, signal error and /// recover (without consuming any expected input token). Returns /// true if and only if input was consumed for recovery. pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool { if self.token == token::OpenDelim(token::Brace) && expected.iter().all(|t| *t != token::OpenDelim(token::Brace)) && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) { // matched; signal non-fatal error and recover. let span = self.span; self.span_err(span, "unit-like struct construction is written with no trailing `{ }`"); self.eat(&token::OpenDelim(token::Brace)); self.eat(&token::CloseDelim(token::Brace)); true } else { false } } /// Commit to parsing a complete expression `e` expected to be /// followed by some token from the set edible + inedible. Recover /// from anticipated input errors, discarding erroneous characters. pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) { debug!("commit_expr {}", e); match e.node { ExprPath(..) => { // might be unit-struct construction; check for recoverableinput error. let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>(); expected.push_all(inedible); self.check_for_erroneous_unit_struct_expecting( expected.as_slice()); } _ => {} } self.expect_one_of(edible, inedible) } pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) { self.commit_expr(e, &[edible], &[]) } /// Commit to parsing a complete statement `s`, which expects to be /// followed by some token from the set edible + inedible. Check /// for recoverable input errors, discarding erroneous characters. pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) { if self.last_token .as_ref() .map_or(false, |t| t.is_ident() || t.is_path()) { let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>(); expected.push_all(inedible.as_slice()); self.check_for_erroneous_unit_struct_expecting( expected.as_slice()); } self.expect_one_of(edible, inedible) } pub fn commit_stmt_expecting(&mut self, edible: token::Token) { self.commit_stmt(&[edible], &[]) } pub fn parse_ident(&mut self) -> ast::Ident { self.check_strict_keywords(); self.check_reserved_keywords(); match self.token { token::Ident(i, _) => { self.bump(); i } token::Interpolated(token::NtIdent(..)) => { self.bug("ident interpolation not converted to real token"); } _ => { let token_str = self.this_token_to_string(); self.fatal((format!("expected ident, found `{}`", token_str)).as_slice()) } } } pub fn parse_path_list_item(&mut self) -> ast::PathListItem { let lo = self.span.lo; let node = if self.eat_keyword(keywords::Mod) { ast::PathListMod { id: ast::DUMMY_NODE_ID } } else { let ident = self.parse_ident(); ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID } }; let hi = self.last_span.hi; spanned(lo, hi, node) } /// Consume token 'tok' if it exists. Returns true if the given /// token was present, false otherwise. pub fn eat(&mut self, tok: &token::Token) -> bool { let is_present = self.token == *tok; if is_present { self.bump() } is_present } /// If the next token is the given keyword, eat it and return /// true. Otherwise, return false. pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool { if self.token.is_keyword(kw) { self.bump(); true } else { false } } /// If the given word is not a keyword, signal an error. /// If the next token is not the given word, signal an error. /// Otherwise, eat it. pub fn expect_keyword(&mut self, kw: keywords::Keyword) { if !self.eat_keyword(kw) { let id_interned_str = token::get_name(kw.to_name()); let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", id_interned_str, token_str).as_slice()) } } /// Signal an error if the given string is a strict keyword pub fn check_strict_keywords(&mut self) { if self.token.is_strict_keyword() { let token_str = self.this_token_to_string(); let span = self.span; self.span_err(span, format!("expected identifier, found keyword `{}`", token_str).as_slice()); } } /// Signal an error if the current token is a reserved keyword pub fn check_reserved_keywords(&mut self) { if self.token.is_reserved_keyword() { let token_str = self.this_token_to_string(); self.fatal(format!("`{}` is a reserved keyword", token_str).as_slice()) } } /// Expect and consume an `&`. If `&&` is seen, replace it with a single /// `&` and continue. If an `&` is not seen, signal an error. fn expect_and(&mut self) { match self.token { token::BinOp(token::And) => self.bump(), token::AndAnd => { let span = self.span; let lo = span.lo + BytePos(1); self.replace_token(token::BinOp(token::And), lo, span.hi) } _ => { let token_str = self.this_token_to_string(); let found_token = Parser::token_to_string(&token::BinOp(token::And)); self.fatal(format!("expected `{}`, found `{}`", found_token, token_str).as_slice()) } } } /// Expect and consume a `|`. If `||` is seen, replace it with a single /// `|` and continue. If a `|` is not seen, signal an error. fn expect_or(&mut self) { match self.token { token::BinOp(token::Or) => self.bump(), token::OrOr => { let span = self.span; let lo = span.lo + BytePos(1); self.replace_token(token::BinOp(token::Or), lo, span.hi) } _ => { let found_token = self.this_token_to_string(); let token_str = Parser::token_to_string(&token::BinOp(token::Or)); self.fatal(format!("expected `{}`, found `{}`", token_str, found_token).as_slice()) } } } pub fn expect_no_suffix(&mut self, sp: Span, kind: &str, suffix: Option<ast::Name>) { match suffix { None => {/* everything ok */} Some(suf) => { let text = suf.as_str(); if text.is_empty() { self.span_bug(sp, "found empty literal suffix in Some") } self.span_err(sp, &*format!("{} with a suffix is illegal", kind)); } } } /// Attempt to consume a `<`. If `<<` is seen, replace it with a single /// `<` and continue. If a `<` is not seen, return false. /// /// This is meant to be used when parsing generics on a path to get the /// starting token. The `force` parameter is used to forcefully break up a /// `<<` token. If `force` is false, then `<<` is only broken when a lifetime /// shows up next. For example, consider the expression: /// /// foo as bar << test /// /// The parser needs to know if `bar <<` is the start of a generic path or if /// it's a left-shift token. If `test` were a lifetime, then it's impossible /// for the token to be a left-shift, but if it's not a lifetime, then it's /// considered a left-shift. /// /// The reason for this is that the only current ambiguity with `<<` is when /// parsing closure types: /// /// foo::<<'a> ||>(); /// impl Foo<<'a> ||>() { ... } fn eat_lt(&mut self, force: bool) -> bool { match self.token { token::Lt => { self.bump(); true } token::BinOp(token::Shl) => { let next_lifetime = self.look_ahead(1, |t| match *t { token::Lifetime(..) => true, _ => false, }); if force || next_lifetime { let span = self.span; let lo = span.lo + BytePos(1); self.replace_token(token::Lt, lo, span.hi); true } else { false } } _ => false, } } fn expect_lt(&mut self) { if !self.eat_lt(true) { let found_token = self.this_token_to_string(); let token_str = Parser::token_to_string(&token::Lt); self.fatal(format!("expected `{}`, found `{}`", token_str, found_token).as_slice()) } } /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`. fn parse_seq_to_before_or<T>( &mut self, sep: &token::Token, f: |&mut Parser| -> T) -> Vec<T> { let mut first = true; let mut vector = Vec::new(); while self.token != token::BinOp(token::Or) && self.token != token::OrOr { if first { first = false } else { self.expect(sep) } vector.push(f(self)) } vector } /// Expect and consume a GT. if a >> is seen, replace it /// with a single > and continue. If a GT is not seen, /// signal an error. pub fn expect_gt(&mut self) { match self.token { token::Gt => self.bump(), token::BinOp(token::Shr) => { let span = self.span; let lo = span.lo + BytePos(1); self.replace_token(token::Gt, lo, span.hi) } token::BinOpEq(token::Shr) => { let span = self.span; let lo = span.lo + BytePos(1); self.replace_token(token::Ge, lo, span.hi) } token::Ge => { let span = self.span; let lo = span.lo + BytePos(1); self.replace_token(token::Eq, lo, span.hi) } _ => { let gt_str = Parser::token_to_string(&token::Gt); let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", gt_str, this_token_str).as_slice()) } } } /// Parse a sequence bracketed by '<' and '>', stopping /// before the '>'. pub fn parse_seq_to_before_gt<T>( &mut self, sep: Option<token::Token>, f: |&mut Parser| -> T) -> OwnedSlice<T> { let mut v = Vec::new(); // This loop works by alternating back and forth between parsing types // and commas. For example, given a string `A, B,>`, the parser would // first parse `A`, then a comma, then `B`, then a comma. After that it // would encounter a `>` and stop. This lets the parser handle trailing // commas in generic parameters, because it can stop either after // parsing a type or after parsing a comma. for i in iter::count(0u, 1) { if self.token == token::Gt || self.token == token::BinOp(token::Shr) || self.token == token::Ge || self.token == token::BinOpEq(token::Shr) { break; } if i % 2 == 0 { v.push(f(self)); } else { sep.as_ref().map(|t| self.expect(t)); } } return OwnedSlice::from_vec(v); } pub fn parse_seq_to_gt<T>( &mut self, sep: Option<token::Token>, f: |&mut Parser| -> T) -> OwnedSlice<T> { let v = self.parse_seq_to_before_gt(sep, f); self.expect_gt(); return v; } /// Parse a sequence, including the closing delimiter. The function /// f must consume tokens until reaching the next separator or /// closing bracket. pub fn parse_seq_to_end<T>( &mut self, ket: &token::Token, sep: SeqSep, f: |&mut Parser| -> T) -> Vec<T> { let val = self.parse_seq_to_before_end(ket, sep, f); self.bump(); val } /// Parse a sequence, not including the closing delimiter. The function /// f must consume tokens until reaching the next separator or /// closing bracket. pub fn parse_seq_to_before_end<T>( &mut self, ket: &token::Token, sep: SeqSep, f: |&mut Parser| -> T) -> Vec<T> { let mut first: bool = true; let mut v = vec!(); while self.token != *ket { match sep.sep { Some(ref t) => { if first { first = false; } else { self.expect(t); } } _ => () } if sep.trailing_sep_allowed && self.token == *ket { break; } v.push(f(self)); } return v; } /// Parse a sequence, including the closing delimiter. The function /// f must consume tokens until reaching the next separator or /// closing bracket. pub fn parse_unspanned_seq<T>( &mut self, bra: &token::Token, ket: &token::Token, sep: SeqSep, f: |&mut Parser| -> T) -> Vec<T> { self.expect(bra); let result = self.parse_seq_to_before_end(ket, sep, f); self.bump(); result } /// Parse a sequence parameter of enum variant. For consistency purposes, /// these should not be empty. pub fn parse_enum_variant_seq<T>( &mut self, bra: &token::Token, ket: &token::Token, sep: SeqSep, f: |&mut Parser| -> T) -> Vec<T> { let result = self.parse_unspanned_seq(bra, ket, sep, f); if result.is_empty() { let last_span = self.last_span; self.span_err(last_span, "nullary enum variants are written with no trailing `( )`"); } result } // NB: Do not use this function unless you actually plan to place the // spanned list in the AST. pub fn parse_seq<T>( &mut self, bra: &token::Token, ket: &token::Token, sep: SeqSep, f: |&mut Parser| -> T) -> Spanned<Vec<T> > { let lo = self.span.lo; self.expect(bra); let result = self.parse_seq_to_before_end(ket, sep, f); let hi = self.span.hi; self.bump(); spanned(lo, hi, result) } /// Advance the parser by one token pub fn bump(&mut self) { self.last_span = self.span; // Stash token for error recovery (sometimes; clone is not necessarily cheap). self.last_token = if self.token.is_ident() || self.token.is_path() { Some(box self.token.clone()) } else { None }; let next = if self.buffer_start == self.buffer_end { self.reader.real_token() } else { // Avoid token copies with `replace`. let buffer_start = self.buffer_start as uint; let next_index = (buffer_start + 1) & 3 as uint; self.buffer_start = next_index as int; let placeholder = TokenAndSpan { tok: token::Underscore, sp: self.span, }; replace(&mut self.buffer[buffer_start], placeholder) }; self.span = next.sp; self.token = next.tok; self.tokens_consumed += 1u; } /// Advance the parser by one token and return the bumped token. pub fn bump_and_get(&mut self) -> token::Token { let old_token = replace(&mut self.token, token::Underscore); self.bump(); old_token } /// EFFECT: replace the current token and span with the given one pub fn replace_token(&mut self, next: token::Token, lo: BytePos, hi: BytePos) { self.last_span = mk_sp(self.span.lo, lo); self.token = next; self.span = mk_sp(lo, hi); } pub fn buffer_length(&mut self) -> int { if self.buffer_start <= self.buffer_end { return self.buffer_end - self.buffer_start; } return (4 - self.buffer_start) + self.buffer_end; } pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R) -> R { let dist = distance as int; while self.buffer_length() < dist { self.buffer[self.buffer_end as uint] = self.reader.real_token(); self.buffer_end = (self.buffer_end + 1) & 3; } f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok) } pub fn fatal(&mut self, m: &str) -> ! { self.sess.span_diagnostic.span_fatal(self.span, m) } pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! { self.sess.span_diagnostic.span_fatal(sp, m) } pub fn span_fatal_help(&mut self, sp: Span, m: &str, help: &str) -> ! { self.span_err(sp, m); self.span_help(sp, help); panic!(diagnostic::FatalError); } pub fn span_note(&mut self, sp: Span, m: &str) { self.sess.span_diagnostic.span_note(sp, m) } pub fn span_help(&mut self, sp: Span, m: &str) { self.sess.span_diagnostic.span_help(sp, m) } pub fn bug(&mut self, m: &str) -> ! { self.sess.span_diagnostic.span_bug(self.span, m) } pub fn warn(&mut self, m: &str) { self.sess.span_diagnostic.span_warn(self.span, m) } pub fn span_warn(&mut self, sp: Span, m: &str) { self.sess.span_diagnostic.span_warn(sp, m) } pub fn span_err(&mut self, sp: Span, m: &str) { self.sess.span_diagnostic.span_err(sp, m) } pub fn span_bug(&mut self, sp: Span, m: &str) -> ! { self.sess.span_diagnostic.span_bug(sp, m) } pub fn abort_if_errors(&mut self) { self.sess.span_diagnostic.handler().abort_if_errors(); } pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString { token::get_ident(id) } /// Is the current token one of the keywords that signals a bare function /// type? pub fn token_is_bare_fn_keyword(&mut self) -> bool { self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) || self.token.is_keyword(keywords::Extern) } /// Is the current token one of the keywords that signals a closure type? pub fn token_is_closure_keyword(&mut self) -> bool { self.token.is_keyword(keywords::Unsafe) } pub fn get_lifetime(&mut self) -> ast::Ident { match self.token { token::Lifetime(ref ident) => *ident, _ => self.bug("not a lifetime"), } } pub fn parse_for_in_type(&mut self) -> Ty_ { /* Parses whatever can come after a `for` keyword in a type. The `for` has already been consumed. Deprecated: - for <'lt> |S| -> T - for <'lt> proc(S) -> T Eventually: - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T - for <'lt> path::foo(a, b) */ // parse <'lt> let lifetime_defs = self.parse_late_bound_lifetime_defs(); // examine next token to decide to do if self.eat_keyword(keywords::Proc) { self.parse_proc_type(lifetime_defs) } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() { self.parse_ty_bare_fn_or_ty_closure(lifetime_defs) } else if self.token == token::ModSep || self.token.is_ident() || self.token.is_path() { let trait_ref = self.parse_trait_ref(); let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs, trait_ref: trait_ref }; let other_bounds = if self.eat(&token::BinOp(token::Plus)) { self.parse_ty_param_bounds() } else { OwnedSlice::empty() }; let all_bounds = Some(TraitTyParamBound(poly_trait_ref)).into_iter() .chain(other_bounds.into_vec().into_iter()) .collect(); ast::TyPolyTraitRef(all_bounds) } else { self.parse_ty_closure(lifetime_defs) } } pub fn parse_ty_path(&mut self, plus_allowed: bool) -> Ty_ { let mode = if plus_allowed { LifetimeAndTypesAndBounds } else { LifetimeAndTypesWithoutColons }; let PathAndBounds { path, bounds } = self.parse_path(mode); TyPath(path, bounds, ast::DUMMY_NODE_ID) } /// parse a TyBareFn type: pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ { /* [unsafe] [extern "ABI"] fn <'lt> (S) -> T ^~~~^ ^~~~^ ^~~~^ ^~^ ^ | | | | | | | | | Return type | | | Argument types | | Lifetimes | ABI Function Style */ let fn_style = self.parse_unsafety(); let abi = if self.eat_keyword(keywords::Extern) { self.parse_opt_abi().unwrap_or(abi::C) } else { abi::Rust }; self.expect_keyword(keywords::Fn); let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs); let (inputs, variadic) = self.parse_fn_args(false, true); let ret_ty = self.parse_ret_ty(); let decl = P(FnDecl { inputs: inputs, output: ret_ty, variadic: variadic }); TyBareFn(P(BareFnTy { abi: abi, fn_style: fn_style, lifetimes: lifetime_defs, decl: decl })) } /// Parses a procedure type (`proc`). The initial `proc` keyword must /// already have been parsed. pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ { /* proc <'lt> (S) [:Bounds] -> T ^~~^ ^~~~^ ^ ^~~~~~~~^ ^ | | | | | | | | | Return type | | | Bounds | | Argument types | Legacy lifetimes the `proc` keyword */ let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs); let (inputs, variadic) = self.parse_fn_args(false, false); let bounds = self.parse_colon_then_ty_param_bounds(); let ret_ty = self.parse_ret_ty(); let decl = P(FnDecl { inputs: inputs, output: ret_ty, variadic: variadic }); TyProc(P(ClosureTy { fn_style: NormalFn, onceness: Once, bounds: bounds, decl: decl, lifetimes: lifetime_defs, })) } /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`). pub fn parse_optional_unboxed_closure_kind(&mut self) -> Option<UnboxedClosureKind> { if self.token == token::BinOp(token::And) && self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) && self.look_ahead(2, |t| *t == token::Colon) { self.bump(); self.bump(); self.bump(); return Some(FnMutUnboxedClosureKind) } if self.token == token::BinOp(token::And) && self.look_ahead(1, |t| *t == token::Colon) { self.bump(); self.bump(); return Some(FnUnboxedClosureKind) } if self.eat(&token::Colon) { return Some(FnOnceUnboxedClosureKind) } return None } pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ { // Both bare fns and closures can begin with stuff like unsafe // and extern. So we just scan ahead a few tokens to see if we see // a `fn`. // // Closure: [unsafe] <'lt> |S| [:Bounds] -> T // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T if self.token.is_keyword(keywords::Fn) { self.parse_ty_bare_fn(lifetime_defs) } else if self.token.is_keyword(keywords::Extern) { self.parse_ty_bare_fn(lifetime_defs) } else if self.token.is_keyword(keywords::Unsafe) { if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) || t.is_keyword(keywords::Extern)) { self.parse_ty_bare_fn(lifetime_defs) } else { self.parse_ty_closure(lifetime_defs) } } else { self.parse_ty_closure(lifetime_defs) } } /// Parse a TyClosure type pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ { /* [unsafe] <'lt> |S| [:Bounds] -> T ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^ | | | | | | | | | Return type | | | Closure bounds | | Argument types | Deprecated lifetime defs | Function Style */ let fn_style = self.parse_unsafety(); let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs); let inputs = if self.eat(&token::OrOr) { Vec::new() } else { self.expect_or(); let inputs = self.parse_seq_to_before_or( &token::Comma, |p| p.parse_arg_general(false)); self.expect_or(); inputs }; let bounds = self.parse_colon_then_ty_param_bounds(); let output = self.parse_ret_ty(); let decl = P(FnDecl { inputs: inputs, output: output, variadic: false }); TyClosure(P(ClosureTy { fn_style: fn_style, onceness: Many, bounds: bounds, decl: decl, lifetimes: lifetime_defs, })) } pub fn parse_unsafety(&mut self) -> FnStyle { if self.eat_keyword(keywords::Unsafe) { return UnsafeFn; } else { return NormalFn; } } /// Parses `[ 'for' '<' lifetime_defs '>' ]' fn parse_legacy_lifetime_defs(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Vec<ast::LifetimeDef> { if self.eat(&token::Lt) { if lifetime_defs.is_empty() { self.warn("deprecated syntax; use the `for` keyword now \ (e.g. change `fn<'a>` to `for<'a> fn`)"); let lifetime_defs = self.parse_lifetime_defs(); self.expect_gt(); lifetime_defs } else { self.fatal("cannot use new `for` keyword and older syntax together"); } } else { lifetime_defs } } /// Parses `type Foo;` in a trait declaration only. The `type` keyword has /// already been parsed. fn parse_associated_type(&mut self, attrs: Vec<Attribute>) -> AssociatedType { let ty_param = self.parse_ty_param(); self.expect(&token::Semi); AssociatedType { attrs: attrs, ty_param: ty_param, } } /// Parses `type Foo = TYPE;` in an implementation declaration only. The /// `type` keyword has already been parsed. fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility) -> Typedef { let lo = self.span.lo; let ident = self.parse_ident(); self.expect(&token::Eq); let typ = self.parse_ty(true); let hi = self.span.hi; self.expect(&token::Semi); Typedef { id: ast::DUMMY_NODE_ID, span: mk_sp(lo, hi), ident: ident, vis: vis, attrs: attrs, typ: typ, } } /// Parse the items in a trait declaration pub fn parse_trait_items(&mut self) -> Vec<TraitItem> { self.parse_unspanned_seq( &token::OpenDelim(token::Brace), &token::CloseDelim(token::Brace), seq_sep_none(), |p| { let attrs = p.parse_outer_attributes(); if p.eat_keyword(keywords::Type) { TypeTraitItem(P(p.parse_associated_type(attrs))) } else { let lo = p.span.lo; let vis = p.parse_visibility(); let abi = if p.eat_keyword(keywords::Extern) { p.parse_opt_abi().unwrap_or(abi::C) } else { abi::Rust }; let style = p.parse_fn_style(); let ident = p.parse_ident(); let mut generics = p.parse_generics(); let (explicit_self, d) = p.parse_fn_decl_with_self(|p| { // This is somewhat dubious; We don't want to allow // argument names to be left off if there is a // definition... p.parse_arg_general(false) }); p.parse_where_clause(&mut generics); let hi = p.last_span.hi; match p.token { token::Semi => { p.bump(); debug!("parse_trait_methods(): parsing required method"); RequiredMethod(TypeMethod { ident: ident, attrs: attrs, fn_style: style, decl: d, generics: generics, abi: abi, explicit_self: explicit_self, id: ast::DUMMY_NODE_ID, span: mk_sp(lo, hi), vis: vis, }) } token::OpenDelim(token::Brace) => { debug!("parse_trait_methods(): parsing provided method"); let (inner_attrs, body) = p.parse_inner_attrs_and_block(); let mut attrs = attrs; attrs.push_all(inner_attrs.as_slice()); ProvidedMethod(P(ast::Method { attrs: attrs, id: ast::DUMMY_NODE_ID, span: mk_sp(lo, hi), node: ast::MethDecl(ident, generics, abi, explicit_self, style, d, body, vis) })) } _ => { let token_str = p.this_token_to_string(); p.fatal((format!("expected `;` or `{{`, found `{}`", token_str)).as_slice()) } } } }) } /// Parse a possibly mutable type pub fn parse_mt(&mut self) -> MutTy { let mutbl = self.parse_mutability(); let t = self.parse_ty(true); MutTy { ty: t, mutbl: mutbl } } /// Parse [mut/const/imm] ID : TY /// now used only by obsolete record syntax parser... pub fn parse_ty_field(&mut self) -> TypeField { let lo = self.span.lo; let mutbl = self.parse_mutability(); let id = self.parse_ident(); self.expect(&token::Colon); let ty = self.parse_ty(true); let hi = ty.span.hi; ast::TypeField { ident: id, mt: MutTy { ty: ty, mutbl: mutbl }, span: mk_sp(lo, hi), } } /// Parse optional return type [ -> TY ] in function decl pub fn parse_ret_ty(&mut self) -> FunctionRetTy { if self.eat(&token::RArrow) { if self.eat(&token::Not) { NoReturn(self.span) } else { Return(self.parse_ty(true)) } } else { let pos = self.span.lo; Return(P(Ty { id: ast::DUMMY_NODE_ID, node: TyTup(vec![]), span: mk_sp(pos, pos), })) } } /// Parse a type. /// /// The second parameter specifies whether the `+` binary operator is /// allowed in the type grammar. pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> { maybe_whole!(no_clone self, NtTy); let lo = self.span.lo; let t = if self.token == token::OpenDelim(token::Paren) { self.bump(); // (t) is a parenthesized ty // (t,) is the type of a tuple with only one field, // of type t let mut ts = vec![]; let mut last_comma = false; while self.token != token::CloseDelim(token::Paren) { ts.push(self.parse_ty(true)); if self.token == token::Comma { last_comma = true; self.bump(); } else { last_comma = false; break; } } self.expect(&token::CloseDelim(token::Paren)); if ts.len() == 1 && !last_comma { TyParen(ts.into_iter().nth(0).unwrap()) } else { TyTup(ts) } } else if self.token == token::Tilde { // OWNED POINTER self.bump(); let last_span = self.last_span; match self.token { token::OpenDelim(token::Bracket) => self.obsolete(last_span, ObsoleteOwnedVector), _ => self.obsolete(last_span, ObsoleteOwnedType) } TyTup(vec![self.parse_ty(false)]) } else if self.token == token::BinOp(token::Star) { // STAR POINTER (bare pointer?) self.bump(); TyPtr(self.parse_ptr()) } else if self.token == token::OpenDelim(token::Bracket) { // VECTOR self.expect(&token::OpenDelim(token::Bracket)); let t = self.parse_ty(true); // Parse the `, ..e` in `[ int, ..e ]` // where `e` is a const expression let t = match self.maybe_parse_fixed_vstore() { None => TyVec(t), Some(suffix) => TyFixedLengthVec(t, suffix) }; self.expect(&token::CloseDelim(token::Bracket)); t } else if self.token == token::BinOp(token::And) || self.token == token::AndAnd { // BORROWED POINTER self.expect_and(); self.parse_borrowed_pointee() } else if self.token.is_keyword(keywords::For) { self.parse_for_in_type() } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() { // BARE FUNCTION OR CLOSURE self.parse_ty_bare_fn_or_ty_closure(Vec::new()) } else if self.token == token::BinOp(token::Or) || self.token == token::OrOr || (self.token == token::Lt && self.look_ahead(1, |t| { *t == token::Gt || t.is_lifetime() })) { // CLOSURE self.parse_ty_closure(Vec::new()) } else if self.eat_keyword(keywords::Typeof) { // TYPEOF // In order to not be ambiguous, the type must be surrounded by parens. self.expect(&token::OpenDelim(token::Paren)); let e = self.parse_expr(); self.expect(&token::CloseDelim(token::Paren)); TyTypeof(e) } else if self.eat_keyword(keywords::Proc) { self.parse_proc_type(Vec::new()) } else if self.token == token::Lt { // QUALIFIED PATH `<TYPE as TRAIT_REF>::item` self.bump(); let self_type = self.parse_ty(true); self.expect_keyword(keywords::As); let trait_ref = self.parse_trait_ref(); self.expect(&token::Gt); self.expect(&token::ModSep); let item_name = self.parse_ident(); TyQPath(P(QPath { self_type: self_type, trait_ref: P(trait_ref), item_name: item_name, })) } else if self.token == token::ModSep || self.token.is_ident() || self.token.is_path() { // NAMED TYPE self.parse_ty_path(plus_allowed) } else if self.eat(&token::Underscore) { // TYPE TO BE INFERRED TyInfer } else { let msg = format!("expected type, found token {}", self.token); self.fatal(msg.as_slice()); }; let sp = mk_sp(lo, self.last_span.hi); P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}) } pub fn parse_borrowed_pointee(&mut self) -> Ty_ { // look for `&'lt` or `&'foo ` and interpret `foo` as the region name: let opt_lifetime = self.parse_opt_lifetime(); let mt = self.parse_mt(); return TyRptr(opt_lifetime, mt); } pub fn parse_ptr(&mut self) -> MutTy { let mutbl = if self.eat_keyword(keywords::Mut) { MutMutable } else if self.eat_keyword(keywords::Const) { MutImmutable } else { let span = self.last_span; self.span_err(span, "bare raw pointers are no longer allowed, you should \ likely use `*mut T`, but otherwise `*T` is now \ known as `*const T`"); MutImmutable }; let t = self.parse_ty(true); MutTy { ty: t, mutbl: mutbl } } pub fn is_named_argument(&mut self) -> bool { let offset = match self.token { token::BinOp(token::And) => 1, token::AndAnd => 1, _ if self.token.is_keyword(keywords::Mut) => 1, _ => 0 }; debug!("parser is_named_argument offset:{}", offset); if offset == 0 { is_plain_ident_or_underscore(&self.token) && self.look_ahead(1, |t| *t == token::Colon) } else { self.look_ahead(offset, |t| is_plain_ident_or_underscore(t)) && self.look_ahead(offset + 1, |t| *t == token::Colon) } } /// This version of parse arg doesn't necessarily require /// identifier names. pub fn parse_arg_general(&mut self, require_name: bool) -> Arg { let pat = if require_name || self.is_named_argument() { debug!("parse_arg_general parse_pat (require_name:{})", require_name); let pat = self.parse_pat(); self.expect(&token::Colon); pat } else { debug!("parse_arg_general ident_to_pat"); ast_util::ident_to_pat(ast::DUMMY_NODE_ID, self.last_span, special_idents::invalid) }; let t = self.parse_ty(true); Arg { ty: t, pat: pat, id: ast::DUMMY_NODE_ID, } } /// Parse a single function argument pub fn parse_arg(&mut self) -> Arg { self.parse_arg_general(true) } /// Parse an argument in a lambda header e.g. |arg, arg| pub fn parse_fn_block_arg(&mut self) -> Arg { let pat = self.parse_pat(); let t = if self.eat(&token::Colon) { self.parse_ty(true) } else { P(Ty { id: ast::DUMMY_NODE_ID, node: TyInfer, span: mk_sp(self.span.lo, self.span.hi), }) }; Arg { ty: t, pat: pat, id: ast::DUMMY_NODE_ID } } pub fn maybe_parse_fixed_vstore(&mut self) -> Option<P<ast::Expr>> { if self.token == token::Comma && self.look_ahead(1, |t| *t == token::DotDot) { self.bump(); self.bump(); Some(self.parse_expr()) } else { None } } /// Matches token_lit = LIT_INTEGER | ... pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ { match *tok { token::Literal(lit, suf) => { let (suffix_illegal, out) = match lit { token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).val0())), token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).val0())), // there are some valid suffixes for integer and // float literals, so all the handling is done // internally. token::Integer(s) => { (false, parse::integer_lit(s.as_str(), suf.as_ref().map(|s| s.as_str()), &self.sess.span_diagnostic, self.last_span)) } token::Float(s) => { (false, parse::float_lit(s.as_str(), suf.as_ref().map(|s| s.as_str()), &self.sess.span_diagnostic, self.last_span)) } token::Str_(s) => { (true, LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()), ast::CookedStr)) } token::StrRaw(s, n) => { (true, LitStr( token::intern_and_get_ident( parse::raw_str_lit(s.as_str()).as_slice()), ast::RawStr(n))) } token::Binary(i) => (true, LitBinary(parse::binary_lit(i.as_str()))), token::BinaryRaw(i, _) => (true, LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))), }; if suffix_illegal { let sp = self.last_span; self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf) } out } _ => { self.unexpected_last(tok); } } } /// Matches lit = true | false | token_lit pub fn parse_lit(&mut self) -> Lit { let lo = self.span.lo; let lit = if self.eat_keyword(keywords::True) { LitBool(true) } else if self.eat_keyword(keywords::False) { LitBool(false) } else { let token = self.bump_and_get(); let lit = self.lit_from_token(&token); lit }; codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) } } /// matches '-' lit | lit pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> { let minus_lo = self.span.lo; let minus_present = self.eat(&token::BinOp(token::Minus)); let lo = self.span.lo; let literal = P(self.parse_lit()); let hi = self.span.hi; let expr = self.mk_expr(lo, hi, ExprLit(literal)); if minus_present { let minus_hi = self.span.hi; let unary = self.mk_unary(UnNeg, expr); self.mk_expr(minus_lo, minus_hi, unary) } else { expr } } /// Parses a path and optional type parameter bounds, depending on the /// mode. The `mode` parameter determines whether lifetimes, types, and/or /// bounds are permitted and whether `::` must precede type parameter /// groups. pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds { // Check for a whole path... let found = match self.token { token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()), _ => None, }; match found { Some(token::Interpolated(token::NtPath(box path))) => { return PathAndBounds { path: path, bounds: None } } _ => {} } let lo = self.span.lo; let is_global = self.eat(&token::ModSep); // Parse any number of segments and bound sets. A segment is an // identifier followed by an optional lifetime and a set of types. // A bound set is a set of type parameter bounds. let segments = match mode { LifetimeAndTypesWithoutColons | LifetimeAndTypesAndBounds => { self.parse_path_segments_without_colons() } LifetimeAndTypesWithColons => { self.parse_path_segments_with_colons() } NoTypesAllowed => { self.parse_path_segments_without_types() } }; // Next, parse a plus and bounded type parameters, if // applicable. We need to remember whether the separate was // present for later, because in some contexts it's a parse // error. let opt_bounds = { if mode == LifetimeAndTypesAndBounds && self.eat(&token::BinOp(token::Plus)) { let bounds = self.parse_ty_param_bounds(); // For some reason that I do not fully understand, we // do not permit an empty list in the case where it is // introduced by a `+`, but we do for `:` and other // separators. -nmatsakis if bounds.len() == 0 { let last_span = self.last_span; self.span_err(last_span, "at least one type parameter bound \ must be specified"); } Some(bounds) } else { None } }; // Assemble the span. let span = mk_sp(lo, self.last_span.hi); // Assemble the result. PathAndBounds { path: ast::Path { span: span, global: is_global, segments: segments, }, bounds: opt_bounds, } } /// Examples: /// - `a::b<T,U>::c<V,W>` /// - `a::b<T,U>::c(V) -> W` /// - `a::b<T,U>::c(V)` pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> { let mut segments = Vec::new(); loop { // First, parse an identifier. let identifier = self.parse_ident(); // Parse types, optionally. let parameters = if self.eat_lt(false) { let (lifetimes, types) = self.parse_generic_values_after_lt(); ast::AngleBracketedParameters(ast::AngleBracketedParameterData { lifetimes: lifetimes, types: OwnedSlice::from_vec(types), }) } else if self.eat(&token::OpenDelim(token::Paren)) { let inputs = self.parse_seq_to_end( &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| p.parse_ty(true)); let output_ty = if self.eat(&token::RArrow) { Some(self.parse_ty(true)) } else { None }; ast::ParenthesizedParameters(ast::ParenthesizedParameterData { inputs: inputs, output: output_ty }) } else { ast::PathParameters::none() }; // Assemble and push the result. segments.push(ast::PathSegment { identifier: identifier, parameters: parameters }); // Continue only if we see a `::` if !self.eat(&token::ModSep) { return segments; } } } /// Examples: /// - `a::b::<T,U>::c` pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> { let mut segments = Vec::new(); loop { // First, parse an identifier. let identifier = self.parse_ident(); // If we do not see a `::`, stop. if !self.eat(&token::ModSep) { segments.push(ast::PathSegment { identifier: identifier, parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData { lifetimes: Vec::new(), types: OwnedSlice::empty(), }) }); return segments; } // Check for a type segment. if self.eat_lt(false) { // Consumed `a::b::<`, go look for types let (lifetimes, types) = self.parse_generic_values_after_lt(); segments.push(ast::PathSegment { identifier: identifier, parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData { lifetimes: lifetimes, types: OwnedSlice::from_vec(types), }), }); // Consumed `a::b::<T,U>`, check for `::` before proceeding if !self.eat(&token::ModSep) { return segments; } } else { // Consumed `a::`, go look for `b` segments.push(ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), }); } } } /// Examples: /// - `a::b::c` pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> { let mut segments = Vec::new(); loop { // First, parse an identifier. let identifier = self.parse_ident(); // Assemble and push the result. segments.push(ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none() }); // If we do not see a `::`, stop. if !self.eat(&token::ModSep) { return segments; } } } /// parses 0 or 1 lifetime pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> { match self.token { token::Lifetime(..) => { Some(self.parse_lifetime()) } _ => { None } } } /// Parses a single lifetime /// Matches lifetime = LIFETIME pub fn parse_lifetime(&mut self) -> ast::Lifetime { match self.token { token::Lifetime(i) => { let span = self.span; self.bump(); return ast::Lifetime { id: ast::DUMMY_NODE_ID, span: span, name: i.name }; } _ => { self.fatal(format!("expected a lifetime name").as_slice()); } } } pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> { /*! * Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` * where `lifetime_def = lifetime [':' lifetimes]` */ let mut res = Vec::new(); loop { match self.token { token::Lifetime(_) => { let lifetime = self.parse_lifetime(); let bounds = if self.eat(&token::Colon) { self.parse_lifetimes(token::BinOp(token::Plus)) } else { Vec::new() }; res.push(ast::LifetimeDef { lifetime: lifetime, bounds: bounds }); } _ => { return res; } } match self.token { token::Comma => { self.bump(); } token::Gt => { return res; } token::BinOp(token::Shr) => { return res; } _ => { let msg = format!("expected `,` or `>` after lifetime \ name, got: {}", self.token); self.fatal(msg.as_slice()); } } } } // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) // actually, it matches the empty one too, but putting that in there // messes up the grammar.... pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> { /*! * Parses zero or more comma separated lifetimes. * Expects each lifetime to be followed by either * a comma or `>`. Used when parsing type parameter * lists, where we expect something like `<'a, 'b, T>`. */ let mut res = Vec::new(); loop { match self.token { token::Lifetime(_) => { res.push(self.parse_lifetime()); } _ => { return res; } } if self.token != sep { return res; } self.bump(); } } /// Parse mutability declaration (mut/const/imm) pub fn parse_mutability(&mut self) -> Mutability { if self.eat_keyword(keywords::Mut) { MutMutable } else { MutImmutable } } /// Parse ident COLON expr pub fn parse_field(&mut self) -> Field { let lo = self.span.lo; let i = self.parse_ident(); let hi = self.last_span.hi; self.expect(&token::Colon); let e = self.parse_expr(); ast::Field { ident: spanned(lo, hi, i), span: mk_sp(lo, e.span.hi), expr: e, } } pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> { P(Expr { id: ast::DUMMY_NODE_ID, node: node, span: mk_sp(lo, hi), }) } pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ { ExprUnary(unop, expr) } pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ { ExprBinary(binop, lhs, rhs) } pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ { ExprCall(f, args) } fn mk_method_call(&mut self, ident: ast::SpannedIdent, tps: Vec<P<Ty>>, args: Vec<P<Expr>>) -> ast::Expr_ { ExprMethodCall(ident, tps, args) } pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ { ExprIndex(expr, idx) } pub fn mk_slice(&mut self, expr: P<Expr>, start: Option<P<Expr>>, end: Option<P<Expr>>, mutbl: Mutability) -> ast::Expr_ { ExprSlice(expr, start, end, mutbl) } pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent, tys: Vec<P<Ty>>) -> ast::Expr_ { ExprField(expr, ident, tys) } pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>, tys: Vec<P<Ty>>) -> ast::Expr_ { ExprTupField(expr, idx, tys) } pub fn mk_assign_op(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ { ExprAssignOp(binop, lhs, rhs) } pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> { P(Expr { id: ast::DUMMY_NODE_ID, node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}), span: mk_sp(lo, hi), }) } pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> { let span = &self.span; let lv_lit = P(codemap::Spanned { node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)), span: *span }); P(Expr { id: ast::DUMMY_NODE_ID, node: ExprLit(lv_lit), span: *span, }) } fn expect_open_delim(&mut self) -> token::DelimToken { match self.token { token::OpenDelim(delim) => { self.bump(); delim }, _ => self.fatal("expected open delimiter"), }<|fim▁hole|> /// At the bottom (top?) of the precedence hierarchy, /// parse things like parenthesized exprs, /// macros, return, etc. pub fn parse_bottom_expr(&mut self) -> P<Expr> { maybe_whole_expr!(self); let lo = self.span.lo; let mut hi = self.span.hi; let ex: Expr_; match self.token { token::OpenDelim(token::Paren) => { self.bump(); // (e) is parenthesized e // (e,) is a tuple with only one field, e let mut es = vec![]; let mut trailing_comma = false; while self.token != token::CloseDelim(token::Paren) { es.push(self.parse_expr()); self.commit_expr(&**es.last().unwrap(), &[], &[token::Comma, token::CloseDelim(token::Paren)]); if self.token == token::Comma { trailing_comma = true; self.bump(); } else { trailing_comma = false; break; } } self.bump(); hi = self.span.hi; return if es.len() == 1 && !trailing_comma { self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap())) } else { self.mk_expr(lo, hi, ExprTup(es)) } }, token::OpenDelim(token::Brace) => { self.bump(); let blk = self.parse_block_tail(lo, DefaultBlock); return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)); }, token::BinOp(token::Or) | token::OrOr => { return self.parse_lambda_expr(CaptureByRef); }, // FIXME #13626: Should be able to stick in // token::SELF_KEYWORD_NAME token::Ident(id @ ast::Ident { name: ast::Name(token::SELF_KEYWORD_NAME_NUM), ctxt: _ }, token::Plain) => { self.bump(); let path = ast_util::ident_to_path(mk_sp(lo, hi), id); ex = ExprPath(path); hi = self.last_span.hi; } token::OpenDelim(token::Bracket) => { self.bump(); if self.token == token::CloseDelim(token::Bracket) { // Empty vector. self.bump(); ex = ExprVec(Vec::new()); } else { // Nonempty vector. let first_expr = self.parse_expr(); if self.token == token::Comma && self.look_ahead(1, |t| *t == token::DotDot) { // Repeating vector syntax: [ 0, ..512 ] self.bump(); self.bump(); let count = self.parse_expr(); self.expect(&token::CloseDelim(token::Bracket)); ex = ExprRepeat(first_expr, count); } else if self.token == token::Comma { // Vector with two or more elements. self.bump(); let remaining_exprs = self.parse_seq_to_end( &token::CloseDelim(token::Bracket), seq_sep_trailing_allowed(token::Comma), |p| p.parse_expr() ); let mut exprs = vec!(first_expr); exprs.extend(remaining_exprs.into_iter()); ex = ExprVec(exprs); } else { // Vector with one element. self.expect(&token::CloseDelim(token::Bracket)); ex = ExprVec(vec!(first_expr)); } } hi = self.last_span.hi; } _ => { if self.eat_keyword(keywords::Move) { return self.parse_lambda_expr(CaptureByValue); } if self.eat_keyword(keywords::Proc) { let decl = self.parse_proc_decl(); let body = self.parse_expr(); let fakeblock = P(ast::Block { id: ast::DUMMY_NODE_ID, view_items: Vec::new(), stmts: Vec::new(), rules: DefaultBlock, span: body.span, expr: Some(body), }); return self.mk_expr(lo, fakeblock.span.hi, ExprProc(decl, fakeblock)); } if self.eat_keyword(keywords::If) { return self.parse_if_expr(); } if self.eat_keyword(keywords::For) { return self.parse_for_expr(None); } if self.eat_keyword(keywords::While) { return self.parse_while_expr(None); } if self.token.is_lifetime() { let lifetime = self.get_lifetime(); self.bump(); self.expect(&token::Colon); if self.eat_keyword(keywords::While) { return self.parse_while_expr(Some(lifetime)) } if self.eat_keyword(keywords::For) { return self.parse_for_expr(Some(lifetime)) } if self.eat_keyword(keywords::Loop) { return self.parse_loop_expr(Some(lifetime)) } self.fatal("expected `while`, `for`, or `loop` after a label") } if self.eat_keyword(keywords::Loop) { return self.parse_loop_expr(None); } if self.eat_keyword(keywords::Continue) { let lo = self.span.lo; let ex = if self.token.is_lifetime() { let lifetime = self.get_lifetime(); self.bump(); ExprAgain(Some(lifetime)) } else { ExprAgain(None) }; let hi = self.span.hi; return self.mk_expr(lo, hi, ex); } if self.eat_keyword(keywords::Match) { return self.parse_match_expr(); } if self.eat_keyword(keywords::Unsafe) { return self.parse_block_expr( lo, UnsafeBlock(ast::UserProvided)); } if self.eat_keyword(keywords::Return) { // RETURN expression if self.token.can_begin_expr() { let e = self.parse_expr(); hi = e.span.hi; ex = ExprRet(Some(e)); } else { ex = ExprRet(None); } } else if self.eat_keyword(keywords::Break) { // BREAK expression if self.token.is_lifetime() { let lifetime = self.get_lifetime(); self.bump(); ex = ExprBreak(Some(lifetime)); } else { ex = ExprBreak(None); } hi = self.span.hi; } else if self.token == token::ModSep || self.token.is_ident() && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False) { let pth = self.parse_path(LifetimeAndTypesWithColons).path; // `!`, as an operator, is prefix, so we know this isn't that if self.token == token::Not { // MACRO INVOCATION expression self.bump(); let delim = self.expect_open_delim(); let tts = self.parse_seq_to_end( &token::CloseDelim(delim), seq_sep_none(), |p| p.parse_token_tree()); let hi = self.span.hi; return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)); } if self.token == token::OpenDelim(token::Brace) { // This is a struct literal, unless we're prohibited // from parsing struct literals here. if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) { // It's a struct literal. self.bump(); let mut fields = Vec::new(); let mut base = None; while self.token != token::CloseDelim(token::Brace) { if self.eat(&token::DotDot) { base = Some(self.parse_expr()); break; } fields.push(self.parse_field()); self.commit_expr(&*fields.last().unwrap().expr, &[token::Comma], &[token::CloseDelim(token::Brace)]); } if fields.len() == 0 && base.is_none() { let last_span = self.last_span; self.span_err(last_span, "structure literal must either \ have at least one field or use \ functional structure update \ syntax"); } hi = self.span.hi; self.expect(&token::CloseDelim(token::Brace)); ex = ExprStruct(pth, fields, base); return self.mk_expr(lo, hi, ex); } } hi = pth.span.hi; ex = ExprPath(pth); } else { // other literal expression let lit = self.parse_lit(); hi = lit.span.hi; ex = ExprLit(P(lit)); } } } return self.mk_expr(lo, hi, ex); } /// Parse a block or unsafe block pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode) -> P<Expr> { self.expect(&token::OpenDelim(token::Brace)); let blk = self.parse_block_tail(lo, blk_mode); return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)); } /// parse a.b or a(13) or a[4] or just a pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> { let b = self.parse_bottom_expr(); self.parse_dot_or_call_expr_with(b) } pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> { let mut e = e0; let lo = e.span.lo; let mut hi; loop { // expr.f if self.eat(&token::Dot) { match self.token { token::Ident(i, _) => { let dot = self.last_span.hi; hi = self.span.hi; self.bump(); let (_, tys) = if self.eat(&token::ModSep) { self.expect_lt(); self.parse_generic_values_after_lt() } else { (Vec::new(), Vec::new()) }; // expr.f() method call match self.token { token::OpenDelim(token::Paren) => { let mut es = self.parse_unspanned_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| p.parse_expr() ); hi = self.last_span.hi; es.insert(0, e); let id = spanned(dot, hi, i); let nd = self.mk_method_call(id, tys, es); e = self.mk_expr(lo, hi, nd); } _ => { if !tys.is_empty() { let last_span = self.last_span; self.span_err(last_span, "field expressions may not \ have type parameters"); } let id = spanned(dot, hi, i); let field = self.mk_field(e, id, tys); e = self.mk_expr(lo, hi, field); } } } token::Literal(token::Integer(n), suf) => { let sp = self.span; self.expect_no_suffix(sp, "tuple index", suf); let index = n.as_str(); let dot = self.last_span.hi; hi = self.span.hi; self.bump(); let (_, tys) = if self.eat(&token::ModSep) { self.expect_lt(); self.parse_generic_values_after_lt() } else { (Vec::new(), Vec::new()) }; let num = from_str::<uint>(index); match num { Some(n) => { let id = spanned(dot, hi, n); let field = self.mk_tup_field(e, id, tys); e = self.mk_expr(lo, hi, field); } None => { let last_span = self.last_span; self.span_err(last_span, "invalid tuple or tuple struct index"); } } } token::Literal(token::Float(n), _suf) => { self.bump(); let last_span = self.last_span; let fstr = n.as_str(); self.span_err(last_span, format!("unexpected token: `{}`", n.as_str()).as_slice()); if fstr.chars().all(|x| "0123456789.".contains_char(x)) { let float = match from_str::<f64>(fstr) { Some(f) => f, None => continue, }; self.span_help(last_span, format!("try parenthesizing the first index; e.g., `(foo.{}){}`", float.trunc() as uint, float.fract().to_string()[1..]).as_slice()); } self.abort_if_errors(); } _ => self.unexpected() } continue; } if self.expr_is_complete(&*e) { break; } match self.token { // expr(...) token::OpenDelim(token::Paren) => { let es = self.parse_unspanned_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| p.parse_expr() ); hi = self.last_span.hi; let nd = self.mk_call(e, es); e = self.mk_expr(lo, hi, nd); } // expr[...] // Could be either an index expression or a slicing expression. // Any slicing non-terminal can have a mutable version with `mut` // after the opening square bracket. token::OpenDelim(token::Bracket) => { self.bump(); let mutbl = if self.eat_keyword(keywords::Mut) { MutMutable } else { MutImmutable }; match self.token { // e[] token::CloseDelim(token::Bracket) => { self.bump(); hi = self.span.hi; let slice = self.mk_slice(e, None, None, mutbl); e = self.mk_expr(lo, hi, slice) } // e[..e] token::DotDot => { self.bump(); match self.token { // e[..] token::CloseDelim(token::Bracket) => { self.bump(); hi = self.span.hi; let slice = self.mk_slice(e, None, None, mutbl); e = self.mk_expr(lo, hi, slice); self.span_err(e.span, "incorrect slicing expression: `[..]`"); self.span_note(e.span, "use `expr[]` to construct a slice of the whole of expr"); } // e[..e] _ => { hi = self.span.hi; let e2 = self.parse_expr(); self.commit_expr_expecting(&*e2, token::CloseDelim(token::Bracket)); let slice = self.mk_slice(e, None, Some(e2), mutbl); e = self.mk_expr(lo, hi, slice) } } } // e[e] | e[e..] | e[e..e] _ => { let ix = self.parse_expr(); match self.token { // e[e..] | e[e..e] token::DotDot => { self.bump(); let e2 = match self.token { // e[e..] token::CloseDelim(token::Bracket) => { self.bump(); None } // e[e..e] _ => { let e2 = self.parse_expr(); self.commit_expr_expecting(&*e2, token::CloseDelim(token::Bracket)); Some(e2) } }; hi = self.span.hi; let slice = self.mk_slice(e, Some(ix), e2, mutbl); e = self.mk_expr(lo, hi, slice) } // e[e] _ => { if mutbl == ast::MutMutable { self.span_err(e.span, "`mut` keyword is invalid in index expressions"); } hi = self.span.hi; self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)); let index = self.mk_index(e, ix); e = self.mk_expr(lo, hi, index) } } } } } _ => return e } } return e; } /// Parse an optional separator followed by a Kleene-style /// repetition token (+ or *). pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) { fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> { match parser.token { token::BinOp(token::Star) => { parser.bump(); Some(ast::ZeroOrMore) }, token::BinOp(token::Plus) => { parser.bump(); Some(ast::OneOrMore) }, _ => None } }; match parse_kleene_op(self) { Some(kleene_op) => return (None, kleene_op), None => {} } let separator = self.bump_and_get(); match parse_kleene_op(self) { Some(zerok) => (Some(separator), zerok), None => self.fatal("expected `*` or `+`") } } /// parse a single token tree from the input. pub fn parse_token_tree(&mut self) -> TokenTree { // FIXME #6994: currently, this is too eager. It // parses token trees but also identifies TtSequence's // and token::SubstNt's; it's too early to know yet // whether something will be a nonterminal or a seq // yet. maybe_whole!(deref self, NtTT); // this is the fall-through for the 'match' below. // invariants: the current token is not a left-delimiter, // not an EOF, and not the desired right-delimiter (if // it were, parse_seq_to_before_end would have prevented // reaching this point. fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree { maybe_whole!(deref p, NtTT); match p.token { token::CloseDelim(_) => { // This is a conservative error: only report the last unclosed delimiter. The // previous unclosed delimiters could actually be closed! The parser just hasn't // gotten to them yet. match p.open_braces.last() { None => {} Some(&sp) => p.span_note(sp, "unclosed delimiter"), }; let token_str = p.this_token_to_string(); p.fatal(format!("incorrect close delimiter: `{}`", token_str).as_slice()) }, /* we ought to allow different depths of unquotation */ token::Dollar if p.quote_depth > 0u => { p.bump(); let sp = p.span; if p.token == token::OpenDelim(token::Paren) { let seq = p.parse_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_none(), |p| p.parse_token_tree() ); let (sep, repeat) = p.parse_sep_and_kleene_op(); let seq = match seq { Spanned { node, .. } => node, }; let name_num = macro_parser::count_names(seq.as_slice()); TtSequence(mk_sp(sp.lo, p.span.hi), Rc::new(SequenceRepetition { tts: seq, separator: sep, op: repeat, num_captures: name_num })) } else { // A nonterminal that matches or not let namep = match p.token { token::Ident(_, p) => p, _ => token::Plain }; let name = p.parse_ident(); if p.token == token::Colon && p.look_ahead(1, |t| t.is_ident()) { p.bump(); let kindp = match p.token { token::Ident(_, p) => p, _ => token::Plain }; let nt_kind = p.parse_ident(); let m = TtToken(sp, MatchNt(name, nt_kind, namep, kindp)); m } else { TtToken(sp, SubstNt(name, namep)) } } } _ => { TtToken(p.span, p.bump_and_get()) } } } match self.token { token::Eof => { let open_braces = self.open_braces.clone(); for sp in open_braces.iter() { self.span_help(*sp, "did you mean to close this delimiter?"); } // There shouldn't really be a span, but it's easier for the test runner // if we give it one self.fatal("this file contains an un-closed delimiter "); }, token::OpenDelim(delim) => { // The span for beginning of the delimited section let pre_span = self.span; // Parse the open delimiter. self.open_braces.push(self.span); let open_span = self.span; self.bump(); // Parse the token trees within the delimeters let tts = self.parse_seq_to_before_end( &token::CloseDelim(delim), seq_sep_none(), |p| p.parse_token_tree() ); // Parse the close delimiter. let close_span = self.span; self.bump(); self.open_braces.pop().unwrap(); // Expand to cover the entire delimited token tree let span = Span { hi: self.span.hi, ..pre_span }; TtDelimited(span, Rc::new(Delimited { delim: delim, open_span: open_span, tts: tts, close_span: close_span, })) }, _ => parse_non_delim_tt_tok(self), } } // parse a stream of tokens into a list of TokenTree's, // up to EOF. pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> { let mut tts = Vec::new(); while self.token != token::Eof { tts.push(self.parse_token_tree()); } tts } /// Parse a prefix-operator expr pub fn parse_prefix_expr(&mut self) -> P<Expr> { let lo = self.span.lo; let hi; let ex; match self.token { token::Not => { self.bump(); let e = self.parse_prefix_expr(); hi = e.span.hi; ex = self.mk_unary(UnNot, e); } token::BinOp(token::Minus) => { self.bump(); let e = self.parse_prefix_expr(); hi = e.span.hi; ex = self.mk_unary(UnNeg, e); } token::BinOp(token::Star) => { self.bump(); let e = self.parse_prefix_expr(); hi = e.span.hi; ex = self.mk_unary(UnDeref, e); } token::BinOp(token::And) | token::AndAnd => { self.expect_and(); let m = self.parse_mutability(); let e = self.parse_prefix_expr(); hi = e.span.hi; ex = ExprAddrOf(m, e); } token::Tilde => { self.bump(); let last_span = self.last_span; match self.token { token::OpenDelim(token::Bracket) => { self.obsolete(last_span, ObsoleteOwnedVector) }, _ => self.obsolete(last_span, ObsoleteOwnedExpr) } let e = self.parse_prefix_expr(); hi = e.span.hi; ex = self.mk_unary(UnUniq, e); } token::Ident(_, _) => { if !self.token.is_keyword(keywords::Box) { return self.parse_dot_or_call_expr(); } let lo = self.span.lo; self.bump(); // Check for a place: `box(PLACE) EXPR`. if self.eat(&token::OpenDelim(token::Paren)) { // Support `box() EXPR` as the default. if !self.eat(&token::CloseDelim(token::Paren)) { let place = self.parse_expr(); self.expect(&token::CloseDelim(token::Paren)); // Give a suggestion to use `box()` when a parenthesised expression is used if !self.token.can_begin_expr() { let span = self.span; let this_token_to_string = self.this_token_to_string(); self.span_err(span, format!("expected expression, found `{}`", this_token_to_string).as_slice()); let box_span = mk_sp(lo, self.last_span.hi); self.span_help(box_span, "perhaps you meant `box() (foo)` instead?"); self.abort_if_errors(); } let subexpression = self.parse_prefix_expr(); hi = subexpression.span.hi; ex = ExprBox(place, subexpression); return self.mk_expr(lo, hi, ex); } } // Otherwise, we use the unique pointer default. let subexpression = self.parse_prefix_expr(); hi = subexpression.span.hi; ex = self.mk_unary(UnUniq, subexpression); } _ => return self.parse_dot_or_call_expr() } return self.mk_expr(lo, hi, ex); } /// Parse an expression of binops pub fn parse_binops(&mut self) -> P<Expr> { let prefix_expr = self.parse_prefix_expr(); self.parse_more_binops(prefix_expr, 0) } /// Parse an expression of binops of at least min_prec precedence pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> { if self.expr_is_complete(&*lhs) { return lhs; } // Prevent dynamic borrow errors later on by limiting the // scope of the borrows. if self.token == token::BinOp(token::Or) && self.restrictions.contains(RESTRICTION_NO_BAR_OP) { return lhs; } let cur_opt = self.token.to_binop(); match cur_opt { Some(cur_op) => { let cur_prec = operator_prec(cur_op); if cur_prec > min_prec { self.bump(); let expr = self.parse_prefix_expr(); let rhs = self.parse_more_binops(expr, cur_prec); let lhs_span = lhs.span; let rhs_span = rhs.span; let binary = self.mk_binary(cur_op, lhs, rhs); let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary); self.parse_more_binops(bin, min_prec) } else { lhs } } None => { if as_prec > min_prec && self.eat_keyword(keywords::As) { let rhs = self.parse_ty(false); let _as = self.mk_expr(lhs.span.lo, rhs.span.hi, ExprCast(lhs, rhs)); self.parse_more_binops(_as, min_prec) } else { lhs } } } } /// Parse an assignment expression.... /// actually, this seems to be the main entry point for /// parsing an arbitrary expression. pub fn parse_assign_expr(&mut self) -> P<Expr> { let lo = self.span.lo; let lhs = self.parse_binops(); let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL; match self.token { token::Eq => { self.bump(); let rhs = self.parse_expr_res(restrictions); self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs)) } token::BinOpEq(op) => { self.bump(); let rhs = self.parse_expr_res(restrictions); let aop = match op { token::Plus => BiAdd, token::Minus => BiSub, token::Star => BiMul, token::Slash => BiDiv, token::Percent => BiRem, token::Caret => BiBitXor, token::And => BiBitAnd, token::Or => BiBitOr, token::Shl => BiShl, token::Shr => BiShr }; let rhs_span = rhs.span; let assign_op = self.mk_assign_op(aop, lhs, rhs); self.mk_expr(lo, rhs_span.hi, assign_op) } _ => { lhs } } } /// Parse an 'if' or 'if let' expression ('if' token already eaten) pub fn parse_if_expr(&mut self) -> P<Expr> { if self.token.is_keyword(keywords::Let) { return self.parse_if_let_expr(); } let lo = self.last_span.lo; let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL); let thn = self.parse_block(); let mut els: Option<P<Expr>> = None; let mut hi = thn.span.hi; if self.eat_keyword(keywords::Else) { let elexpr = self.parse_else_expr(); hi = elexpr.span.hi; els = Some(elexpr); } self.mk_expr(lo, hi, ExprIf(cond, thn, els)) } /// Parse an 'if let' expression ('if' token already eaten) pub fn parse_if_let_expr(&mut self) -> P<Expr> { let lo = self.last_span.lo; self.expect_keyword(keywords::Let); let pat = self.parse_pat(); self.expect(&token::Eq); let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL); let thn = self.parse_block(); let (hi, els) = if self.eat_keyword(keywords::Else) { let expr = self.parse_else_expr(); (expr.span.hi, Some(expr)) } else { (thn.span.hi, None) }; self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els)) } // `|args| expr` pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause) -> P<Expr> { let lo = self.span.lo; let (decl, optional_unboxed_closure_kind) = self.parse_fn_block_decl(); let body = self.parse_expr(); let fakeblock = P(ast::Block { id: ast::DUMMY_NODE_ID, view_items: Vec::new(), stmts: Vec::new(), span: body.span, expr: Some(body), rules: DefaultBlock, }); match optional_unboxed_closure_kind { Some(unboxed_closure_kind) => { self.mk_expr(lo, fakeblock.span.hi, ExprUnboxedFn(capture_clause, unboxed_closure_kind, decl, fakeblock)) } None => { self.mk_expr(lo, fakeblock.span.hi, ExprFnBlock(capture_clause, decl, fakeblock)) } } } pub fn parse_else_expr(&mut self) -> P<Expr> { if self.eat_keyword(keywords::If) { return self.parse_if_expr(); } else { let blk = self.parse_block(); return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)); } } /// Parse a 'for' .. 'in' expression ('for' token already eaten) pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> { // Parse: `for <src_pat> in <src_expr> <src_loop_block>` let lo = self.last_span.lo; let pat = self.parse_pat(); self.expect_keyword(keywords::In); let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL); let loop_block = self.parse_block(); let hi = self.span.hi; self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident)) } /// Parse a 'while' or 'while let' expression ('while' token already eaten) pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> { if self.token.is_keyword(keywords::Let) { return self.parse_while_let_expr(opt_ident); } let lo = self.last_span.lo; let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL); let body = self.parse_block(); let hi = body.span.hi; return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident)); } /// Parse a 'while let' expression ('while' token already eaten) pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> { let lo = self.last_span.lo; self.expect_keyword(keywords::Let); let pat = self.parse_pat(); self.expect(&token::Eq); let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL); let body = self.parse_block(); let hi = body.span.hi; return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident)); } pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> { let lo = self.last_span.lo; let body = self.parse_block(); let hi = body.span.hi; self.mk_expr(lo, hi, ExprLoop(body, opt_ident)) } fn parse_match_expr(&mut self) -> P<Expr> { let lo = self.last_span.lo; let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL); self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace)); let mut arms: Vec<Arm> = Vec::new(); while self.token != token::CloseDelim(token::Brace) { arms.push(self.parse_arm()); } let hi = self.span.hi; self.bump(); return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchNormal)); } pub fn parse_arm(&mut self) -> Arm { let attrs = self.parse_outer_attributes(); let pats = self.parse_pats(); let mut guard = None; if self.eat_keyword(keywords::If) { guard = Some(self.parse_expr()); } self.expect(&token::FatArrow); let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR); let require_comma = !classify::expr_is_simple_block(&*expr) && self.token != token::CloseDelim(token::Brace); if require_comma { self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]); } else { self.eat(&token::Comma); } ast::Arm { attrs: attrs, pats: pats, guard: guard, body: expr, } } /// Parse an expression pub fn parse_expr(&mut self) -> P<Expr> { return self.parse_expr_res(UNRESTRICTED); } /// Parse an expression, subject to the given restrictions pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> { let old = self.restrictions; self.restrictions = r; let e = self.parse_assign_expr(); self.restrictions = old; return e; } /// Parse the RHS of a local variable declaration (e.g. '= 14;') fn parse_initializer(&mut self) -> Option<P<Expr>> { if self.token == token::Eq { self.bump(); Some(self.parse_expr()) } else { None } } /// Parse patterns, separated by '|' s fn parse_pats(&mut self) -> Vec<P<Pat>> { let mut pats = Vec::new(); loop { pats.push(self.parse_pat()); if self.token == token::BinOp(token::Or) { self.bump(); } else { return pats; } }; } fn parse_pat_vec_elements( &mut self, ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) { let mut before = Vec::new(); let mut slice = None; let mut after = Vec::new(); let mut first = true; let mut before_slice = true; while self.token != token::CloseDelim(token::Bracket) { if first { first = false; } else { self.expect(&token::Comma); } if before_slice { if self.token == token::DotDot { self.bump(); if self.token == token::Comma || self.token == token::CloseDelim(token::Bracket) { slice = Some(P(ast::Pat { id: ast::DUMMY_NODE_ID, node: PatWild(PatWildMulti), span: self.span, })); before_slice = false; } else { let _ = self.parse_pat(); let span = self.span; self.obsolete(span, ObsoleteSubsliceMatch); } continue } } let subpat = self.parse_pat(); if before_slice && self.token == token::DotDot { self.bump(); slice = Some(subpat); before_slice = false; } else if before_slice { before.push(subpat); } else { after.push(subpat); } } (before, slice, after) } /// Parse the fields of a struct-like pattern fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) { let mut fields = Vec::new(); let mut etc = false; let mut first = true; while self.token != token::CloseDelim(token::Brace) { if first { first = false; } else { self.expect(&token::Comma); // accept trailing commas if self.token == token::CloseDelim(token::Brace) { break } } let lo = self.span.lo; let hi; if self.token == token::DotDot { self.bump(); if self.token != token::CloseDelim(token::Brace) { let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", "}", token_str).as_slice()) } etc = true; break; } let bind_type = if self.eat_keyword(keywords::Mut) { BindByValue(MutMutable) } else if self.eat_keyword(keywords::Ref) { BindByRef(self.parse_mutability()) } else { BindByValue(MutImmutable) }; let fieldname = self.parse_ident(); let (subpat, is_shorthand) = if self.token == token::Colon { match bind_type { BindByRef(..) | BindByValue(MutMutable) => { let token_str = self.this_token_to_string(); self.fatal(format!("unexpected `{}`", token_str).as_slice()) } _ => {} } self.bump(); let pat = self.parse_pat(); hi = pat.span.hi; (pat, false) } else { hi = self.last_span.hi; let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname}; (P(ast::Pat { id: ast::DUMMY_NODE_ID, node: PatIdent(bind_type, fieldpath, None), span: self.last_span }), true) }; fields.push(codemap::Spanned { span: mk_sp(lo, hi), node: ast::FieldPat { ident: fieldname, pat: subpat, is_shorthand: is_shorthand }}); } return (fields, etc); } /// Parse a pattern. pub fn parse_pat(&mut self) -> P<Pat> { maybe_whole!(self, NtPat); let lo = self.span.lo; let mut hi; let pat; match self.token { // parse _ token::Underscore => { self.bump(); pat = PatWild(PatWildSingle); hi = self.last_span.hi; return P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: mk_sp(lo, hi) }) } token::Tilde => { // parse ~pat self.bump(); let sub = self.parse_pat(); pat = PatBox(sub); let last_span = self.last_span; hi = last_span.hi; self.obsolete(last_span, ObsoleteOwnedPattern); return P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: mk_sp(lo, hi) }) } token::BinOp(token::And) | token::AndAnd => { // parse &pat let lo = self.span.lo; self.expect_and(); let sub = self.parse_pat(); pat = PatRegion(sub); hi = self.last_span.hi; return P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: mk_sp(lo, hi) }) } token::OpenDelim(token::Paren) => { // parse (pat,pat,pat,...) as tuple self.bump(); if self.token == token::CloseDelim(token::Paren) { self.bump(); pat = PatTup(vec![]); } else { let mut fields = vec!(self.parse_pat()); if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) { while self.token == token::Comma { self.bump(); if self.token == token::CloseDelim(token::Paren) { break; } fields.push(self.parse_pat()); } } if fields.len() == 1 { self.expect(&token::Comma); } self.expect(&token::CloseDelim(token::Paren)); pat = PatTup(fields); } hi = self.last_span.hi; return P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: mk_sp(lo, hi) }) } token::OpenDelim(token::Bracket) => { // parse [pat,pat,...] as vector pattern self.bump(); let (before, slice, after) = self.parse_pat_vec_elements(); self.expect(&token::CloseDelim(token::Bracket)); pat = ast::PatVec(before, slice, after); hi = self.last_span.hi; return P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: mk_sp(lo, hi) }) } _ => {} } // at this point, token != _, ~, &, &&, (, [ if (!(self.token.is_ident() || self.token.is_path()) && self.token != token::ModSep) || self.token.is_keyword(keywords::True) || self.token.is_keyword(keywords::False) { // Parse an expression pattern or exp .. exp. // // These expressions are limited to literals (possibly // preceded by unary-minus) or identifiers. let val = self.parse_literal_maybe_minus(); if (self.token == token::DotDotDot) && self.look_ahead(1, |t| { *t != token::Comma && *t != token::CloseDelim(token::Bracket) }) { self.bump(); let end = if self.token.is_ident() || self.token.is_path() { let path = self.parse_path(LifetimeAndTypesWithColons) .path; let hi = self.span.hi; self.mk_expr(lo, hi, ExprPath(path)) } else { self.parse_literal_maybe_minus() }; pat = PatRange(val, end); } else { pat = PatLit(val); } } else if self.eat_keyword(keywords::Mut) { pat = self.parse_pat_ident(BindByValue(MutMutable)); } else if self.eat_keyword(keywords::Ref) { // parse ref pat let mutbl = self.parse_mutability(); pat = self.parse_pat_ident(BindByRef(mutbl)); } else if self.eat_keyword(keywords::Box) { // `box PAT` // // FIXME(#13910): Rename to `PatBox` and extend to full DST // support. let sub = self.parse_pat(); pat = PatBox(sub); hi = self.last_span.hi; return P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: mk_sp(lo, hi) }) } else { let can_be_enum_or_struct = self.look_ahead(1, |t| { match *t { token::OpenDelim(_) | token::Lt | token::ModSep => true, _ => false, } }); if self.look_ahead(1, |t| *t == token::DotDotDot) && self.look_ahead(2, |t| { *t != token::Comma && *t != token::CloseDelim(token::Bracket) }) { let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP); self.eat(&token::DotDotDot); let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP); pat = PatRange(start, end); } else if self.token.is_plain_ident() && !can_be_enum_or_struct { let id = self.parse_ident(); let id_span = self.last_span; let pth1 = codemap::Spanned{span:id_span, node: id}; if self.eat(&token::Not) { // macro invocation let delim = self.expect_open_delim(); let tts = self.parse_seq_to_end(&token::CloseDelim(delim), seq_sep_none(), |p| p.parse_token_tree()); let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT); pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span}); } else { let sub = if self.eat(&token::At) { // parse foo @ pat Some(self.parse_pat()) } else { // or just foo None }; pat = PatIdent(BindByValue(MutImmutable), pth1, sub); } } else { // parse an enum pat let enum_path = self.parse_path(LifetimeAndTypesWithColons) .path; match self.token { token::OpenDelim(token::Brace) => { self.bump(); let (fields, etc) = self.parse_pat_fields(); self.bump(); pat = PatStruct(enum_path, fields, etc); } _ => { let mut args: Vec<P<Pat>> = Vec::new(); match self.token { token::OpenDelim(token::Paren) => { let is_dotdot = self.look_ahead(1, |t| { match *t { token::DotDot => true, _ => false, } }); if is_dotdot { // This is a "top constructor only" pat self.bump(); self.bump(); self.expect(&token::CloseDelim(token::Paren)); pat = PatEnum(enum_path, None); } else { args = self.parse_enum_variant_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| p.parse_pat() ); pat = PatEnum(enum_path, Some(args)); } }, _ => { if !enum_path.global && enum_path.segments.len() == 1 && enum_path.segments[0].parameters.is_empty() { // it could still be either an enum // or an identifier pattern, resolve // will sort it out: pat = PatIdent(BindByValue(MutImmutable), codemap::Spanned{ span: enum_path.span, node: enum_path.segments[0] .identifier}, None); } else { pat = PatEnum(enum_path, Some(args)); } } } } } } } hi = self.last_span.hi; P(ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: mk_sp(lo, hi), }) } /// Parse ident or ident @ pat /// used by the copy foo and ref foo patterns to give a good /// error message when parsing mistakes like ref foo(a,b) fn parse_pat_ident(&mut self, binding_mode: ast::BindingMode) -> ast::Pat_ { if !self.token.is_plain_ident() { let span = self.span; let tok_str = self.this_token_to_string(); self.span_fatal(span, format!("expected identifier, found `{}`", tok_str).as_slice()); } let ident = self.parse_ident(); let last_span = self.last_span; let name = codemap::Spanned{span: last_span, node: ident}; let sub = if self.eat(&token::At) { Some(self.parse_pat()) } else { None }; // just to be friendly, if they write something like // ref Some(i) // we end up here with ( as the current token. This shortly // leads to a parse error. Note that if there is no explicit // binding mode then we do not end up here, because the lookahead // will direct us over to parse_enum_variant() if self.token == token::OpenDelim(token::Paren) { let last_span = self.last_span; self.span_fatal( last_span, "expected identifier, found enum pattern"); } PatIdent(binding_mode, name, sub) } /// Parse a local variable declaration fn parse_local(&mut self) -> P<Local> { let lo = self.span.lo; let pat = self.parse_pat(); let mut ty = P(Ty { id: ast::DUMMY_NODE_ID, node: TyInfer, span: mk_sp(lo, lo), }); if self.eat(&token::Colon) { ty = self.parse_ty(true); } let init = self.parse_initializer(); P(ast::Local { ty: ty, pat: pat, init: init, id: ast::DUMMY_NODE_ID, span: mk_sp(lo, self.last_span.hi), source: LocalLet, }) } /// Parse a "let" stmt fn parse_let(&mut self) -> P<Decl> { let lo = self.span.lo; let local = self.parse_local(); P(spanned(lo, self.last_span.hi, DeclLocal(local))) } /// Parse a structure field fn parse_name_and_ty(&mut self, pr: Visibility, attrs: Vec<Attribute> ) -> StructField { let lo = self.span.lo; if !self.token.is_plain_ident() { self.fatal("expected ident"); } let name = self.parse_ident(); self.expect(&token::Colon); let ty = self.parse_ty(true); spanned(lo, self.last_span.hi, ast::StructField_ { kind: NamedField(name, pr), id: ast::DUMMY_NODE_ID, ty: ty, attrs: attrs, }) } /// Get an expected item after attributes error message. fn expected_item_err(attrs: &[Attribute]) -> &'static str { match attrs.last() { Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => { "expected item after doc comment" } _ => "expected item after attributes", } } /// Parse a statement. may include decl. /// Precondition: any attributes are parsed already pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> { maybe_whole!(self, NtStmt); fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) { // If we have attributes then we should have an item if !attrs.is_empty() { let last_span = p.last_span; p.span_err(last_span, Parser::expected_item_err(attrs)); } } let lo = self.span.lo; if self.token.is_keyword(keywords::Let) { check_expected_item(self, item_attrs.as_slice()); self.expect_keyword(keywords::Let); let decl = self.parse_let(); P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))) } else if self.token.is_ident() && !self.token.is_any_keyword() && self.look_ahead(1, |t| *t == token::Not) { // it's a macro invocation: check_expected_item(self, item_attrs.as_slice()); // Potential trouble: if we allow macros with paths instead of // idents, we'd need to look ahead past the whole path here... let pth = self.parse_path(NoTypesAllowed).path; self.bump(); let id = match self.token { token::OpenDelim(_) => token::special_idents::invalid, // no special identifier _ => self.parse_ident(), }; // check that we're pointing at delimiters (need to check // again after the `if`, because of `parse_ident` // consuming more tokens). let delim = match self.token { token::OpenDelim(delim) => delim, _ => { // we only expect an ident if we didn't parse one // above. let ident_str = if id.name == token::special_idents::invalid.name { "identifier, " } else { "" }; let tok_str = self.this_token_to_string(); self.fatal(format!("expected {}`(` or `{{`, found `{}`", ident_str, tok_str).as_slice()) }, }; let tts = self.parse_unspanned_seq( &token::OpenDelim(delim), &token::CloseDelim(delim), seq_sep_none(), |p| p.parse_token_tree() ); let hi = self.span.hi; if id.name == token::special_idents::invalid.name { if self.token == token::Dot { let span = self.span; let token_string = self.this_token_to_string(); self.span_err(span, format!("expected statement, found `{}`", token_string).as_slice()); let mac_span = mk_sp(lo, hi); self.span_help(mac_span, "try parenthesizing this macro invocation"); self.abort_if_errors(); } P(spanned(lo, hi, StmtMac( spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false))) } else { // if it has a special ident, it's definitely an item P(spanned(lo, hi, StmtDecl( P(spanned(lo, hi, DeclItem( self.mk_item( lo, hi, id /*id is good here*/, ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))), Inherited, Vec::new(/*no attrs*/))))), ast::DUMMY_NODE_ID))) } } else { let found_attrs = !item_attrs.is_empty(); let item_err = Parser::expected_item_err(item_attrs.as_slice()); match self.parse_item_or_view_item(item_attrs, false) { IoviItem(i) => { let hi = i.span.hi; let decl = P(spanned(lo, hi, DeclItem(i))); P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))) } IoviViewItem(vi) => { self.span_fatal(vi.span, "view items must be declared at the top of the block"); } IoviForeignItem(_) => { self.fatal("foreign items are not allowed here"); } IoviNone(_) => { if found_attrs { let last_span = self.last_span; self.span_err(last_span, item_err); } // Remainder are line-expr stmts. let e = self.parse_expr_res(RESTRICTION_STMT_EXPR); P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID))) } } } } /// Is this expression a successfully-parsed statement? fn expr_is_complete(&mut self, e: &Expr) -> bool { self.restrictions.contains(RESTRICTION_STMT_EXPR) && !classify::expr_requires_semi_to_be_stmt(e) } /// Parse a block. No inner attrs are allowed. pub fn parse_block(&mut self) -> P<Block> { maybe_whole!(no_clone self, NtBlock); let lo = self.span.lo; if !self.eat(&token::OpenDelim(token::Brace)) { let sp = self.span; let tok = self.this_token_to_string(); self.span_fatal_help(sp, format!("expected `{{`, found `{}`", tok).as_slice(), "place this code inside a block"); } return self.parse_block_tail_(lo, DefaultBlock, Vec::new()); } /// Parse a block. Inner attrs are allowed. fn parse_inner_attrs_and_block(&mut self) -> (Vec<Attribute> , P<Block>) { maybe_whole!(pair_empty self, NtBlock); let lo = self.span.lo; self.expect(&token::OpenDelim(token::Brace)); let (inner, next) = self.parse_inner_attrs_and_next(); (inner, self.parse_block_tail_(lo, DefaultBlock, next)) } /// Precondition: already parsed the '{' or '#{' /// I guess that also means "already parsed the 'impure'" if /// necessary, and this should take a qualifier. /// Some blocks start with "#{"... fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> { self.parse_block_tail_(lo, s, Vec::new()) } /// Parse the rest of a block expression or function body fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode, first_item_attrs: Vec<Attribute> ) -> P<Block> { let mut stmts = Vec::new(); let mut expr = None; // wouldn't it be more uniform to parse view items only, here? let ParsedItemsAndViewItems { attrs_remaining, view_items, items, .. } = self.parse_items_and_view_items(first_item_attrs, false, false); for item in items.into_iter() { let span = item.span; let decl = P(spanned(span.lo, span.hi, DeclItem(item))); stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))); } let mut attributes_box = attrs_remaining; while self.token != token::CloseDelim(token::Brace) { // parsing items even when they're not allowed lets us give // better error messages and recover more gracefully. attributes_box.push_all(self.parse_outer_attributes().as_slice()); match self.token { token::Semi => { if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, Parser::expected_item_err(attributes_box.as_slice())); attributes_box = Vec::new(); } self.bump(); // empty } token::CloseDelim(token::Brace) => { // fall through and out. } _ => { let stmt = self.parse_stmt(attributes_box); attributes_box = Vec::new(); stmt.and_then(|Spanned {node, span}| match node { StmtExpr(e, stmt_id) => { // expression without semicolon if classify::expr_requires_semi_to_be_stmt(&*e) { // Just check for errors and recover; do not eat semicolon yet. self.commit_stmt(&[], &[token::Semi, token::CloseDelim(token::Brace)]); } match self.token { token::Semi => { self.bump(); let span_with_semi = Span { lo: span.lo, hi: self.last_span.hi, expn_id: span.expn_id, }; stmts.push(P(Spanned { node: StmtSemi(e, stmt_id), span: span_with_semi, })); } token::CloseDelim(token::Brace) => { expr = Some(e); } _ => { stmts.push(P(Spanned { node: StmtExpr(e, stmt_id), span: span })); } } } StmtMac(m, semi) => { // statement macro; might be an expr match self.token { token::Semi => { stmts.push(P(Spanned { node: StmtMac(m, true), span: span, })); self.bump(); } token::CloseDelim(token::Brace) => { // if a block ends in `m!(arg)` without // a `;`, it must be an expr expr = Some( self.mk_mac_expr(span.lo, span.hi, m.node)); } _ => { stmts.push(P(Spanned { node: StmtMac(m, semi), span: span })); } } } _ => { // all other kinds of statements: if classify::stmt_ends_with_semi(&node) { self.commit_stmt_expecting(token::Semi); } stmts.push(P(Spanned { node: node, span: span })); } }) } } } if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, Parser::expected_item_err(attributes_box.as_slice())); } let hi = self.span.hi; self.bump(); P(ast::Block { view_items: view_items, stmts: stmts, expr: expr, id: ast::DUMMY_NODE_ID, rules: s, span: mk_sp(lo, hi), }) } // Parses a sequence of bounds if a `:` is found, // otherwise returns empty list. fn parse_colon_then_ty_param_bounds(&mut self) -> OwnedSlice<TyParamBound> { if !self.eat(&token::Colon) { OwnedSlice::empty() } else { self.parse_ty_param_bounds() } } // matches bounds = ( boundseq )? // where boundseq = ( polybound + boundseq ) | polybound // and polybound = ( 'for' '<' 'region '>' )? bound // and bound = 'region | trait_ref // NB: The None/Some distinction is important for issue #7264. fn parse_ty_param_bounds(&mut self) -> OwnedSlice<TyParamBound> { let mut result = vec!(); loop { match self.token { token::Lifetime(lifetime) => { result.push(RegionTyParamBound(ast::Lifetime { id: ast::DUMMY_NODE_ID, span: self.span, name: lifetime.name })); self.bump(); } token::ModSep | token::Ident(..) => { let poly_trait_ref = self.parse_poly_trait_ref(); result.push(TraitTyParamBound(poly_trait_ref)) } _ => break, } if !self.eat(&token::BinOp(token::Plus)) { break; } } return OwnedSlice::from_vec(result); } fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef { let segment = ast::PathSegment { identifier: ident, parameters: ast::PathParameters::none() }; let path = ast::Path { span: span, global: false, segments: vec![segment], }; ast::TraitRef { path: path, ref_id: ast::DUMMY_NODE_ID, } } /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )? fn parse_ty_param(&mut self) -> TyParam { // This is a bit hacky. Currently we are only interested in a single // unbound, and it may only be `Sized`. To avoid backtracking and other // complications, we parse an ident, then check for `?`. If we find it, // we use the ident as the unbound, otherwise, we use it as the name of // type param. let mut span = self.span; let mut ident = self.parse_ident(); let mut unbound = None; if self.eat(&token::Question) { let tref = Parser::trait_ref_from_ident(ident, span); unbound = Some(tref); span = self.span; ident = self.parse_ident(); } let bounds = self.parse_colon_then_ty_param_bounds(); let default = if self.token == token::Eq { self.bump(); Some(self.parse_ty(true)) } else { None }; TyParam { ident: ident, id: ast::DUMMY_NODE_ID, bounds: bounds, unbound: unbound, default: default, span: span, } } /// Parse a set of optional generic type parameter declarations. Where /// clauses are not parsed here, and must be added later via /// `parse_where_clause()`. /// /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > ) /// | ( < lifetimes , typaramseq ( , )? > ) /// where typaramseq = ( typaram ) | ( typaram , typaramseq ) pub fn parse_generics(&mut self) -> ast::Generics { if self.eat(&token::Lt) { let lifetime_defs = self.parse_lifetime_defs(); let mut seen_default = false; let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| { p.forbid_lifetime(); let ty_param = p.parse_ty_param(); if ty_param.default.is_some() { seen_default = true; } else if seen_default { let last_span = p.last_span; p.span_err(last_span, "type parameters with a default must be trailing"); } ty_param }); ast::Generics { lifetimes: lifetime_defs, ty_params: ty_params, where_clause: WhereClause { id: ast::DUMMY_NODE_ID, predicates: Vec::new(), } } } else { ast_util::empty_generics() } } fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) { let lifetimes = self.parse_lifetimes(token::Comma); let result = self.parse_seq_to_gt( Some(token::Comma), |p| { p.forbid_lifetime(); p.parse_ty(true) } ); (lifetimes, result.into_vec()) } fn forbid_lifetime(&mut self) { if self.token.is_lifetime() { let span = self.span; self.span_fatal(span, "lifetime parameters must be declared \ prior to type parameters"); } } /// Parses an optional `where` clause and places it in `generics`. fn parse_where_clause(&mut self, generics: &mut ast::Generics) { if !self.eat_keyword(keywords::Where) { return } let mut parsed_something = false; loop { let lo = self.span.lo; let ident = match self.token { token::Ident(..) => self.parse_ident(), _ => break, }; self.expect(&token::Colon); let bounds = self.parse_ty_param_bounds(); let hi = self.span.hi; let span = mk_sp(lo, hi); if bounds.len() == 0 { self.span_err(span, "each predicate in a `where` clause must have \ at least one bound in it"); } generics.where_clause.predicates.push(ast::WherePredicate { id: ast::DUMMY_NODE_ID, span: span, ident: ident, bounds: bounds, }); parsed_something = true; if !self.eat(&token::Comma) { break } } if !parsed_something { let last_span = self.last_span; self.span_err(last_span, "a `where` clause must have at least one predicate \ in it"); } } fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool) -> (Vec<Arg> , bool) { let sp = self.span; let mut args: Vec<Option<Arg>> = self.parse_unspanned_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| { if p.token == token::DotDotDot { p.bump(); if allow_variadic { if p.token != token::CloseDelim(token::Paren) { let span = p.span; p.span_fatal(span, "`...` must be last in argument list for variadic function"); } } else { let span = p.span; p.span_fatal(span, "only foreign functions are allowed to be variadic"); } None } else { Some(p.parse_arg_general(named_args)) } } ); let variadic = match args.pop() { Some(None) => true, Some(x) => { // Need to put back that last arg args.push(x); false } None => false }; if variadic && args.is_empty() { self.span_err(sp, "variadic function must be declared with at least one named argument"); } let args = args.into_iter().map(|x| x.unwrap()).collect(); (args, variadic) } /// Parse the argument list and result type of a function declaration pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> { let (args, variadic) = self.parse_fn_args(true, allow_variadic); let ret_ty = self.parse_ret_ty(); P(FnDecl { inputs: args, output: ret_ty, variadic: variadic }) } fn is_self_ident(&mut self) -> bool { match self.token { token::Ident(id, token::Plain) => id.name == special_idents::self_.name, _ => false } } fn expect_self_ident(&mut self) -> ast::Ident { match self.token { token::Ident(id, token::Plain) if id.name == special_idents::self_.name => { self.bump(); id }, _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected `self`, found `{}`", token_str).as_slice()) } } } /// Parse the argument list and result type of a function /// that may have a self type. fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg) -> (ExplicitSelf, P<FnDecl>) { fn maybe_parse_borrowed_explicit_self(this: &mut Parser) -> ast::ExplicitSelf_ { // The following things are possible to see here: // // fn(&mut self) // fn(&mut self) // fn(&'lt self) // fn(&'lt mut self) // // We already know that the current token is `&`. if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) { this.bump(); SelfRegion(None, MutImmutable, this.expect_self_ident()) } else if this.look_ahead(1, |t| t.is_mutability()) && this.look_ahead(2, |t| t.is_keyword(keywords::Self)) { this.bump(); let mutability = this.parse_mutability(); SelfRegion(None, mutability, this.expect_self_ident()) } else if this.look_ahead(1, |t| t.is_lifetime()) && this.look_ahead(2, |t| t.is_keyword(keywords::Self)) { this.bump(); let lifetime = this.parse_lifetime(); SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident()) } else if this.look_ahead(1, |t| t.is_lifetime()) && this.look_ahead(2, |t| t.is_mutability()) && this.look_ahead(3, |t| t.is_keyword(keywords::Self)) { this.bump(); let lifetime = this.parse_lifetime(); let mutability = this.parse_mutability(); SelfRegion(Some(lifetime), mutability, this.expect_self_ident()) } else { SelfStatic } } self.expect(&token::OpenDelim(token::Paren)); // A bit of complexity and lookahead is needed here in order to be // backwards compatible. let lo = self.span.lo; let mut self_ident_lo = self.span.lo; let mut self_ident_hi = self.span.hi; let mut mutbl_self = MutImmutable; let explicit_self = match self.token { token::BinOp(token::And) => { let eself = maybe_parse_borrowed_explicit_self(self); self_ident_lo = self.last_span.lo; self_ident_hi = self.last_span.hi; eself } token::Tilde => { // We need to make sure it isn't a type if self.look_ahead(1, |t| t.is_keyword(keywords::Self)) { self.bump(); drop(self.expect_self_ident()); let last_span = self.last_span; self.obsolete(last_span, ObsoleteOwnedSelf) } SelfStatic } token::BinOp(token::Star) => { // Possibly "*self" or "*mut self" -- not supported. Try to avoid // emitting cryptic "unexpected token" errors. self.bump(); let _mutability = if self.token.is_mutability() { self.parse_mutability() } else { MutImmutable }; if self.is_self_ident() { let span = self.span; self.span_err(span, "cannot pass self by unsafe pointer"); self.bump(); } // error case, making bogus self ident: SelfValue(special_idents::self_) } token::Ident(..) => { if self.is_self_ident() { let self_ident = self.expect_self_ident(); // Determine whether this is the fully explicit form, `self: // TYPE`. if self.eat(&token::Colon) { SelfExplicit(self.parse_ty(false), self_ident) } else { SelfValue(self_ident) } } else if self.token.is_mutability() && self.look_ahead(1, |t| t.is_keyword(keywords::Self)) { mutbl_self = self.parse_mutability(); let self_ident = self.expect_self_ident(); // Determine whether this is the fully explicit form, // `self: TYPE`. if self.eat(&token::Colon) { SelfExplicit(self.parse_ty(false), self_ident) } else { SelfValue(self_ident) } } else if self.token.is_mutability() && self.look_ahead(1, |t| *t == token::Tilde) && self.look_ahead(2, |t| t.is_keyword(keywords::Self)) { mutbl_self = self.parse_mutability(); self.bump(); drop(self.expect_self_ident()); let last_span = self.last_span; self.obsolete(last_span, ObsoleteOwnedSelf); SelfStatic } else { SelfStatic } } _ => SelfStatic, }; let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi); // shared fall-through for the three cases below. borrowing prevents simply // writing this as a closure macro_rules! parse_remaining_arguments { ($self_id:ident) => { // If we parsed a self type, expect a comma before the argument list. match self.token { token::Comma => { self.bump(); let sep = seq_sep_trailing_allowed(token::Comma); let mut fn_inputs = self.parse_seq_to_before_end( &token::CloseDelim(token::Paren), sep, parse_arg_fn ); fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id)); fn_inputs } token::CloseDelim(token::Paren) => { vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id)) } _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected `,` or `)`, found `{}`", token_str).as_slice()) } } } } let fn_inputs = match explicit_self { SelfStatic => { let sep = seq_sep_trailing_allowed(token::Comma); self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn) } SelfValue(id) => parse_remaining_arguments!(id), SelfRegion(_,_,id) => parse_remaining_arguments!(id), SelfExplicit(_,id) => parse_remaining_arguments!(id), }; self.expect(&token::CloseDelim(token::Paren)); let hi = self.span.hi; let ret_ty = self.parse_ret_ty(); let fn_decl = P(FnDecl { inputs: fn_inputs, output: ret_ty, variadic: false }); (spanned(lo, hi, explicit_self), fn_decl) } // parse the |arg, arg| header on a lambda fn parse_fn_block_decl(&mut self) -> (P<FnDecl>, Option<UnboxedClosureKind>) { let (optional_unboxed_closure_kind, inputs_captures) = { if self.eat(&token::OrOr) { (None, Vec::new()) } else { self.expect(&token::BinOp(token::Or)); let optional_unboxed_closure_kind = self.parse_optional_unboxed_closure_kind(); let args = self.parse_seq_to_before_end( &token::BinOp(token::Or), seq_sep_trailing_allowed(token::Comma), |p| p.parse_fn_block_arg() ); self.bump(); (optional_unboxed_closure_kind, args) } }; let output = if self.token == token::RArrow { self.parse_ret_ty() } else { Return(P(Ty { id: ast::DUMMY_NODE_ID, node: TyInfer, span: self.span, })) }; (P(FnDecl { inputs: inputs_captures, output: output, variadic: false }), optional_unboxed_closure_kind) } /// Parses the `(arg, arg) -> return_type` header on a procedure. fn parse_proc_decl(&mut self) -> P<FnDecl> { let inputs = self.parse_unspanned_seq(&token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| p.parse_fn_block_arg()); let output = if self.token == token::RArrow { self.parse_ret_ty() } else { Return(P(Ty { id: ast::DUMMY_NODE_ID, node: TyInfer, span: self.span, })) }; P(FnDecl { inputs: inputs, output: output, variadic: false }) } /// Parse the name and optional generic types of a function header. fn parse_fn_header(&mut self) -> (Ident, ast::Generics) { let id = self.parse_ident(); let generics = self.parse_generics(); (id, generics) } fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident, node: Item_, vis: Visibility, attrs: Vec<Attribute>) -> P<Item> { P(Item { ident: ident, attrs: attrs, id: ast::DUMMY_NODE_ID, node: node, vis: vis, span: mk_sp(lo, hi) }) } /// Parse an item-position function declaration. fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo { let (ident, mut generics) = self.parse_fn_header(); let decl = self.parse_fn_decl(false); self.parse_where_clause(&mut generics); let (inner_attrs, body) = self.parse_inner_attrs_and_block(); (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs)) } /// Parse a method in a trait impl pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> { let attrs = self.parse_outer_attributes(); let visa = self.parse_visibility(); self.parse_method(attrs, visa) } /// Parse a method in a trait impl, starting with `attrs` attributes. pub fn parse_method(&mut self, attrs: Vec<Attribute>, visa: Visibility) -> P<Method> { let lo = self.span.lo; // code copied from parse_macro_use_or_failure... abstraction! let (method_, hi, new_attrs) = { if !self.token.is_any_keyword() && self.look_ahead(1, |t| *t == token::Not) && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren)) || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) { // method macro. let pth = self.parse_path(NoTypesAllowed).path; self.expect(&token::Not); // eat a matched-delimiter token tree: let delim = self.expect_open_delim(); let tts = self.parse_seq_to_end(&token::CloseDelim(delim), seq_sep_none(), |p| p.parse_token_tree()); let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT); let m: ast::Mac = codemap::Spanned { node: m_, span: mk_sp(self.span.lo, self.span.hi) }; (ast::MethMac(m), self.span.hi, attrs) } else { let abi = if self.eat_keyword(keywords::Extern) { self.parse_opt_abi().unwrap_or(abi::C) } else { abi::Rust }; let fn_style = self.parse_fn_style(); let ident = self.parse_ident(); let mut generics = self.parse_generics(); let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| { p.parse_arg() }); self.parse_where_clause(&mut generics); let (inner_attrs, body) = self.parse_inner_attrs_and_block(); let body_span = body.span; let mut new_attrs = attrs; new_attrs.push_all(inner_attrs.as_slice()); (ast::MethDecl(ident, generics, abi, explicit_self, fn_style, decl, body, visa), body_span.hi, new_attrs) } }; P(ast::Method { attrs: new_attrs, id: ast::DUMMY_NODE_ID, span: mk_sp(lo, hi), node: method_, }) } /// Parse trait Foo { ... } fn parse_item_trait(&mut self) -> ItemInfo { let ident = self.parse_ident(); let mut tps = self.parse_generics(); let sized = self.parse_for_sized(); // Parse supertrait bounds. let bounds = self.parse_colon_then_ty_param_bounds(); self.parse_where_clause(&mut tps); let meths = self.parse_trait_items(); (ident, ItemTrait(tps, sized, bounds, meths), None) } fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) { let mut impl_items = Vec::new(); self.expect(&token::OpenDelim(token::Brace)); let (inner_attrs, mut method_attrs) = self.parse_inner_attrs_and_next(); while !self.eat(&token::CloseDelim(token::Brace)) { method_attrs.extend(self.parse_outer_attributes().into_iter()); let vis = self.parse_visibility(); if self.eat_keyword(keywords::Type) { impl_items.push(TypeImplItem(P(self.parse_typedef( method_attrs, vis)))) } else { impl_items.push(MethodImplItem(self.parse_method( method_attrs, vis))); } method_attrs = self.parse_outer_attributes(); } (impl_items, inner_attrs) } /// Parses two variants (with the region/type params always optional): /// impl<T> Foo { ... } /// impl<T> ToString for ~[T] { ... } fn parse_item_impl(&mut self) -> ItemInfo { // First, parse type parameters if necessary. let mut generics = self.parse_generics(); // Special case: if the next identifier that follows is '(', don't // allow this to be parsed as a trait. let could_be_trait = self.token != token::OpenDelim(token::Paren); // Parse the trait. let mut ty = self.parse_ty(true); // Parse traits, if necessary. let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) { // New-style trait. Reinterpret the type as a trait. let opt_trait_ref = match ty.node { TyPath(ref path, None, node_id) => { Some(TraitRef { path: (*path).clone(), ref_id: node_id, }) } TyPath(_, Some(_), _) => { self.span_err(ty.span, "bounded traits are only valid in type position"); None } _ => { self.span_err(ty.span, "not a trait"); None } }; ty = self.parse_ty(true); opt_trait_ref } else { None }; self.parse_where_clause(&mut generics); let (impl_items, attrs) = self.parse_impl_items(); let ident = ast_util::impl_pretty_name(&opt_trait, &*ty); (ident, ItemImpl(generics, opt_trait, ty, impl_items), Some(attrs)) } /// Parse a::B<String,int> fn parse_trait_ref(&mut self) -> TraitRef { ast::TraitRef { path: self.parse_path(LifetimeAndTypesWithoutColons).path, ref_id: ast::DUMMY_NODE_ID, } } fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> { if self.eat_keyword(keywords::For) { self.expect(&token::Lt); let lifetime_defs = self.parse_lifetime_defs(); self.expect_gt(); lifetime_defs } else { Vec::new() } } /// Parse for<'l> a::B<String,int> fn parse_poly_trait_ref(&mut self) -> PolyTraitRef { let lifetime_defs = self.parse_late_bound_lifetime_defs(); ast::PolyTraitRef { bound_lifetimes: lifetime_defs, trait_ref: self.parse_trait_ref() } } /// Parse struct Foo { ... } fn parse_item_struct(&mut self) -> ItemInfo { let class_name = self.parse_ident(); let mut generics = self.parse_generics(); if self.eat(&token::Colon) { let ty = self.parse_ty(true); self.span_err(ty.span, "`virtual` structs have been removed from the language"); } self.parse_where_clause(&mut generics); let mut fields: Vec<StructField>; let is_tuple_like; if self.eat(&token::OpenDelim(token::Brace)) { // It's a record-like struct. is_tuple_like = false; fields = Vec::new(); while self.token != token::CloseDelim(token::Brace) { fields.push(self.parse_struct_decl_field(true)); } if fields.len() == 0 { self.fatal(format!("unit-like struct definition should be \ written as `struct {};`", token::get_ident(class_name)).as_slice()); } self.bump(); } else if self.token == token::OpenDelim(token::Paren) { // It's a tuple-like struct. is_tuple_like = true; fields = self.parse_unspanned_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| { let attrs = p.parse_outer_attributes(); let lo = p.span.lo; let struct_field_ = ast::StructField_ { kind: UnnamedField(p.parse_visibility()), id: ast::DUMMY_NODE_ID, ty: p.parse_ty(true), attrs: attrs, }; spanned(lo, p.span.hi, struct_field_) }); if fields.len() == 0 { self.fatal(format!("unit-like struct definition should be \ written as `struct {};`", token::get_ident(class_name)).as_slice()); } self.expect(&token::Semi); } else if self.eat(&token::Semi) { // It's a unit-like struct. is_tuple_like = true; fields = Vec::new(); } else { let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, `(`, or `;` after struct \ name, found `{}`", "{", token_str).as_slice()) } let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug. let new_id = ast::DUMMY_NODE_ID; (class_name, ItemStruct(P(ast::StructDef { fields: fields, ctor_id: if is_tuple_like { Some(new_id) } else { None }, }), generics), None) } /// Parse a structure field declaration pub fn parse_single_struct_field(&mut self, vis: Visibility, attrs: Vec<Attribute> ) -> StructField { let a_var = self.parse_name_and_ty(vis, attrs); match self.token { token::Comma => { self.bump(); } token::CloseDelim(token::Brace) => {} _ => { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal_help(span, format!("expected `,`, or `}}`, found `{}`", token_str).as_slice(), "struct fields should be separated by commas") } } a_var } /// Parse an element of a struct definition fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField { let attrs = self.parse_outer_attributes(); if self.eat_keyword(keywords::Pub) { if !allow_pub { let span = self.last_span; self.span_err(span, "`pub` is not allowed here"); } return self.parse_single_struct_field(Public, attrs); } return self.parse_single_struct_field(Inherited, attrs); } /// Parse visibility: PUB, PRIV, or nothing fn parse_visibility(&mut self) -> Visibility { if self.eat_keyword(keywords::Pub) { Public } else { Inherited } } fn parse_for_sized(&mut self) -> Option<ast::TraitRef> { if self.eat_keyword(keywords::For) { let span = self.span; let ident = self.parse_ident(); if !self.eat(&token::Question) { self.span_err(span, "expected 'Sized?' after `for` in trait item"); return None; } let tref = Parser::trait_ref_from_ident(ident, span); Some(tref) } else { None } } /// Given a termination token and a vector of already-parsed /// attributes (of length 0 or 1), parse all of the items in a module fn parse_mod_items(&mut self, term: token::Token, first_item_attrs: Vec<Attribute>, inner_lo: BytePos) -> Mod { // parse all of the items up to closing or an attribute. // view items are legal here. let ParsedItemsAndViewItems { attrs_remaining, view_items, items: starting_items, .. } = self.parse_items_and_view_items(first_item_attrs, true, true); let mut items: Vec<P<Item>> = starting_items; let attrs_remaining_len = attrs_remaining.len(); // don't think this other loop is even necessary.... let mut first = true; while self.token != term { let mut attrs = self.parse_outer_attributes(); if first { let mut tmp = attrs_remaining.clone(); tmp.push_all(attrs.as_slice()); attrs = tmp; first = false; } debug!("parse_mod_items: parse_item_or_view_item(attrs={})", attrs); match self.parse_item_or_view_item(attrs, true /* macros allowed */) { IoviItem(item) => items.push(item), IoviViewItem(view_item) => { self.span_fatal(view_item.span, "view items must be declared at the top of \ the module"); } _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected item, found `{}`", token_str).as_slice()) } } } if first && attrs_remaining_len > 0u { // We parsed attributes for the first item but didn't find it let last_span = self.last_span; self.span_err(last_span, Parser::expected_item_err(attrs_remaining.as_slice())); } ast::Mod { inner: mk_sp(inner_lo, self.span.lo), view_items: view_items, items: items } } fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo { let id = self.parse_ident(); self.expect(&token::Colon); let ty = self.parse_ty(true); self.expect(&token::Eq); let e = self.parse_expr(); self.commit_expr_expecting(&*e, token::Semi); let item = match m { Some(m) => ItemStatic(ty, m, e), None => ItemConst(ty, e), }; (id, item, None) } /// Parse a `mod <foo> { ... }` or `mod <foo>;` item fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo { let id_span = self.span; let id = self.parse_ident(); if self.token == token::Semi { self.bump(); // This mod is in an external file. Let's go get it! let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span); (id, m, Some(attrs)) } else { self.push_mod_path(id, outer_attrs); self.expect(&token::OpenDelim(token::Brace)); let mod_inner_lo = self.span.lo; let old_owns_directory = self.owns_directory; self.owns_directory = true; let (inner, next) = self.parse_inner_attrs_and_next(); let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo); self.expect(&token::CloseDelim(token::Brace)); self.owns_directory = old_owns_directory; self.pop_mod_path(); (id, ItemMod(m), Some(inner)) } } fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) { let default_path = self.id_to_interned_str(id); let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") { Some(d) => d, None => default_path, }; self.mod_path_stack.push(file_path) } fn pop_mod_path(&mut self) { self.mod_path_stack.pop().unwrap(); } /// Read a module from a source file. fn eval_src_mod(&mut self, id: ast::Ident, outer_attrs: &[ast::Attribute], id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) { let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span)); prefix.pop(); let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice()); let dir_path = prefix.join(&mod_path); let mod_string = token::get_ident(id); let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name( outer_attrs, "path") { Some(d) => (dir_path.join(d), true), None => { let mod_name = mod_string.get().to_string(); let default_path_str = format!("{}.rs", mod_name); let secondary_path_str = format!("{}/mod.rs", mod_name); let default_path = dir_path.join(default_path_str.as_slice()); let secondary_path = dir_path.join(secondary_path_str.as_slice()); let default_exists = default_path.exists(); let secondary_exists = secondary_path.exists(); if !self.owns_directory { self.span_err(id_sp, "cannot declare a new module at this location"); let this_module = match self.mod_path_stack.last() { Some(name) => name.get().to_string(), None => self.root_module_name.as_ref().unwrap().clone(), }; self.span_note(id_sp, format!("maybe move this module `{0}` \ to its own directory via \ `{0}/mod.rs`", this_module).as_slice()); if default_exists || secondary_exists { self.span_note(id_sp, format!("... or maybe `use` the module \ `{}` instead of possibly \ redeclaring it", mod_name).as_slice()); } self.abort_if_errors(); } match (default_exists, secondary_exists) { (true, false) => (default_path, false), (false, true) => (secondary_path, true), (false, false) => { self.span_fatal_help(id_sp, format!("file not found for module `{}`", mod_name).as_slice(), format!("name the file either {} or {} inside \ the directory {}", default_path_str, secondary_path_str, dir_path.display()).as_slice()); } (true, true) => { self.span_fatal_help( id_sp, format!("file for module `{}` found at both {} \ and {}", mod_name, default_path_str, secondary_path_str).as_slice(), "delete or rename one of them to remove the ambiguity"); } } } }; self.eval_src_mod_from_path(file_path, owns_directory, mod_string.get().to_string(), id_sp) } fn eval_src_mod_from_path(&mut self, path: Path, owns_directory: bool, name: String, id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) { let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut(); match included_mod_stack.iter().position(|p| *p == path) { Some(i) => { let mut err = String::from_str("circular modules: "); let len = included_mod_stack.len(); for p in included_mod_stack.slice(i, len).iter() { err.push_str(p.display().as_maybe_owned().as_slice()); err.push_str(" -> "); } err.push_str(path.display().as_maybe_owned().as_slice()); self.span_fatal(id_sp, err.as_slice()); } None => () } included_mod_stack.push(path.clone()); drop(included_mod_stack); let mut p0 = new_sub_parser_from_file(self.sess, self.cfg.clone(), &path, owns_directory, Some(name), id_sp); let mod_inner_lo = p0.span.lo; let (mod_attrs, next) = p0.parse_inner_attrs_and_next(); let first_item_outer_attrs = next; let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo); self.sess.included_mod_stack.borrow_mut().pop(); return (ast::ItemMod(m0), mod_attrs); } /// Parse a function declaration from a foreign module fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, attrs: Vec<Attribute>) -> P<ForeignItem> { let lo = self.span.lo; self.expect_keyword(keywords::Fn); let (ident, mut generics) = self.parse_fn_header(); let decl = self.parse_fn_decl(true); self.parse_where_clause(&mut generics); let hi = self.span.hi; self.expect(&token::Semi); P(ast::ForeignItem { ident: ident, attrs: attrs, node: ForeignItemFn(decl, generics), id: ast::DUMMY_NODE_ID, span: mk_sp(lo, hi), vis: vis }) } /// Parse a static item from a foreign module fn parse_item_foreign_static(&mut self, vis: ast::Visibility, attrs: Vec<Attribute>) -> P<ForeignItem> { let lo = self.span.lo; self.expect_keyword(keywords::Static); let mutbl = self.eat_keyword(keywords::Mut); let ident = self.parse_ident(); self.expect(&token::Colon); let ty = self.parse_ty(true); let hi = self.span.hi; self.expect(&token::Semi); P(ForeignItem { ident: ident, attrs: attrs, node: ForeignItemStatic(ty, mutbl), id: ast::DUMMY_NODE_ID, span: mk_sp(lo, hi), vis: vis }) } /// Parse safe/unsafe and fn fn parse_fn_style(&mut self) -> FnStyle { if self.eat_keyword(keywords::Fn) { NormalFn } else if self.eat_keyword(keywords::Unsafe) { self.expect_keyword(keywords::Fn); UnsafeFn } else { self.unexpected(); } } /// At this point, this is essentially a wrapper for /// parse_foreign_items. fn parse_foreign_mod_items(&mut self, abi: abi::Abi, first_item_attrs: Vec<Attribute> ) -> ForeignMod { let ParsedItemsAndViewItems { attrs_remaining, view_items, items: _, foreign_items, } = self.parse_foreign_items(first_item_attrs, true); if !attrs_remaining.is_empty() { let last_span = self.last_span; self.span_err(last_span, Parser::expected_item_err(attrs_remaining.as_slice())); } assert!(self.token == token::CloseDelim(token::Brace)); ast::ForeignMod { abi: abi, view_items: view_items, items: foreign_items } } /// Parse extern crate links /// /// # Example /// /// extern crate url; /// extern crate foo = "bar"; //deprecated /// extern crate "bar" as foo; fn parse_item_extern_crate(&mut self, lo: BytePos, visibility: Visibility, attrs: Vec<Attribute> ) -> ItemOrViewItem { let span = self.span; let (maybe_path, ident) = match self.token { token::Ident(..) => { let the_ident = self.parse_ident(); let path = if self.eat(&token::Eq) { let path = self.parse_str(); let span = self.span; self.obsolete(span, ObsoleteExternCrateRenaming); Some(path) } else if self.eat_keyword(keywords::As) { // skip the ident if there is one if self.token.is_ident() { self.bump(); } self.span_err(span, "expected `;`, found `as`"); self.span_help(span, format!("perhaps you meant to enclose the crate name `{}` in \ a string?", the_ident.as_str()).as_slice()); None } else { None }; self.expect(&token::Semi); (path, the_ident) }, token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => { let sp = self.span; self.expect_no_suffix(sp, "extern crate name", suf); // forgo the internal suffix check of `parse_str` to // avoid repeats (this unwrap will always succeed due // to the restriction of the `match`) let (s, style, _) = self.parse_optional_str().unwrap(); self.expect_keyword(keywords::As); let the_ident = self.parse_ident(); self.expect(&token::Semi); (Some((s, style)), the_ident) }, _ => { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal(span, format!("expected extern crate name but \ found `{}`", token_str).as_slice()); } }; IoviViewItem(ast::ViewItem { node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID), attrs: attrs, vis: visibility, span: mk_sp(lo, self.last_span.hi) }) } /// Parse `extern` for foreign ABIs /// modules. /// /// `extern` is expected to have been /// consumed before calling this method /// /// # Examples: /// /// extern "C" {} /// extern {} fn parse_item_foreign_mod(&mut self, lo: BytePos, opt_abi: Option<abi::Abi>, visibility: Visibility, attrs: Vec<Attribute> ) -> ItemOrViewItem { self.expect(&token::OpenDelim(token::Brace)); let abi = opt_abi.unwrap_or(abi::C); let (inner, next) = self.parse_inner_attrs_and_next(); let m = self.parse_foreign_mod_items(abi, next); self.expect(&token::CloseDelim(token::Brace)); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, special_idents::invalid, ItemForeignMod(m), visibility, maybe_append(attrs, Some(inner))); return IoviItem(item); } /// Parse type Foo = Bar; fn parse_item_type(&mut self) -> ItemInfo { let ident = self.parse_ident(); let mut tps = self.parse_generics(); self.parse_where_clause(&mut tps); self.expect(&token::Eq); let ty = self.parse_ty(true); self.expect(&token::Semi); (ident, ItemTy(ty, tps), None) } /// Parse a structure-like enum variant definition /// this should probably be renamed or refactored... fn parse_struct_def(&mut self) -> P<StructDef> { let mut fields: Vec<StructField> = Vec::new(); while self.token != token::CloseDelim(token::Brace) { fields.push(self.parse_struct_decl_field(false)); } self.bump(); P(StructDef { fields: fields, ctor_id: None, }) } /// Parse the part of an "enum" decl following the '{' fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef { let mut variants = Vec::new(); let mut all_nullary = true; let mut any_disr = None; while self.token != token::CloseDelim(token::Brace) { let variant_attrs = self.parse_outer_attributes(); let vlo = self.span.lo; let vis = self.parse_visibility(); let ident; let kind; let mut args = Vec::new(); let mut disr_expr = None; ident = self.parse_ident(); if self.eat(&token::OpenDelim(token::Brace)) { // Parse a struct variant. all_nullary = false; let start_span = self.span; let struct_def = self.parse_struct_def(); if struct_def.fields.len() == 0 { self.span_err(start_span, format!("unit-like struct variant should be written \ without braces, as `{},`", token::get_ident(ident)).as_slice()); } kind = StructVariantKind(struct_def); } else if self.token == token::OpenDelim(token::Paren) { all_nullary = false; let arg_tys = self.parse_enum_variant_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| p.parse_ty(true) ); for ty in arg_tys.into_iter() { args.push(ast::VariantArg { ty: ty, id: ast::DUMMY_NODE_ID, }); } kind = TupleVariantKind(args); } else if self.eat(&token::Eq) { disr_expr = Some(self.parse_expr()); any_disr = disr_expr.as_ref().map(|expr| expr.span); kind = TupleVariantKind(args); } else { kind = TupleVariantKind(Vec::new()); } let vr = ast::Variant_ { name: ident, attrs: variant_attrs, kind: kind, id: ast::DUMMY_NODE_ID, disr_expr: disr_expr, vis: vis, }; variants.push(P(spanned(vlo, self.last_span.hi, vr))); if !self.eat(&token::Comma) { break; } } self.expect(&token::CloseDelim(token::Brace)); match any_disr { Some(disr_span) if !all_nullary => self.span_err(disr_span, "discriminator values can only be used with a c-like enum"), _ => () } ast::EnumDef { variants: variants } } /// Parse an "enum" declaration fn parse_item_enum(&mut self) -> ItemInfo { let id = self.parse_ident(); let mut generics = self.parse_generics(); self.parse_where_clause(&mut generics); self.expect(&token::OpenDelim(token::Brace)); let enum_definition = self.parse_enum_def(&generics); (id, ItemEnum(enum_definition, generics), None) } fn fn_expr_lookahead(tok: &token::Token) -> bool { match *tok { token::OpenDelim(token::Paren) | token::At | token::Tilde | token::BinOp(_) => true, _ => false } } /// Parses a string as an ABI spec on an extern type or module. Consumes /// the `extern` keyword, if one is found. fn parse_opt_abi(&mut self) -> Option<abi::Abi> { match self.token { token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => { let sp = self.span; self.expect_no_suffix(sp, "ABI spec", suf); self.bump(); let the_string = s.as_str(); match abi::lookup(the_string) { Some(abi) => Some(abi), None => { let last_span = self.last_span; self.span_err( last_span, format!("illegal ABI: expected one of [{}], \ found `{}`", abi::all_names().connect(", "), the_string).as_slice()); None } } } _ => None, } } /// Parse one of the items or view items allowed by the /// flags; on failure, return IoviNone. /// NB: this function no longer parses the items inside an /// extern crate. fn parse_item_or_view_item(&mut self, attrs: Vec<Attribute> , macros_allowed: bool) -> ItemOrViewItem { let nt_item = match self.token { token::Interpolated(token::NtItem(ref item)) => { Some((**item).clone()) } _ => None }; match nt_item { Some(mut item) => { self.bump(); let mut attrs = attrs; mem::swap(&mut item.attrs, &mut attrs); item.attrs.extend(attrs.into_iter()); return IoviItem(P(item)); } None => {} } let lo = self.span.lo; let visibility = self.parse_visibility(); // must be a view item: if self.eat_keyword(keywords::Use) { // USE ITEM (IoviViewItem) let view_item = self.parse_use(); self.expect(&token::Semi); return IoviViewItem(ast::ViewItem { node: view_item, attrs: attrs, vis: visibility, span: mk_sp(lo, self.last_span.hi) }); } // either a view item or an item: if self.eat_keyword(keywords::Extern) { let next_is_mod = self.eat_keyword(keywords::Mod); if next_is_mod || self.eat_keyword(keywords::Crate) { if next_is_mod { let last_span = self.last_span; self.span_err(mk_sp(lo, last_span.hi), format!("`extern mod` is obsolete, use \ `extern crate` instead \ to refer to external \ crates.").as_slice()) } return self.parse_item_extern_crate(lo, visibility, attrs); } let opt_abi = self.parse_opt_abi(); if self.eat_keyword(keywords::Fn) { // EXTERN FUNCTION ITEM let abi = opt_abi.unwrap_or(abi::C); let (ident, item_, extra_attrs) = self.parse_item_fn(NormalFn, abi); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } else if self.token == token::OpenDelim(token::Brace) { return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs); } let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal(span, format!("expected `{}` or `fn`, found `{}`", "{", token_str).as_slice()); } if self.eat_keyword(keywords::Virtual) { let span = self.span; self.span_err(span, "`virtual` structs have been removed from the language"); } // the rest are all guaranteed to be items: if self.token.is_keyword(keywords::Static) { // STATIC ITEM self.bump(); let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable}; let (ident, item_, extra_attrs) = self.parse_item_const(Some(m)); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.token.is_keyword(keywords::Const) { // CONST ITEM self.bump(); if self.eat_keyword(keywords::Mut) { let last_span = self.last_span; self.span_err(last_span, "const globals cannot be mutable"); self.span_help(last_span, "did you mean to declare a static?"); } let (ident, item_, extra_attrs) = self.parse_item_const(None); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.token.is_keyword(keywords::Fn) && self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) { // FUNCTION ITEM self.bump(); let (ident, item_, extra_attrs) = self.parse_item_fn(NormalFn, abi::Rust); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.token.is_keyword(keywords::Unsafe) && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) { // UNSAFE FUNCTION ITEM self.bump(); let abi = if self.eat_keyword(keywords::Extern) { self.parse_opt_abi().unwrap_or(abi::C) } else { abi::Rust }; self.expect_keyword(keywords::Fn); let (ident, item_, extra_attrs) = self.parse_item_fn(UnsafeFn, abi); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.eat_keyword(keywords::Mod) { // MODULE ITEM let (ident, item_, extra_attrs) = self.parse_item_mod(attrs.as_slice()); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.eat_keyword(keywords::Type) { // TYPE ITEM let (ident, item_, extra_attrs) = self.parse_item_type(); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.eat_keyword(keywords::Enum) { // ENUM ITEM let (ident, item_, extra_attrs) = self.parse_item_enum(); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.eat_keyword(keywords::Trait) { // TRAIT ITEM let (ident, item_, extra_attrs) = self.parse_item_trait(); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.eat_keyword(keywords::Impl) { // IMPL ITEM let (ident, item_, extra_attrs) = self.parse_item_impl(); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } if self.eat_keyword(keywords::Struct) { // STRUCT ITEM let (ident, item_, extra_attrs) = self.parse_item_struct(); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs)); return IoviItem(item); } self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility) } /// Parse a foreign item; on failure, return IoviNone. fn parse_foreign_item(&mut self, attrs: Vec<Attribute> , macros_allowed: bool) -> ItemOrViewItem { maybe_whole!(iovi self, NtItem); let lo = self.span.lo; let visibility = self.parse_visibility(); if self.token.is_keyword(keywords::Static) { // FOREIGN STATIC ITEM let item = self.parse_item_foreign_static(visibility, attrs); return IoviForeignItem(item); } if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) { // FOREIGN FUNCTION ITEM let item = self.parse_item_foreign_fn(visibility, attrs); return IoviForeignItem(item); } self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility) } /// This is the fall-through for parsing items. fn parse_macro_use_or_failure( &mut self, attrs: Vec<Attribute> , macros_allowed: bool, lo: BytePos, visibility: Visibility ) -> ItemOrViewItem { if macros_allowed && !self.token.is_any_keyword() && self.look_ahead(1, |t| *t == token::Not) && (self.look_ahead(2, |t| t.is_plain_ident()) || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren)) || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) { // MACRO INVOCATION ITEM // item macro. let pth = self.parse_path(NoTypesAllowed).path; self.expect(&token::Not); // a 'special' identifier (like what `macro_rules!` uses) // is optional. We should eventually unify invoc syntax // and remove this. let id = if self.token.is_plain_ident() { self.parse_ident() } else { token::special_idents::invalid // no special identifier }; // eat a matched-delimiter token tree: let delim = self.expect_open_delim(); let tts = self.parse_seq_to_end(&token::CloseDelim(delim), seq_sep_none(), |p| p.parse_token_tree()); // single-variant-enum... : let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT); let m: ast::Mac = codemap::Spanned { node: m, span: mk_sp(self.span.lo, self.span.hi) }; let item_ = ItemMac(m); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, id, item_, visibility, attrs); return IoviItem(item); } // FAILURE TO PARSE ITEM match visibility { Inherited => {} Public => { let last_span = self.last_span; self.span_fatal(last_span, "unmatched visibility `pub`"); } } return IoviNone(attrs); } pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> { let attrs = self.parse_outer_attributes(); self.parse_item(attrs) } pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> { match self.parse_item_or_view_item(attrs, true) { IoviNone(_) => None, IoviViewItem(_) => self.fatal("view items are not allowed here"), IoviForeignItem(_) => self.fatal("foreign items are not allowed here"), IoviItem(item) => Some(item) } } /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo` pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem { match self.parse_item_or_view_item(attrs, false) { IoviViewItem(vi) => vi, _ => self.fatal("expected `use` or `extern crate`"), } } /// Parse, e.g., "use a::b::{z,y}" fn parse_use(&mut self) -> ViewItem_ { return ViewItemUse(self.parse_view_path()); } /// Matches view_path : MOD? IDENT EQ non_global_path /// | MOD? non_global_path MOD_SEP LBRACE RBRACE /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE /// | MOD? non_global_path MOD_SEP STAR /// | MOD? non_global_path fn parse_view_path(&mut self) -> P<ViewPath> { let lo = self.span.lo; if self.token == token::OpenDelim(token::Brace) { // use {foo,bar} let idents = self.parse_unspanned_seq( &token::OpenDelim(token::Brace), &token::CloseDelim(token::Brace), seq_sep_trailing_allowed(token::Comma), |p| p.parse_path_list_item()); let path = ast::Path { span: mk_sp(lo, self.span.hi), global: false, segments: Vec::new() }; return P(spanned(lo, self.span.hi, ViewPathList(path, idents, ast::DUMMY_NODE_ID))); } let first_ident = self.parse_ident(); let mut path = vec!(first_ident); match self.token { token::Eq => { // x = foo::bar self.bump(); let path_lo = self.span.lo; path = vec!(self.parse_ident()); while self.token == token::ModSep { self.bump(); let id = self.parse_ident(); path.push(id); } let span = mk_sp(path_lo, self.span.hi); self.obsolete(span, ObsoleteImportRenaming); let path = ast::Path { span: span, global: false, segments: path.into_iter().map(|identifier| { ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), } }).collect() }; return P(spanned(lo, self.span.hi, ViewPathSimple(first_ident, path, ast::DUMMY_NODE_ID))); } token::ModSep => { // foo::bar or foo::{a,b,c} or foo::* while self.token == token::ModSep { self.bump(); match self.token { token::Ident(i, _) => { self.bump(); path.push(i); } // foo::bar::{a,b,c} token::OpenDelim(token::Brace) => { let idents = self.parse_unspanned_seq( &token::OpenDelim(token::Brace), &token::CloseDelim(token::Brace), seq_sep_trailing_allowed(token::Comma), |p| p.parse_path_list_item() ); let path = ast::Path { span: mk_sp(lo, self.span.hi), global: false, segments: path.into_iter().map(|identifier| { ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), } }).collect() }; return P(spanned(lo, self.span.hi, ViewPathList(path, idents, ast::DUMMY_NODE_ID))); } // foo::bar::* token::BinOp(token::Star) => { self.bump(); let path = ast::Path { span: mk_sp(lo, self.span.hi), global: false, segments: path.into_iter().map(|identifier| { ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), } }).collect() }; return P(spanned(lo, self.span.hi, ViewPathGlob(path, ast::DUMMY_NODE_ID))); } _ => break } } } _ => () } let mut rename_to = path[path.len() - 1u]; let path = ast::Path { span: mk_sp(lo, self.span.hi), global: false, segments: path.into_iter().map(|identifier| { ast::PathSegment { identifier: identifier, parameters: ast::PathParameters::none(), } }).collect() }; if self.eat_keyword(keywords::As) { rename_to = self.parse_ident() } P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID))) } /// Parses a sequence of items. Stops when it finds program /// text that can't be parsed as an item /// - mod_items uses extern_mod_allowed = true /// - block_tail_ uses extern_mod_allowed = false fn parse_items_and_view_items(&mut self, first_item_attrs: Vec<Attribute> , mut extern_mod_allowed: bool, macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; attrs.push_all(self.parse_outer_attributes().as_slice()); // First, parse view items. let mut view_items : Vec<ast::ViewItem> = Vec::new(); let mut items = Vec::new(); // I think this code would probably read better as a single // loop with a mutable three-state-variable (for extern crates, // view items, and regular items) ... except that because // of macros, I'd like to delay that entire check until later. loop { match self.parse_item_or_view_item(attrs, macros_allowed) { IoviNone(attrs) => { return ParsedItemsAndViewItems { attrs_remaining: attrs, view_items: view_items, items: items, foreign_items: Vec::new() } } IoviViewItem(view_item) => { match view_item.node { ViewItemUse(..) => { // `extern crate` must precede `use`. extern_mod_allowed = false; } ViewItemExternCrate(..) if !extern_mod_allowed => { self.span_err(view_item.span, "\"extern crate\" declarations are \ not allowed here"); } ViewItemExternCrate(..) => {} } view_items.push(view_item); } IoviItem(item) => { items.push(item); attrs = self.parse_outer_attributes(); break; } IoviForeignItem(_) => { panic!(); } } attrs = self.parse_outer_attributes(); } // Next, parse items. loop { match self.parse_item_or_view_item(attrs, macros_allowed) { IoviNone(returned_attrs) => { attrs = returned_attrs; break } IoviViewItem(view_item) => { attrs = self.parse_outer_attributes(); self.span_err(view_item.span, "`use` and `extern crate` declarations must precede items"); } IoviItem(item) => { attrs = self.parse_outer_attributes(); items.push(item) } IoviForeignItem(_) => { panic!(); } } } ParsedItemsAndViewItems { attrs_remaining: attrs, view_items: view_items, items: items, foreign_items: Vec::new() } } /// Parses a sequence of foreign items. Stops when it finds program /// text that can't be parsed as an item fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> , macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; attrs.push_all(self.parse_outer_attributes().as_slice()); let mut foreign_items = Vec::new(); loop { match self.parse_foreign_item(attrs, macros_allowed) { IoviNone(returned_attrs) => { if self.token == token::CloseDelim(token::Brace) { attrs = returned_attrs; break } self.unexpected(); }, IoviViewItem(view_item) => { // I think this can't occur: self.span_err(view_item.span, "`use` and `extern crate` declarations must precede items"); } IoviItem(item) => { // FIXME #5668: this will occur for a macro invocation: self.span_fatal(item.span, "macros cannot expand to foreign items"); } IoviForeignItem(foreign_item) => { foreign_items.push(foreign_item); } } attrs = self.parse_outer_attributes(); } ParsedItemsAndViewItems { attrs_remaining: attrs, view_items: Vec::new(), items: Vec::new(), foreign_items: foreign_items } } /// Parses a source module as a crate. This is the main /// entry point for the parser. pub fn parse_crate_mod(&mut self) -> Crate { let lo = self.span.lo; // parse the crate's inner attrs, maybe (oops) one // of the attrs of an item: let (inner, next) = self.parse_inner_attrs_and_next(); let first_item_outer_attrs = next; // parse the items inside the crate: let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo); ast::Crate { module: m, attrs: inner, config: self.cfg.clone(), span: mk_sp(lo, self.span.lo), exported_macros: Vec::new(), } } pub fn parse_optional_str(&mut self) -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> { let ret = match self.token { token::Literal(token::Str_(s), suf) => { (self.id_to_interned_str(s.ident()), ast::CookedStr, suf) } token::Literal(token::StrRaw(s, n), suf) => { (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf) } _ => return None }; self.bump(); Some(ret) } pub fn parse_str(&mut self) -> (InternedString, StrStyle) { match self.parse_optional_str() { Some((s, style, suf)) => { let sp = self.last_span; self.expect_no_suffix(sp, "str literal", suf); (s, style) } _ => self.fatal("expected string literal") } } }<|fim▁end|>
}
<|file_name|>load-resolve-path.js<|end_file_name|><|fim▁begin|>'use strict' module.exports = function (config) { if (!process.env.COOKING_PATH) { return } const rootPath = process.env.COOKING_PATH.split(',') config.resolve = config.resolve || {} config.resolveLoader = config.resolveLoader || {}<|fim▁hole|> config.resolve.modules = (config.resolve.root || []).concat(rootPath) config.resolveLoader.modules = (config.resolveLoader.root || []).concat(rootPath) }<|fim▁end|>
<|file_name|>vec.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 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 std::iter::{FromIterator, repeat}; use std::mem::size_of; use std::vec::as_vec; use test::Bencher; struct DropCounter<'a> { count: &'a mut u32 } impl<'a> Drop for DropCounter<'a> { fn drop(&mut self) { *self.count += 1; } } #[test] fn test_as_vec() { let xs = [1u8, 2u8, 3u8]; assert_eq!(&**as_vec(&xs), xs); } #[test] fn test_as_vec_dtor() { let (mut count_x, mut count_y) = (0, 0); { let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }]; assert_eq!(as_vec(xs).len(), 2); } assert_eq!(count_x, 1); assert_eq!(count_y, 1); } #[test] fn test_small_vec_struct() { assert!(size_of::<Vec<u8>>() == size_of::<usize>() * 3); } #[test] fn test_double_drop() { struct TwoVec<T> { x: Vec<T>, y: Vec<T> } let (mut count_x, mut count_y) = (0, 0); { let mut tv = TwoVec { x: Vec::new(), y: Vec::new() }; tv.x.push(DropCounter {count: &mut count_x}); tv.y.push(DropCounter {count: &mut count_y}); // If Vec had a drop flag, here is where it would be zeroed. // Instead, it should rely on its internal state to prevent // doing anything significant when dropped multiple times. drop(tv.x); // Here tv goes out of scope, tv.y should be dropped, but not tv.x. } assert_eq!(count_x, 1); assert_eq!(count_y, 1); } #[test] fn test_reserve() { let mut v = Vec::new(); assert_eq!(v.capacity(), 0); v.reserve(2); assert!(v.capacity() >= 2); for i in 0..16 { v.push(i); } assert!(v.capacity() >= 16); v.reserve(16); assert!(v.capacity() >= 32); v.push(16); v.reserve(16); assert!(v.capacity() >= 33) } #[test] fn test_extend() { let mut v = Vec::new(); let mut w = Vec::new(); v.extend(0..3); for i in 0..3 { w.push(i) } assert_eq!(v, w); v.extend(3..10); for i in 3..10 { w.push(i) } assert_eq!(v, w); } #[test] fn test_slice_from_mut() { let mut values = vec![1, 2, 3, 4, 5]; { let slice = &mut values[2 ..]; assert!(slice == [3, 4, 5]); for p in slice { *p += 2; } } assert!(values == [1, 2, 5, 6, 7]); } #[test] fn test_slice_to_mut() { let mut values = vec![1, 2, 3, 4, 5]; { let slice = &mut values[.. 2]; assert!(slice == [1, 2]); for p in slice { *p += 1; } } assert!(values == [2, 3, 3, 4, 5]); } #[test] fn test_split_at_mut() { let mut values = vec![1, 2, 3, 4, 5]; { let (left, right) = values.split_at_mut(2); { let left: &[_] = left; assert!(&left[..left.len()] == &[1, 2]); } for p in left { *p += 1; } { let right: &[_] = right; assert!(&right[..right.len()] == &[3, 4, 5]); } for p in right { *p += 2; } } assert_eq!(values, [2, 3, 5, 6, 7]); } #[test] fn test_clone() { let v: Vec<i32> = vec![]; let w = vec!(1, 2, 3); assert_eq!(v, v.clone()); let z = w.clone(); assert_eq!(w, z); // they should be disjoint in memory. assert!(w.as_ptr() != z.as_ptr()) } #[test] fn test_clone_from() { let mut v = vec!(); let three: Vec<Box<_>> = vec!(box 1, box 2, box 3); let two: Vec<Box<_>> = vec!(box 4, box 5); // zero, long v.clone_from(&three); assert_eq!(v, three); // equal v.clone_from(&three); assert_eq!(v, three); // long, short v.clone_from(&two); assert_eq!(v, two); // short, long v.clone_from(&three); assert_eq!(v, three) } #[test] fn test_retain() { let mut vec = vec![1, 2, 3, 4]; vec.retain(|&x| x % 2 == 0); assert_eq!(vec, [2, 4]); } #[test] fn zero_sized_values() { let mut v = Vec::new(); assert_eq!(v.len(), 0); v.push(()); assert_eq!(v.len(), 1); v.push(()); assert_eq!(v.len(), 2); assert_eq!(v.pop(), Some(())); assert_eq!(v.pop(), Some(())); assert_eq!(v.pop(), None); assert_eq!(v.iter().count(), 0); v.push(()); assert_eq!(v.iter().count(), 1); v.push(()); assert_eq!(v.iter().count(), 2); for &() in &v {} assert_eq!(v.iter_mut().count(), 2); v.push(()); assert_eq!(v.iter_mut().count(), 3); v.push(()); assert_eq!(v.iter_mut().count(), 4); for &mut () in &mut v {} unsafe { v.set_len(0); } assert_eq!(v.iter_mut().count(), 0); } #[test] fn test_partition() { assert_eq!(vec![].into_iter().partition(|x: &i32| *x < 3), (vec![], vec![])); assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 4), (vec![1, 2, 3], vec![])); assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 2), (vec![1], vec![2, 3])); assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 0), (vec![], vec![1, 2, 3])); } #[test] fn test_zip_unzip() { let z1 = vec![(1, 4), (2, 5), (3, 6)]; let (left, right): (Vec<_>, Vec<_>) = z1.iter().cloned().unzip(); assert_eq!((1, 4), (left[0], right[0])); assert_eq!((2, 5), (left[1], right[1])); assert_eq!((3, 6), (left[2], right[2])); } #[test] fn test_unsafe_ptrs() { unsafe { // Test on-stack copy-from-buf. let a = [1, 2, 3]; let ptr = a.as_ptr(); let b = Vec::from_raw_buf(ptr, 3); assert_eq!(b, [1, 2, 3]); // Test on-heap copy-from-buf. let c = vec![1, 2, 3, 4, 5]; let ptr = c.as_ptr(); let d = Vec::from_raw_buf(ptr, 5); assert_eq!(d, [1, 2, 3, 4, 5]); } } #[test] fn test_vec_truncate_drop() { static mut drops: u32 = 0; struct Elem(i32); impl Drop for Elem { fn drop(&mut self) { unsafe { drops += 1; } } } let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)]; assert_eq!(unsafe { drops }, 0); v.truncate(3); assert_eq!(unsafe { drops }, 2); v.truncate(0); assert_eq!(unsafe { drops }, 5); } #[test] #[should_panic] fn test_vec_truncate_fail() { struct BadElem(i32); impl Drop for BadElem { fn drop(&mut self) { let BadElem(ref mut x) = *self; if *x == 0xbadbeef { panic!("BadElem panic: 0xbadbeef") } } } let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)]; v.truncate(0); } #[test] fn test_index() { let vec = vec![1, 2, 3]; assert!(vec[1] == 2); } #[test] #[should_panic] fn test_index_out_of_bounds() { let vec = vec![1, 2, 3]; let _ = vec[3]; } #[test] #[should_panic] fn test_slice_out_of_bounds_1() { let x = vec![1, 2, 3, 4, 5]; &x[-1..]; } #[test] #[should_panic] fn test_slice_out_of_bounds_2() { let x = vec![1, 2, 3, 4, 5]; &x[..6]; } #[test] #[should_panic] fn test_slice_out_of_bounds_3() { let x = vec![1, 2, 3, 4, 5]; &x[-1..4]; } #[test] #[should_panic] fn test_slice_out_of_bounds_4() { let x = vec![1, 2, 3, 4, 5]; &x[1..6]; } #[test] #[should_panic] fn test_slice_out_of_bounds_5() { let x = vec![1, 2, 3, 4, 5]; &x[3..2]; } #[test] #[should_panic] fn test_swap_remove_empty() { let mut vec= Vec::<i32>::new(); vec.swap_remove(0); } #[test] fn test_move_iter_unwrap() { let mut vec = Vec::with_capacity(7); vec.push(1); vec.push(2); let ptr = vec.as_ptr(); vec = vec.into_iter().into_inner(); assert_eq!(vec.as_ptr(), ptr); assert_eq!(vec.capacity(), 7); assert_eq!(vec.len(), 0); } #[test] #[should_panic] fn test_map_in_place_incompatible_types_fail() { let v = vec![0, 1, 2]; v.map_in_place(|_| ()); } #[test] fn test_map_in_place() { let v = vec![0, 1, 2]; assert_eq!(v.map_in_place(|i: u32| i as i32 - 1), [-1, 0, 1]); } #[test] fn test_map_in_place_zero_sized() { let v = vec![(), ()]; #[derive(PartialEq, Debug)] struct ZeroSized; assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]); } #[test] fn test_map_in_place_zero_drop_count() { use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; #[derive(Clone, PartialEq, Debug)] struct Nothing; impl Drop for Nothing { fn drop(&mut self) { } } #[derive(Clone, PartialEq, Debug)] struct ZeroSized; impl Drop for ZeroSized { fn drop(&mut self) { DROP_COUNTER.fetch_add(1, Ordering::Relaxed); } } const NUM_ELEMENTS: usize = 2; static DROP_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>(); DROP_COUNTER.store(0, Ordering::Relaxed); let v = v.map_in_place(|_| ZeroSized); assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0); drop(v); assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS); } #[test] fn test_move_items() { let vec = vec![1, 2, 3]; let mut vec2 = vec![]; for i in vec { vec2.push(i); } assert_eq!(vec2, [1, 2, 3]); } #[test] fn test_move_items_reverse() { let vec = vec![1, 2, 3]; let mut vec2 = vec![]; for i in vec.into_iter().rev() { vec2.push(i); } assert_eq!(vec2, [3, 2, 1]); } #[test] fn test_move_items_zero_sized() { let vec = vec![(), (), ()]; let mut vec2 = vec![]; for i in vec { vec2.push(i); } assert_eq!(vec2, [(), (), ()]); } #[test] fn test_drain_items() { let mut vec = vec![1, 2, 3]; let mut vec2 = vec![]; for i in vec.drain(..) { vec2.push(i); } assert_eq!(vec, []); assert_eq!(vec2, [ 1, 2, 3 ]); } #[test] fn test_drain_items_reverse() { let mut vec = vec![1, 2, 3]; let mut vec2 = vec![]; for i in vec.drain(..).rev() { vec2.push(i); } assert_eq!(vec, []); assert_eq!(vec2, [3, 2, 1]); } #[test] fn test_drain_items_zero_sized() { let mut vec = vec![(), (), ()]; let mut vec2 = vec![]; for i in vec.drain(..) { vec2.push(i); } assert_eq!(vec, []); assert_eq!(vec2, [(), (), ()]); } #[test] #[should_panic] fn test_drain_out_of_bounds() { let mut v = vec![1, 2, 3, 4, 5]; v.drain(5..6); } #[test] fn test_drain_range() { let mut v = vec![1, 2, 3, 4, 5]; for _ in v.drain(4..) { } assert_eq!(v, &[1, 2, 3, 4]); let mut v: Vec<_> = (1..6).map(|x| x.to_string()).collect(); for _ in v.drain(1..4) { } assert_eq!(v, &[1.to_string(), 5.to_string()]); let mut v: Vec<_> = (1..6).map(|x| x.to_string()).collect(); for _ in v.drain(1..4).rev() { } assert_eq!(v, &[1.to_string(), 5.to_string()]); let mut v: Vec<_> = vec![(); 5]; for _ in v.drain(1..4).rev() { } assert_eq!(v, &[(), ()]); } #[test] fn test_into_boxed_slice() { let xs = vec![1, 2, 3]; let ys = xs.into_boxed_slice(); assert_eq!(&*ys, [1, 2, 3]); } #[test] fn test_append() { let mut vec = vec![1, 2, 3]; let mut vec2 = vec![4, 5, 6]; vec.append(&mut vec2); assert_eq!(vec, [1, 2, 3, 4, 5, 6]); assert_eq!(vec2, []); } #[test] fn test_split_off() { let mut vec = vec![1, 2, 3, 4, 5, 6]; let vec2 = vec.split_off(4); assert_eq!(vec, [1, 2, 3, 4]); assert_eq!(vec2, [5, 6]); } #[test] fn test_into_iter_count() { assert_eq!(vec![1, 2, 3].into_iter().count(), 3); } #[bench] fn bench_new(b: &mut Bencher) { b.iter(|| { let v: Vec<u32> = Vec::new(); assert_eq!(v.len(), 0); assert_eq!(v.capacity(), 0); }) } fn do_bench_with_capacity(b: &mut Bencher, src_len: usize) { b.bytes = src_len as u64; b.iter(|| { let v: Vec<u32> = Vec::with_capacity(src_len); assert_eq!(v.len(), 0); assert_eq!(v.capacity(), src_len); }) } #[bench] fn bench_with_capacity_0000(b: &mut Bencher) { do_bench_with_capacity(b, 0) } #[bench] fn bench_with_capacity_0010(b: &mut Bencher) { do_bench_with_capacity(b, 10) } #[bench] fn bench_with_capacity_0100(b: &mut Bencher) { do_bench_with_capacity(b, 100) } #[bench] fn bench_with_capacity_1000(b: &mut Bencher) { do_bench_with_capacity(b, 1000) } fn do_bench_from_fn(b: &mut Bencher, src_len: usize) { b.bytes = src_len as u64; b.iter(|| { let dst = (0..src_len).collect::<Vec<_>>(); assert_eq!(dst.len(), src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }) } #[bench] fn bench_from_fn_0000(b: &mut Bencher) { do_bench_from_fn(b, 0) } #[bench] fn bench_from_fn_0010(b: &mut Bencher) { do_bench_from_fn(b, 10) } #[bench] fn bench_from_fn_0100(b: &mut Bencher) { do_bench_from_fn(b, 100) } #[bench] fn bench_from_fn_1000(b: &mut Bencher) { do_bench_from_fn(b, 1000) } fn do_bench_from_elem(b: &mut Bencher, src_len: usize) { b.bytes = src_len as u64; b.iter(|| { let dst: Vec<usize> = repeat(5).take(src_len).collect(); assert_eq!(dst.len(), src_len); assert!(dst.iter().all(|x| *x == 5)); }) } #[bench] fn bench_from_elem_0000(b: &mut Bencher) { do_bench_from_elem(b, 0) } #[bench] fn bench_from_elem_0010(b: &mut Bencher) { do_bench_from_elem(b, 10) } #[bench] fn bench_from_elem_0100(b: &mut Bencher) { do_bench_from_elem(b, 100) } #[bench] fn bench_from_elem_1000(b: &mut Bencher) { do_bench_from_elem(b, 1000) } fn do_bench_from_slice(b: &mut Bencher, src_len: usize) { let src: Vec<_> = FromIterator::from_iter(0..src_len); b.bytes = src_len as u64; b.iter(|| { let dst = src.clone()[..].to_vec(); assert_eq!(dst.len(), src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); } #[bench] fn bench_from_slice_0000(b: &mut Bencher) { do_bench_from_slice(b, 0) } #[bench] fn bench_from_slice_0010(b: &mut Bencher) { do_bench_from_slice(b, 10) } #[bench] fn bench_from_slice_0100(b: &mut Bencher) { do_bench_from_slice(b, 100) } #[bench] fn bench_from_slice_1000(b: &mut Bencher) { do_bench_from_slice(b, 1000) } fn do_bench_from_iter(b: &mut Bencher, src_len: usize) { let src: Vec<_> = FromIterator::from_iter(0..src_len); b.bytes = src_len as u64; b.iter(|| { let dst: Vec<_> = FromIterator::from_iter(src.clone().into_iter()); assert_eq!(dst.len(), src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); } #[bench] fn bench_from_iter_0000(b: &mut Bencher) { do_bench_from_iter(b, 0) } #[bench] fn bench_from_iter_0010(b: &mut Bencher) { do_bench_from_iter(b, 10) } #[bench] fn bench_from_iter_0100(b: &mut Bencher) { do_bench_from_iter(b, 100) } #[bench] fn bench_from_iter_1000(b: &mut Bencher) { do_bench_from_iter(b, 1000) } fn do_bench_extend(b: &mut Bencher, dst_len: usize, src_len: usize) { let dst: Vec<_> = FromIterator::from_iter(0..dst_len); let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); b.bytes = src_len as u64; b.iter(|| { let mut dst = dst.clone(); dst.extend(src.clone().into_iter()); assert_eq!(dst.len(), dst_len + src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); } #[bench] fn bench_extend_0000_0000(b: &mut Bencher) { do_bench_extend(b, 0, 0) } #[bench] fn bench_extend_0000_0010(b: &mut Bencher) { do_bench_extend(b, 0, 10) } #[bench] fn bench_extend_0000_0100(b: &mut Bencher) { do_bench_extend(b, 0, 100) } #[bench] fn bench_extend_0000_1000(b: &mut Bencher) { do_bench_extend(b, 0, 1000) } #[bench] fn bench_extend_0010_0010(b: &mut Bencher) { do_bench_extend(b, 10, 10) } #[bench] fn bench_extend_0100_0100(b: &mut Bencher) { do_bench_extend(b, 100, 100) } #[bench] fn bench_extend_1000_1000(b: &mut Bencher) { do_bench_extend(b, 1000, 1000) } fn do_bench_push_all(b: &mut Bencher, dst_len: usize, src_len: usize) { let dst: Vec<_> = FromIterator::from_iter(0..dst_len); let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); b.bytes = src_len as u64; b.iter(|| { let mut dst = dst.clone(); dst.push_all(&src); assert_eq!(dst.len(), dst_len + src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); } #[bench] fn bench_push_all_0000_0000(b: &mut Bencher) { do_bench_push_all(b, 0, 0) } #[bench] fn bench_push_all_0000_0010(b: &mut Bencher) { do_bench_push_all(b, 0, 10) } #[bench] fn bench_push_all_0000_0100(b: &mut Bencher) { do_bench_push_all(b, 0, 100) } #[bench] fn bench_push_all_0000_1000(b: &mut Bencher) { do_bench_push_all(b, 0, 1000) } #[bench] fn bench_push_all_0010_0010(b: &mut Bencher) { do_bench_push_all(b, 10, 10) } #[bench] fn bench_push_all_0100_0100(b: &mut Bencher) { do_bench_push_all(b, 100, 100) } #[bench] fn bench_push_all_1000_1000(b: &mut Bencher) { do_bench_push_all(b, 1000, 1000) } fn do_bench_push_all_move(b: &mut Bencher, dst_len: usize, src_len: usize) { let dst: Vec<_> = FromIterator::from_iter(0..dst_len); let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); b.bytes = src_len as u64; b.iter(|| { let mut dst = dst.clone(); dst.extend(src.clone().into_iter()); assert_eq!(dst.len(), dst_len + src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); } #[bench] fn bench_push_all_move_0000_0000(b: &mut Bencher) { do_bench_push_all_move(b, 0, 0) } #[bench] fn bench_push_all_move_0000_0010(b: &mut Bencher) { do_bench_push_all_move(b, 0, 10) } #[bench] fn bench_push_all_move_0000_0100(b: &mut Bencher) { do_bench_push_all_move(b, 0, 100) } #[bench] fn bench_push_all_move_0000_1000(b: &mut Bencher) { do_bench_push_all_move(b, 0, 1000) } #[bench] fn bench_push_all_move_0010_0010(b: &mut Bencher) { do_bench_push_all_move(b, 10, 10) } #[bench] fn bench_push_all_move_0100_0100(b: &mut Bencher) { do_bench_push_all_move(b, 100, 100) } #[bench] fn bench_push_all_move_1000_1000(b: &mut Bencher) { do_bench_push_all_move(b, 1000, 1000) } fn do_bench_clone(b: &mut Bencher, src_len: usize) { let src: Vec<usize> = FromIterator::from_iter(0..src_len); b.bytes = src_len as u64; b.iter(|| { let dst = src.clone(); assert_eq!(dst.len(), src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); } #[bench] fn bench_clone_0000(b: &mut Bencher) { do_bench_clone(b, 0) } #[bench] fn bench_clone_0010(b: &mut Bencher) { do_bench_clone(b, 10) } #[bench] fn bench_clone_0100(b: &mut Bencher) { do_bench_clone(b, 100) } #[bench] fn bench_clone_1000(b: &mut Bencher) { do_bench_clone(b, 1000) } fn do_bench_clone_from(b: &mut Bencher, times: usize, dst_len: usize, src_len: usize) { let dst: Vec<_> = FromIterator::from_iter(0..src_len); let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); b.bytes = (times * src_len) as u64;<|fim▁hole|> b.iter(|| { let mut dst = dst.clone(); for _ in 0..times { dst.clone_from(&src); assert_eq!(dst.len(), src_len); assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x)); } }); } #[bench] fn bench_clone_from_01_0000_0000(b: &mut Bencher) { do_bench_clone_from(b, 1, 0, 0) } #[bench] fn bench_clone_from_01_0000_0010(b: &mut Bencher) { do_bench_clone_from(b, 1, 0, 10) } #[bench] fn bench_clone_from_01_0000_0100(b: &mut Bencher) { do_bench_clone_from(b, 1, 0, 100) } #[bench] fn bench_clone_from_01_0000_1000(b: &mut Bencher) { do_bench_clone_from(b, 1, 0, 1000) } #[bench] fn bench_clone_from_01_0010_0010(b: &mut Bencher) { do_bench_clone_from(b, 1, 10, 10) } #[bench] fn bench_clone_from_01_0100_0100(b: &mut Bencher) { do_bench_clone_from(b, 1, 100, 100) } #[bench] fn bench_clone_from_01_1000_1000(b: &mut Bencher) { do_bench_clone_from(b, 1, 1000, 1000) } #[bench] fn bench_clone_from_01_0010_0100(b: &mut Bencher) { do_bench_clone_from(b, 1, 10, 100) } #[bench] fn bench_clone_from_01_0100_1000(b: &mut Bencher) { do_bench_clone_from(b, 1, 100, 1000) } #[bench] fn bench_clone_from_01_0010_0000(b: &mut Bencher) { do_bench_clone_from(b, 1, 10, 0) } #[bench] fn bench_clone_from_01_0100_0010(b: &mut Bencher) { do_bench_clone_from(b, 1, 100, 10) } #[bench] fn bench_clone_from_01_1000_0100(b: &mut Bencher) { do_bench_clone_from(b, 1, 1000, 100) } #[bench] fn bench_clone_from_10_0000_0000(b: &mut Bencher) { do_bench_clone_from(b, 10, 0, 0) } #[bench] fn bench_clone_from_10_0000_0010(b: &mut Bencher) { do_bench_clone_from(b, 10, 0, 10) } #[bench] fn bench_clone_from_10_0000_0100(b: &mut Bencher) { do_bench_clone_from(b, 10, 0, 100) } #[bench] fn bench_clone_from_10_0000_1000(b: &mut Bencher) { do_bench_clone_from(b, 10, 0, 1000) } #[bench] fn bench_clone_from_10_0010_0010(b: &mut Bencher) { do_bench_clone_from(b, 10, 10, 10) } #[bench] fn bench_clone_from_10_0100_0100(b: &mut Bencher) { do_bench_clone_from(b, 10, 100, 100) } #[bench] fn bench_clone_from_10_1000_1000(b: &mut Bencher) { do_bench_clone_from(b, 10, 1000, 1000) } #[bench] fn bench_clone_from_10_0010_0100(b: &mut Bencher) { do_bench_clone_from(b, 10, 10, 100) } #[bench] fn bench_clone_from_10_0100_1000(b: &mut Bencher) { do_bench_clone_from(b, 10, 100, 1000) } #[bench] fn bench_clone_from_10_0010_0000(b: &mut Bencher) { do_bench_clone_from(b, 10, 10, 0) } #[bench] fn bench_clone_from_10_0100_0010(b: &mut Bencher) { do_bench_clone_from(b, 10, 100, 10) } #[bench] fn bench_clone_from_10_1000_0100(b: &mut Bencher) { do_bench_clone_from(b, 10, 1000, 100) }<|fim▁end|>
<|file_name|>commandtest.py<|end_file_name|><|fim▁begin|># Copyright (C) 2009 Google Inc. 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 Google Inc. 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 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest from webkitpy.common.system.outputcapture import OutputCapture from webkitpy.tool.mocktool import MockOptions, MockTool<|fim▁hole|> class CommandsTest(unittest.TestCase): def assert_execute_outputs(self, command, args=[], expected_stdout="", expected_stderr="", expected_exception=None, expected_logs=None, options=MockOptions(), tool=MockTool()): options.blocks = None options.cc = 'MOCK cc' options.component = 'MOCK component' options.confirm = True options.email = 'MOCK email' options.git_commit = 'MOCK git commit' options.obsolete_patches = True options.open_bug = True options.port = 'MOCK port' options.update_changelogs = False options.quiet = True options.reviewer = 'MOCK reviewer' command.bind_to_tool(tool) OutputCapture().assert_outputs(self, command.execute, [options, args, tool], expected_stdout=expected_stdout, expected_stderr=expected_stderr, expected_exception=expected_exception, expected_logs=expected_logs)<|fim▁end|>
<|file_name|>test_nb.py<|end_file_name|><|fim▁begin|><|fim▁hole|>locale = "nb" def test_diff_for_humans(): with pendulum.test(pendulum.datetime(2016, 8, 29)): diff_for_humans() def diff_for_humans(): d = pendulum.now().subtract(seconds=1) assert d.diff_for_humans(locale=locale) == "for 1 sekund siden" d = pendulum.now().subtract(seconds=2) assert d.diff_for_humans(locale=locale) == "for 2 sekunder siden" d = pendulum.now().subtract(minutes=1) assert d.diff_for_humans(locale=locale) == "for 1 minutt siden" d = pendulum.now().subtract(minutes=2) assert d.diff_for_humans(locale=locale) == "for 2 minutter siden" d = pendulum.now().subtract(hours=1) assert d.diff_for_humans(locale=locale) == "for 1 time siden" d = pendulum.now().subtract(hours=2) assert d.diff_for_humans(locale=locale) == "for 2 timer siden" d = pendulum.now().subtract(days=1) assert d.diff_for_humans(locale=locale) == "for 1 dag siden" d = pendulum.now().subtract(days=2) assert d.diff_for_humans(locale=locale) == "for 2 dager siden" d = pendulum.now().subtract(weeks=1) assert d.diff_for_humans(locale=locale) == "for 1 uke siden" d = pendulum.now().subtract(weeks=2) assert d.diff_for_humans(locale=locale) == "for 2 uker siden" d = pendulum.now().subtract(months=1) assert d.diff_for_humans(locale=locale) == "for 1 måned siden" d = pendulum.now().subtract(months=2) assert d.diff_for_humans(locale=locale) == "for 2 måneder siden" d = pendulum.now().subtract(years=1) assert d.diff_for_humans(locale=locale) == "for 1 år siden" d = pendulum.now().subtract(years=2) assert d.diff_for_humans(locale=locale) == "for 2 år siden" d = pendulum.now().add(seconds=1) assert d.diff_for_humans(locale=locale) == "om 1 sekund" d = pendulum.now().add(seconds=1) d2 = pendulum.now() assert d.diff_for_humans(d2, locale=locale) == "1 sekund etter" assert d2.diff_for_humans(d, locale=locale) == "1 sekund før" assert d.diff_for_humans(d2, True, locale=locale) == "1 sekund" assert d2.diff_for_humans(d.add(seconds=1), True, locale=locale) == "2 sekunder" def test_format(): d = pendulum.datetime(2016, 8, 28, 7, 3, 6, 123456) assert d.format("dddd", locale=locale) == "søndag" assert d.format("ddd", locale=locale) == "søn." assert d.format("MMMM", locale=locale) == "august" assert d.format("MMM", locale=locale) == "aug." assert d.format("A", locale=locale) == "a.m." assert d.format("Qo", locale=locale) == "3." assert d.format("Mo", locale=locale) == "8." assert d.format("Do", locale=locale) == "28." assert d.format("LT", locale=locale) == "07:03" assert d.format("LTS", locale=locale) == "07:03:06" assert d.format("L", locale=locale) == "28.08.2016" assert d.format("LL", locale=locale) == "28. august 2016" assert d.format("LLL", locale=locale) == "28. august 2016 07:03" assert d.format("LLLL", locale=locale) == "søndag 28. august 2016 07:03"<|fim▁end|>
import pendulum
<|file_name|>3451.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
print((int((str(179**10))*4))**(1/10))
<|file_name|>issue-5884.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.<|fim▁hole|>// pretty-expanded FIXME #23616 #![feature(box_syntax)] pub struct Foo { a: isize, } struct Bar<'a> { a: Box<Option<isize>>, b: &'a Foo, } fn check(a: Box<Foo>) { let _ic = Bar{ b: &*a, a: box None }; } pub fn main(){}<|fim▁end|>
// compile-pass #![allow(dead_code)]
<|file_name|>HttpFilterCamelHeadersTest.java<|end_file_name|><|fim▁begin|>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jetty; import java.util.Map; <|fim▁hole|>import org.junit.Test; /** * @version */ public class HttpFilterCamelHeadersTest extends BaseJettyTest { @Test public void testFilterCamelHeaders() throws Exception { Exchange out = template.send("http://localhost:{{port}}/test/filter", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Claus"); exchange.getIn().setHeader("bar", 123); } }); assertNotNull(out); assertEquals("Hi Claus", out.getOut().getBody(String.class)); // there should be no internal Camel headers // except for the response code Map<String, Object> headers = out.getOut().getHeaders(); for (String key : headers.keySet()) { if (!key.equalsIgnoreCase(Exchange.HTTP_RESPONSE_CODE)) { assertTrue("Should not contain any Camel internal headers", !key.toLowerCase().startsWith("camel")); } else { assertEquals(200, headers.get(Exchange.HTTP_RESPONSE_CODE)); } } } @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); jndi.bind("foo", new MyFooBean()); return jndi; } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("jetty:http://localhost:{{port}}/test/filter").beanRef("foo"); } }; } public static class MyFooBean { public String hello(String name) { return "Hi " + name; } } }<|fim▁end|>
import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.JndiRegistry;
<|file_name|>mails_resource.py<|end_file_name|><|fim▁begin|># # Copyright (c) 2015 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Pixelated. If not, see <http://www.gnu.org/licenses/>. import time import json from twisted.internet import defer from twisted.logger import Logger from twisted.web.server import NOT_DONE_YET from twisted.web.resource import Resource from twisted.web import server from leap.common import events from pixelated.adapter.model.mail import InputMail from pixelated.resources import respond_json_deferred, BaseResource from pixelated.adapter.services.mail_sender import SMTPDownException from pixelated.support.functional import to_unicode log = Logger() class MailsUnreadResource(Resource): isLeaf = True def __init__(self, mail_service): Resource.__init__(self) self._mail_service = mail_service def render_POST(self, request): idents = json.load(request.content).get('idents') deferreds = [] for ident in idents: deferreds.append(self._mail_service.mark_as_unread(ident)) d = defer.gatherResults(deferreds, consumeErrors=True) d.addCallback(lambda _: respond_json_deferred(None, request)) d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500)) return NOT_DONE_YET class MailsReadResource(Resource): isLeaf = True def __init__(self, mail_service): Resource.__init__(self) self._mail_service = mail_service def render_POST(self, request): idents = json.load(request.content).get('idents') deferreds = [] for ident in idents: deferreds.append(self._mail_service.mark_as_read(ident)) d = defer.gatherResults(deferreds, consumeErrors=True) d.addCallback(lambda _: respond_json_deferred(None, request)) d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500)) return NOT_DONE_YET class MailsDeleteResource(Resource): isLeaf = True def __init__(self, mail_service): Resource.__init__(self) self._mail_service = mail_service def render_POST(self, request): def response_failed(failure): log.error('something failed: %s' % failure.getErrorMessage()) request.finish() idents = json.loads(request.content.read())['idents'] deferreds = [] for ident in idents: deferreds.append(self._mail_service.delete_mail(ident)) d = defer.gatherResults(deferreds, consumeErrors=True) d.addCallback(lambda _: respond_json_deferred(None, request)) d.addErrback(response_failed) return NOT_DONE_YET class MailsRecoverResource(Resource): isLeaf = True def __init__(self, mail_service): Resource.__init__(self) self._mail_service = mail_service def render_POST(self, request): idents = json.loads(request.content.read())['idents'] deferreds = [] for ident in idents: deferreds.append(self._mail_service.recover_mail(ident)) d = defer.gatherResults(deferreds, consumeErrors=True) d.addCallback(lambda _: respond_json_deferred(None, request)) d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500)) return NOT_DONE_YET class MailsArchiveResource(Resource): isLeaf = True def __init__(self, mail_service): Resource.__init__(self) self._mail_service = mail_service def render_POST(self, request): idents = json.loads(request.content.read())['idents'] deferreds = [] for ident in idents: deferreds.append(self._mail_service.archive_mail(ident)) d = defer.gatherResults(deferreds, consumeErrors=True) d.addCallback(lambda _: respond_json_deferred({'successMessage': 'your-message-was-archived'}, request)) d.addErrback(lambda _: respond_json_deferred(None, request, status_code=500))<|fim▁hole|> class MailsResource(BaseResource): def _register_smtp_error_handler(self): def on_error(event, content): delivery_error_mail = InputMail.delivery_error_template(delivery_address=event.content) self._mail_service.mailboxes.inbox.add(delivery_error_mail) events.register(events.catalog.SMTP_SEND_MESSAGE_ERROR, callback=on_error) def __init__(self, services_factory): BaseResource.__init__(self, services_factory) self._register_smtp_error_handler() def getChild(self, action, request): _mail_service = self.mail_service(request) if action == 'delete': return MailsDeleteResource(_mail_service) if action == 'recover': return MailsRecoverResource(_mail_service) if action == 'archive': return MailsArchiveResource(_mail_service) if action == 'read': return MailsReadResource(_mail_service) if action == 'unread': return MailsUnreadResource(_mail_service) def _build_mails_response(self, (mails, total)): return { "stats": { "total": total, }, "mails": [mail.as_dict() for mail in mails] } def render_GET(self, request): _mail_service = self.mail_service(request) query, window_size, page = request.args.get('q')[0], request.args.get('w')[0], request.args.get('p')[0] unicode_query = to_unicode(query) d = _mail_service.mails(unicode_query, window_size, page) d.addCallback(self._build_mails_response) d.addCallback(lambda res: respond_json_deferred(res, request)) def error_handler(error): print error d.addErrback(error_handler) return NOT_DONE_YET def render_POST(self, request): def onError(error): if isinstance(error.value, SMTPDownException): respond_json_deferred({'message': str(error.value)}, request, status_code=503) else: log.error('error occurred while sending: %s' % error.getErrorMessage()) respond_json_deferred({'message': 'an error occurred while sending'}, request, status_code=422) deferred = self._handle_post(request) deferred.addErrback(onError) return server.NOT_DONE_YET def render_PUT(self, request): def onError(error): log.error('error saving draft: %s' % error.getErrorMessage()) respond_json_deferred("", request, status_code=422) deferred = self._handle_put(request) deferred.addErrback(onError) return server.NOT_DONE_YET @defer.inlineCallbacks def _fetch_attachment_contents(self, content_dict, _mail_service): attachments = content_dict.get('attachments', []) if content_dict else [] for attachment in attachments: retrieved_attachment = yield _mail_service.attachment(attachment['ident']) attachment['raw'] = retrieved_attachment['content'] content_dict['attachments'] = attachments defer.returnValue(content_dict) @defer.inlineCallbacks def _handle_post(self, request): _mail_service = self.mail_service(request) content_dict = json.loads(request.content.read()) with_attachment_content = yield self._fetch_attachment_contents(content_dict, _mail_service) sent_mail = yield _mail_service.send_mail(with_attachment_content) respond_json_deferred(sent_mail.as_dict(), request, status_code=201) @defer.inlineCallbacks def _handle_put(self, request): _draft_service = self.draft_service(request) _mail_service = self.mail_service(request) content_dict = json.loads(request.content.read()) with_attachment_content = yield self._fetch_attachment_contents(content_dict, _mail_service) _mail = InputMail.from_dict(with_attachment_content, from_address=_mail_service.account_email) draft_id = content_dict.get('ident') pixelated_mail = yield _draft_service.process_draft(draft_id, _mail) if not pixelated_mail: respond_json_deferred("", request, status_code=422) else: respond_json_deferred({'ident': pixelated_mail.ident}, request)<|fim▁end|>
return NOT_DONE_YET
<|file_name|>state.entity.ts<|end_file_name|><|fim▁begin|>export interface IState{ id:number; name:string; uf:string; } export class StateEntity implements IState{ id:number; name:string; uf:string;<|fim▁hole|> this.name = data.name || null; this.uf = data.ud || null; } } }<|fim▁end|>
constructor(data?:any) { if (data) { this.id = data.id || null;
<|file_name|>genericNodePropertyComponent.tsx<|end_file_name|><|fim▁begin|>import * as React from "react"; import { LineContainerComponent } from '../../sharedComponents/lineContainerComponent'; import { IPropertyComponentProps } from './propertyComponentProps'; import { TextInputLineComponent } from '../../sharedComponents/textInputLineComponent'; import { TextLineComponent } from '../../sharedComponents/textLineComponent'; import { CheckBoxLineComponent } from '../../sharedComponents/checkBoxLineComponent'; import { FloatLineComponent } from '../../sharedComponents/floatLineComponent'; import { SliderLineComponent } from '../../sharedComponents/sliderLineComponent'; import { Vector2LineComponent } from '../../sharedComponents/vector2LineComponent'; import { OptionsLineComponent } from '../../sharedComponents/optionsLineComponent'; import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock'; import { PropertyTypeForEdition, IPropertyDescriptionForEdition, IEditablePropertyListOption } from 'babylonjs/Materials/Node/nodeMaterialDecorator'; export class GenericPropertyComponent extends React.Component<IPropertyComponentProps> { constructor(props: IPropertyComponentProps) { super(props); } render() { return ( <> <GeneralPropertyTabComponent globalState={this.props.globalState} block={this.props.block}/> <GenericPropertyTabComponent globalState={this.props.globalState} block={this.props.block}/> </> ); } } export class GeneralPropertyTabComponent extends React.Component<IPropertyComponentProps> { constructor(props: IPropertyComponentProps) { super(props); } render() { return ( <> <LineContainerComponent title="GENERAL"> { (!this.props.block.isInput || !(this.props.block as InputBlock).isAttribute) && <TextInputLineComponent globalState={this.props.globalState} label="Name" propertyName="name" target={this.props.block} onChange={() => this.props.globalState.onUpdateRequiredObservable.notifyObservers()} /> } <TextLineComponent label="Type" value={this.props.block.getClassName()} /> <TextInputLineComponent globalState={this.props.globalState} label="Comments" propertyName="comments" target={this.props.block} onChange={() => this.props.globalState.onUpdateRequiredObservable.notifyObservers()} /> </LineContainerComponent> </> ); } } export class GenericPropertyTabComponent extends React.Component<IPropertyComponentProps> { constructor(props: IPropertyComponentProps) { super(props); } forceRebuild(notifiers?: { "rebuild"?: boolean; "update"?: boolean; }) { if (!notifiers || notifiers.update) { this.props.globalState.onUpdateRequiredObservable.notifyObservers(); } if (!notifiers || notifiers.rebuild) { this.props.globalState.onRebuildRequiredObservable.notifyObservers(); } } render() { const block = this.props.block, propStore: IPropertyDescriptionForEdition[] = (block as any)._propStore; if (!propStore) { return ( <> </> ); } const componentList: { [groupName: string]: JSX.Element[]} = {}, groups: string[] = []; for (const { propertyName, displayName, type, groupName, options } of propStore) { let components = componentList[groupName]; if (!components) { components = []; componentList[groupName] = components; groups.push(groupName); } switch (type) { case PropertyTypeForEdition.Boolean: { components.push( <CheckBoxLineComponent label={displayName} target={this.props.block} propertyName={propertyName} onValueChanged={() => this.forceRebuild(options.notifiers)} /> ); break; } case PropertyTypeForEdition.Float: { <|fim▁hole|> if (cantDisplaySlider) { components.push( <FloatLineComponent globalState={this.props.globalState} label={displayName} propertyName={propertyName} target={this.props.block} onChange={() => this.forceRebuild(options.notifiers)} /> ); } else { components.push( <SliderLineComponent label={displayName} target={this.props.block} propertyName={propertyName} step={Math.abs((options.max as number) - (options.min as number)) / 100.0} minimum={Math.min(options.min as number, options.max as number)} maximum={options.max as number} onChange={() => this.forceRebuild(options.notifiers)}/> ); } break; } case PropertyTypeForEdition.Vector2: { components.push( <Vector2LineComponent globalState={this.props.globalState} label={displayName} propertyName={propertyName} target={this.props.block} onChange={() => this.forceRebuild(options.notifiers)} /> ); break; } case PropertyTypeForEdition.List: { components.push( <OptionsLineComponent label={displayName} options={options.options as IEditablePropertyListOption[]} target={this.props.block} propertyName={propertyName} onSelect={() => this.forceRebuild(options.notifiers)} /> ); break; } } } return ( <> { groups.map((group) => <LineContainerComponent title={group}> {componentList[group]} </LineContainerComponent> ) } </> ); } }<|fim▁end|>
let cantDisplaySlider = (isNaN(options.min as number) || isNaN(options.max as number) || options.min === options.max);
<|file_name|>product.py<|end_file_name|><|fim▁begin|># coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for<|fim▁hole|># # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class Product(Model): _required = [] _attribute_map = { 'integer': {'key': 'integer', 'type': 'int'}, 'string': {'key': 'string', 'type': 'str'}, } def __init__(self, *args, **kwargs): """Product :param int integer :param str string """ self.integer = None self.string = None super(Product, self).__init__(*args, **kwargs)<|fim▁end|>
# license information.
<|file_name|>apiservice.go<|end_file_name|><|fim▁begin|>/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file was automatically generated by informer-gen with arguments: --input-dirs=[k8s.io/kubernetes/cmd/kube-aggregator/pkg/apis/apiregistration,k8s.io/kubernetes/cmd/kube-aggregator/pkg/apis/apiregistration/v1alpha1] --internal-clientset-package=k8s.io/kubernetes/cmd/kube-aggregator/pkg/client/clientset_generated/internalclientset --listers-package=k8s.io/kubernetes/cmd/kube-aggregator/pkg/client/listers --output-package=k8s.io/kubernetes/cmd/kube-aggregator/pkg/client/informers --versioned-clientset-package=k8s.io/kubernetes/cmd/kube-aggregator/pkg/client/clientset_generated/clientset package v1alpha1 <|fim▁hole|> v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" apiregistration_v1alpha1 "k8s.io/kubernetes/cmd/kube-aggregator/pkg/apis/apiregistration/v1alpha1" clientset "k8s.io/kubernetes/cmd/kube-aggregator/pkg/client/clientset_generated/clientset" internalinterfaces "k8s.io/kubernetes/cmd/kube-aggregator/pkg/client/informers/internalinterfaces" v1alpha1 "k8s.io/kubernetes/cmd/kube-aggregator/pkg/client/listers/apiregistration/v1alpha1" cache "k8s.io/kubernetes/pkg/client/cache" time "time" ) // APIServiceInformer provides access to a shared informer and lister for // APIServices. type APIServiceInformer interface { Informer() cache.SharedIndexInformer Lister() v1alpha1.APIServiceLister } type aPIServiceInformer struct { factory internalinterfaces.SharedInformerFactory } func newAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { sharedIndexInformer := cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { return client.ApiregistrationV1alpha1().APIServices().List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { return client.ApiregistrationV1alpha1().APIServices().Watch(options) }, }, &apiregistration_v1alpha1.APIService{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, ) return sharedIndexInformer } func (f *aPIServiceInformer) Informer() cache.SharedIndexInformer { return f.factory.VersionedInformerFor(&apiregistration_v1alpha1.APIService{}, newAPIServiceInformer) } func (f *aPIServiceInformer) Lister() v1alpha1.APIServiceLister { return v1alpha1.NewAPIServiceLister(f.Informer().GetIndexer()) }<|fim▁end|>
import (
<|file_name|>browsercontext.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::trace::Traceable; use dom::bindings::utils::Reflectable; use dom::document::Document; use dom::window::Window; use js::jsapi::JSObject; use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps}; use js::rust::with_compartment; use libc::c_void; use std::ptr; #[allow(raw_pointer_deriving)] #[deriving(Encodable)] pub struct BrowserContext { history: Vec<SessionHistoryEntry>, active_index: uint, window_proxy: Traceable<*mut JSObject>, } impl BrowserContext { pub fn new(document: JSRef<Document>) -> BrowserContext { let mut context = BrowserContext { history: vec!(SessionHistoryEntry::new(document)), active_index: 0, window_proxy: Traceable::new(ptr::null_mut()), }; context.create_window_proxy(); context } pub fn active_document(&self) -> Temporary<Document> { Temporary::new(self.history[self.active_index].document.clone()) } pub fn active_window(&self) -> Temporary<Window> { let doc = self.active_document().root(); Temporary::new(doc.deref().window.clone()) } pub fn window_proxy(&self) -> *mut JSObject { assert!(self.window_proxy.deref().is_not_null()); *self.window_proxy } fn create_window_proxy(&mut self) { let win = self.active_window().root(); let page = win.deref().page(); let js_info = page.js_info(); let handler = js_info.as_ref().unwrap().dom_static.windowproxy_handler; assert!(handler.deref().is_not_null()); let parent = win.deref().reflector().get_jsobject(); let cx = js_info.as_ref().unwrap().js_context.deref().deref().ptr; let wrapper = with_compartment(cx, parent, || unsafe { WrapperNew(cx, parent, *handler.deref()) }); assert!(wrapper.is_not_null()); self.window_proxy = Traceable::new(wrapper); } } #[deriving(Encodable)] #[must_root] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<BrowserContext> } impl SessionHistoryEntry { fn new(document: JSRef<Document>) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_rooted(document), children: vec!() } } } static proxy_handler: ProxyTraps = ProxyTraps { getPropertyDescriptor: None, getOwnPropertyDescriptor: None, defineProperty: None, getOwnPropertyNames: 0 as *const u8, delete_: None, enumerate: 0 as *const u8, has: None, hasOwn: None, get: None, set: None, keys: 0 as *const u8,<|fim▁hole|> nativeCall: 0 as *const u8, hasInstance: None, typeOf: None, objectClassIs: None, obj_toString: None, fun_toString: None, //regexp_toShared: 0 as *u8, defaultValue: None, iteratorNext: None, finalize: None, getElementIfPresent: None, getPrototypeOf: None, trace: None }; pub fn new_window_proxy_handler() -> *const c_void { unsafe { CreateWrapperProxyHandler(&proxy_handler) } }<|fim▁end|>
iterate: None, call: None, construct: None,
<|file_name|>data.py<|end_file_name|><|fim▁begin|>""" A neural chatbot using sequence to sequence model with attentional decoder. This is based on Google Translate Tensorflow model https://github.com/tensorflow/models/blob/master/tutorials/rnn/translate/ Sequence to sequence model by Cho et al.(2014) Created by Chip Huyen as the starter code for assignment 3, class CS 20SI: "TensorFlow for Deep Learning Research" cs20si.stanford.edu This file contains the code to do the pre-processing for the Cornell Movie-Dialogs Corpus. See readme.md for instruction on how to run the starter code. """ from __future__ import print_function import random import re import os import numpy as np import config def get_lines(): id2line = {} file_path = os.path.join(config.DATA_PATH, config.LINE_FILE)<|fim▁hole|> for line in lines: parts = line.split(' +++$+++ ') if len(parts) == 5: if parts[4][-1] == '\n': parts[4] = parts[4][:-1] id2line[parts[0]] = parts[4] return id2line def get_convos(): """ Get conversations from the raw data """ file_path = os.path.join(config.DATA_PATH, config.CONVO_FILE) convos = [] with open(file_path, 'rb') as f: for line in f.readlines(): parts = line.split(' +++$+++ ') if len(parts) == 4: convo = [] for line in parts[3][1:-2].split(', '): convo.append(line[1:-1]) convos.append(convo) return convos def question_answers(id2line, convos): """ Divide the dataset into two sets: questions and answers. """ questions, answers = [], [] for convo in convos: for index, line in enumerate(convo[:-1]): questions.append(id2line[convo[index]]) answers.append(id2line[convo[index + 1]]) assert len(questions) == len(answers) return questions, answers def prepare_dataset(questions, answers): # create path to store all the train & test encoder & decoder make_dir(config.PROCESSED_PATH) # random convos to create the test set test_ids = random.sample([i for i in range(len(questions))],config.TESTSET_SIZE) filenames = ['train.enc', 'train.dec', 'test.enc', 'test.dec'] files = [] for filename in filenames: files.append(open(os.path.join(config.PROCESSED_PATH, filename),'wb')) for i in range(len(questions)): if i in test_ids: files[2].write(questions[i] + '\n') files[3].write(answers[i] + '\n') else: files[0].write(questions[i] + '\n') files[1].write(answers[i] + '\n') for file in files: file.close() def make_dir(path): """ Create a directory if there isn't one already. """ try: os.mkdir(path) except OSError: pass def basic_tokenizer(line, normalize_digits=True): """ A basic tokenizer to tokenize text into tokens. Feel free to change this to suit your need. """ line = re.sub('<u>', '', line) line = re.sub('</u>', '', line) line = re.sub('\[', '', line) line = re.sub('\]', '', line) words = [] _WORD_SPLIT = re.compile(b"([.,!?\"'-<>:;)(])") _DIGIT_RE = re.compile(r"\d") for fragment in line.strip().lower().split(): for token in re.split(_WORD_SPLIT, fragment): if not token: continue if normalize_digits: token = re.sub(_DIGIT_RE, b'#', token) words.append(token) return words def build_vocab(filename, normalize_digits=True): in_path = os.path.join(config.PROCESSED_PATH, filename) out_path = os.path.join(config.PROCESSED_PATH, 'vocab.{}'.format(filename[-3:])) vocab = {} with open(in_path, 'rb') as f: for line in f.readlines(): for token in basic_tokenizer(line): if not token in vocab: vocab[token] = 0 vocab[token] += 1 sorted_vocab = sorted(vocab, key=vocab.get, reverse=True) with open(out_path, 'wb') as f: f.write('<pad>' + '\n') f.write('<unk>' + '\n') f.write('<s>' + '\n') f.write('<\s>' + '\n') index = 4 for word in sorted_vocab: if vocab[word] < config.THRESHOLD: with open('config.py', 'ab') as cf: if filename[-3:] == 'enc': cf.write('ENC_VOCAB = ' + str(index) + '\n') else: cf.write('DEC_VOCAB = ' + str(index) + '\n') break f.write(word + '\n') index += 1 def load_vocab(vocab_path): with open(vocab_path, 'rb') as f: words = f.read().splitlines() return words, {words[i]: i for i in range(len(words))} def sentence2id(vocab, line): return [vocab.get(token, vocab['<unk>']) for token in basic_tokenizer(line)] def token2id(data, mode): """ Convert all the tokens in the data into their corresponding index in the vocabulary. """ vocab_path = 'vocab.' + mode in_path = data + '.' + mode out_path = data + '_ids.' + mode _, vocab = load_vocab(os.path.join(config.PROCESSED_PATH, vocab_path)) in_file = open(os.path.join(config.PROCESSED_PATH, in_path), 'rb') out_file = open(os.path.join(config.PROCESSED_PATH, out_path), 'wb') lines = in_file.read().splitlines() for line in lines: if mode == 'dec': # we only care about '<s>' and </s> in encoder ids = [vocab['<s>']] else: ids = [] ids.extend(sentence2id(vocab, line)) # ids.extend([vocab.get(token, vocab['<unk>']) for token in basic_tokenizer(line)]) if mode == 'dec': ids.append(vocab['<\s>']) out_file.write(' '.join(str(id_) for id_ in ids) + '\n') def prepare_raw_data(): print('Preparing raw data into train set and test set ...') id2line = get_lines() convos = get_convos() questions, answers = question_answers(id2line, convos) prepare_dataset(questions, answers) def process_data(): print('Preparing data to be model-ready ...') build_vocab('train.enc') build_vocab('train.dec') token2id('train', 'enc') token2id('train', 'dec') token2id('test', 'enc') token2id('test', 'dec') def load_data(enc_filename, dec_filename, max_training_size=None): encode_file = open(os.path.join(config.PROCESSED_PATH, enc_filename), 'rb') decode_file = open(os.path.join(config.PROCESSED_PATH, dec_filename), 'rb') encode, decode = encode_file.readline(), decode_file.readline() data_buckets = [[] for _ in config.BUCKETS] i = 0 while encode and decode: if (i + 1) % 10000 == 0: print("Bucketing conversation number", i) encode_ids = [int(id_) for id_ in encode.split()] decode_ids = [int(id_) for id_ in decode.split()] for bucket_id, (encode_max_size, decode_max_size) in enumerate(config.BUCKETS): if len(encode_ids) <= encode_max_size and len(decode_ids) <= decode_max_size: data_buckets[bucket_id].append([encode_ids, decode_ids]) break encode, decode = encode_file.readline(), decode_file.readline() i += 1 return data_buckets def _pad_input(input_, size): return input_ + [config.PAD_ID] * (size - len(input_)) def _reshape_batch(inputs, size, batch_size): """ Create batch-major inputs. Batch inputs are just re-indexed inputs """ batch_inputs = [] for length_id in xrange(size): batch_inputs.append(np.array([inputs[batch_id][length_id] for batch_id in xrange(batch_size)], dtype=np.int32)) return batch_inputs def get_batch(data_bucket, bucket_id, batch_size=1): """ Return one batch to feed into the model """ # only pad to the max length of the bucket encoder_size, decoder_size = config.BUCKETS[bucket_id] encoder_inputs, decoder_inputs = [], [] for _ in xrange(batch_size): encoder_input, decoder_input = random.choice(data_bucket) # pad both encoder and decoder, reverse the encoder encoder_inputs.append(list(reversed(_pad_input(encoder_input, encoder_size)))) decoder_inputs.append(_pad_input(decoder_input, decoder_size)) # now we create batch-major vectors from the data selected above. batch_encoder_inputs = _reshape_batch(encoder_inputs, encoder_size, batch_size) batch_decoder_inputs = _reshape_batch(decoder_inputs, decoder_size, batch_size) # create decoder_masks to be 0 for decoders that are padding. batch_masks = [] for length_id in xrange(decoder_size): batch_mask = np.ones(batch_size, dtype=np.float32) for batch_id in xrange(batch_size): # we set mask to 0 if the corresponding target is a PAD symbol. # the corresponding decoder is decoder_input shifted by 1 forward. if length_id < decoder_size - 1: target = decoder_inputs[batch_id][length_id + 1] if length_id == decoder_size - 1 or target == config.PAD_ID: batch_mask[batch_id] = 0.0 batch_masks.append(batch_mask) return batch_encoder_inputs, batch_decoder_inputs, batch_masks if __name__ == '__main__': prepare_raw_data() process_data()<|fim▁end|>
with open(file_path, 'rb') as f: lines = f.readlines()
<|file_name|>app.ts<|end_file_name|><|fim▁begin|>import 'leaflet'; import './main.scss'; import "reflect-metadata"; import "zone.js/dist/zone"; import "zone.js/dist/long-stack-trace-zone"; import { BrowserModule } from "@angular/platform-browser"; import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; import { Component, NgModule, ComponentRef, Injector, ApplicationRef, ComponentFactoryResolver, Injectable, NgZone } from "@angular/core"; // ########################################### // App component // ########################################### @Component({ selector: "app", template: `<section class="app"><map></map></section>` }) class AppComponent { } // ########################################### // Popup component // ########################################### @Component({ selector: "popup", template: `<section class="popup">Popup Component! :D {{ param }}</section>` }) class PopupComponent { } // ########################################### // $compile for Angular 4! :D // ########################################### @Injectable() class CustomCompileService { private appRef: ApplicationRef; constructor( private injector: Injector, private resolver: ComponentFactoryResolver ) { } configure(appRef) { this.appRef = appRef; } compile(component, onAttach) { const compFactory = this.resolver.resolveComponentFactory(component); let compRef = compFactory.create(this.injector); if (onAttach) onAttach(compRef); this.appRef.attachView(compRef.hostView); compRef.onDestroy(() => this.appRef.detachView(compRef.hostView)); let div = document.createElement('div'); div.appendChild(compRef.location.nativeElement); return div; } } // ########################################### // Leaflet map service // ########################################### @Injectable() class MapService { map: any; baseMaps: any; markersLayer: any; appRef: ApplicationRef; constructor(private compileService: CustomCompileService) { compileService.configure(this.appRef); } init(selector, appRef: ApplicationRef) { this.appRef = appRef; this.baseMaps = { CartoDB: L.tileLayer("http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png", { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>' }) }; L.Icon.Default.imagePath = '.'; L.Icon.Default.mergeOptions({ iconUrl: require('leaflet/dist/images/marker-icon.png'), shadowUrl: require('leaflet/dist/images/marker-shadow.png') }); this.map = L.map(selector); this.baseMaps.CartoDB.addTo(this.map); this.map.setView([51.505, -0.09], 13); <|fim▁hole|> this.markersLayer = new L.FeatureGroup(null); this.markersLayer.clearLayers(); this.markersLayer.addTo(this.map); this.compileService.configure(this.appRef); } addMarker() { var m = L.marker([51.510, -0.09]); m.bindTooltip('Angular 4 marker (PopupComponent)'); m.bindPopup(null); m.on('click', (e) => { m.setPopupContent( this.compileService.compile(PopupComponent, (c) => { c.instance.param = 0; setInterval(() => c.instance.param++, 1000); }) ); }); this.markersLayer.addLayer(m); return m; } } // ########################################### // Map component. These imports must be made // here, they can't be in a service as they // seem to depend on being loaded inside a // component. // ########################################### @Component({ selector: "map", template: `<section class="map"><div id="map"></div></section>`, }) class MapComponent { marker: any; constructor( private appRef: ApplicationRef, private mapService: MapService ) { } ngOnInit() { this.mapService.init('map', this.appRef); this.marker = this.mapService.addMarker(); } } // ########################################### // Main module // ########################################### @NgModule({ imports: [ BrowserModule ], providers: [ MapService, CustomCompileService ], declarations: [ AppComponent, MapComponent, PopupComponent ], entryComponents: [ PopupComponent ], bootstrap: [AppComponent] }) class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule);<|fim▁end|>
<|file_name|>quaternion.pb.go<|end_file_name|><|fim▁begin|>// Copyright 2021 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.26.0 // protoc v3.12.2 // source: google/type/quaternion.proto package quaternion 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) ) // A quaternion is defined as the quotient of two directed lines in a // three-dimensional space or equivalently as the quotient of two Euclidean // vectors (https://en.wikipedia.org/wiki/Quaternion). // // Quaternions are often used in calculations involving three-dimensional // rotations (https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation), // as they provide greater mathematical robustness by avoiding the gimbal lock // problems that can be encountered when using Euler angles // (https://en.wikipedia.org/wiki/Gimbal_lock). // // Quaternions are generally represented in this form: // // w + xi + yj + zk // // where x, y, z, and w are real numbers, and i, j, and k are three imaginary // numbers. // // Our naming choice `(x, y, z, w)` comes from the desire to avoid confusion for // those interested in the geometric properties of the quaternion in the 3D // Cartesian space. Other texts often use alternative names or subscripts, such // as `(a, b, c, d)`, `(1, i, j, k)`, or `(0, 1, 2, 3)`, which are perhaps // better suited for mathematical interpretations. // // To avoid any confusion, as well as to maintain compatibility with a large // number of software libraries, the quaternions represented using the protocol // buffer below *must* follow the Hamilton convention, which defines `ij = k` // (i.e. a right-handed algebra), and therefore: // // i^2 = j^2 = k^2 = ijk = −1 // ij = −ji = k // jk = −kj = i // ki = −ik = j // // Please DO NOT use this to represent quaternions that follow the JPL // convention, or any of the other quaternion flavors out there. // // Definitions: // // - Quaternion norm (or magnitude): `sqrt(x^2 + y^2 + z^2 + w^2)`. // - Unit (or normalized) quaternion: a quaternion whose norm is 1. // - Pure quaternion: a quaternion whose scalar component (`w`) is 0. // - Rotation quaternion: a unit quaternion used to represent rotation. // - Orientation quaternion: a unit quaternion used to represent orientation. // // A quaternion can be normalized by dividing it by its norm. The resulting // quaternion maintains the same direction, but has a norm of 1, i.e. it moves // on the unit sphere. This is generally necessary for rotation and orientation // quaternions, to avoid rounding errors: // https://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions // // Note that `(x, y, z, w)` and `(-x, -y, -z, -w)` represent the same rotation, // but normalization would be even more useful, e.g. for comparison purposes, if // it would produce a unique representation. It is thus recommended that `w` be // kept positive, which can be achieved by changing all the signs when `w` is // negative. // type Quaternion struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The x component. X float64 `protobuf:"fixed64,1,opt,name=x,proto3" json:"x,omitempty"` // The y component. Y float64 `protobuf:"fixed64,2,opt,name=y,proto3" json:"y,omitempty"` // The z component. Z float64 `protobuf:"fixed64,3,opt,name=z,proto3" json:"z,omitempty"` // The scalar component. W float64 `protobuf:"fixed64,4,opt,name=w,proto3" json:"w,omitempty"` } func (x *Quaternion) Reset() { *x = Quaternion{} if protoimpl.UnsafeEnabled { mi := &file_google_type_quaternion_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Quaternion) String() string { return protoimpl.X.MessageStringOf(x) } func (*Quaternion) ProtoMessage() {} func (x *Quaternion) ProtoReflect() protoreflect.Message { mi := &file_google_type_quaternion_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 Quaternion.ProtoReflect.Descriptor instead. func (*Quaternion) Descriptor() ([]byte, []int) { return file_google_type_quaternion_proto_rawDescGZIP(), []int{0} } func (x *Quaternion) GetX() float64 { if x != nil { return x.X } return 0 } func (x *Quaternion) GetY() float64 { if x != nil { return x.Y } return 0 } func (x *Quaternion) GetZ() float64 { if x != nil { return x.Z } return 0 } func (x *Quaternion) GetW() float64 { if x != nil { return x.W } return 0 } var File_google_type_quaternion_proto protoreflect.FileDescriptor var file_google_type_quaternion_proto_rawDesc = []byte{ 0x0a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x71, 0x75, 0x61, 0x74, 0x65, 0x72, 0x6e, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x22, 0x44, 0x0a, 0x0a, 0x51, 0x75, 0x61, 0x74, 0x65, 0x72, 0x6e, 0x69, 0x6f, 0x6e, 0x12, 0x0c, 0x0a, 0x01, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x01, 0x78, 0x12, 0x0c, 0x0a, 0x01, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x01, 0x79, 0x12, 0x0c, 0x0a, 0x01, 0x7a, 0x18, 0x03, 0x20, 0x01, 0x28, 0x01, 0x52, 0x01, 0x7a, 0x12, 0x0c, 0x0a, 0x01, 0x77, 0x18, 0x04, 0x20, 0x01, 0x28, 0x01, 0x52, 0x01, 0x77, 0x42, 0x6f, 0x0a, 0x0f, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x42, 0x0f, 0x51, 0x75, 0x61, 0x74, 0x65, 0x72, 0x6e, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x40, 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, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x71, 0x75, 0x61, 0x74, 0x65, 0x72, 0x6e, 0x69, 0x6f, 0x6e, 0x3b, 0x71, 0x75, 0x61, 0x74, 0x65, 0x72, 0x6e, 0x69, 0x6f, 0x6e, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x54, 0x50, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_type_quaternion_proto_rawDescOnce sync.Once file_google_type_quaternion_proto_rawDescData = file_google_type_quaternion_proto_rawDesc ) func file_google_type_quaternion_proto_rawDescGZIP() []byte { file_google_type_quaternion_proto_rawDescOnce.Do(func() { file_google_type_quaternion_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_type_quaternion_proto_rawDescData) }) return file_google_type_quaternion_proto_rawDescData } var file_google_type_quaternion_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_type_quaternion_proto_goTypes = []interface{}{ (*Quaternion)(nil), // 0: google.type.Quaternion } var file_google_type_quaternion_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_type_quaternion_proto_init() } func file_google_type_quaternion_proto_init() { if File_google_type_quaternion_proto != nil { return } if !protoimpl.UnsafeEnabled { file_google_type_quaternion_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Quaternion); 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_type_quaternion_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, },<|fim▁hole|> GoTypes: file_google_type_quaternion_proto_goTypes, DependencyIndexes: file_google_type_quaternion_proto_depIdxs, MessageInfos: file_google_type_quaternion_proto_msgTypes, }.Build() File_google_type_quaternion_proto = out.File file_google_type_quaternion_proto_rawDesc = nil file_google_type_quaternion_proto_goTypes = nil file_google_type_quaternion_proto_depIdxs = nil }<|fim▁end|>
<|file_name|>_open_newick.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://ete.cgenomics.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ETE is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public # License for more details. # # You should have received a copy of the GNU General Public License # along with ETE. If not, see <http://www.gnu.org/licenses/>. # # # ABOUT THE ETE PACKAGE # ===================== # # ETE is distributed under the GPL copyleft license (2008-2011). # # If you make use of ETE in published work, please cite: # # Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. # ETE: a python Environment for Tree Exploration. Jaime BMC # Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 # # Note that extra references to the specific methods implemented in # the toolkit are available in the documentation. # # More info at http://ete.cgenomics.org # # # #END_LICENSE############################################################# __VERSION__="ete2-2.2rev1056" # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'open_newick.ui' # # Created: Tue Jan 10 15:56:56 2012 # by: PyQt4 UI code generator 4.7.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui <|fim▁hole|>class Ui_OpenNewick(object): def setupUi(self, OpenNewick): OpenNewick.setObjectName("OpenNewick") OpenNewick.resize(569, 353) self.comboBox = QtGui.QComboBox(OpenNewick) self.comboBox.setGeometry(QtCore.QRect(460, 300, 81, 23)) self.comboBox.setObjectName("comboBox") self.widget = QtGui.QWidget(OpenNewick) self.widget.setGeometry(QtCore.QRect(30, 10, 371, 321)) self.widget.setObjectName("widget") self.retranslateUi(OpenNewick) QtCore.QMetaObject.connectSlotsByName(OpenNewick) def retranslateUi(self, OpenNewick): OpenNewick.setWindowTitle(QtGui.QApplication.translate("OpenNewick", "Dialog", None, QtGui.QApplication.UnicodeUTF8))<|fim▁end|>
<|file_name|>pages.js<|end_file_name|><|fim▁begin|>const models = require('../../models'); const {i18n} = require('../../lib/common'); const errors = require('@tryghost/errors'); const urlUtils = require('../../../shared/url-utils'); const ALLOWED_INCLUDES = ['tags', 'authors', 'authors.roles']; const UNSAFE_ATTRS = ['status', 'authors', 'visibility']; module.exports = { docName: 'pages', browse: { options: [ 'include', 'filter', 'fields', 'formats', 'limit', 'order', 'page', 'debug', 'absolute_urls' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, formats: { values: models.Post.allowedFormats } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.findPage(frame.options); } }, read: { options: [ 'include', 'fields', 'formats', 'debug', 'absolute_urls', // NOTE: only for internal context 'forUpdate', 'transacting' ], data: [ 'id', 'slug', 'uuid' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, formats: { values: models.Post.allowedFormats } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.findOne(frame.data, frame.options) .then((model) => { if (!model) { throw new errors.NotFoundError({ message: i18n.t('errors.api.pages.pageNotFound') }); } return model; }); } }, add: { statusCode: 201, headers: {}, options: [ 'include', 'source' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, source: { values: ['html'] } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.add(frame.data.pages[0], frame.options) .then((model) => { if (model.get('status') !== 'published') { this.headers.cacheInvalidate = false; } else { this.headers.cacheInvalidate = true; } return model; }); } }, <|fim▁hole|> edit: { headers: {}, options: [ 'include', 'id', 'source', // NOTE: only for internal context 'forUpdate', 'transacting' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, id: { required: true }, source: { values: ['html'] } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.edit(frame.data.pages[0], frame.options) .then((model) => { if ( model.get('status') === 'published' && model.wasChanged() || model.get('status') === 'draft' && model.previous('status') === 'published' ) { this.headers.cacheInvalidate = true; } else if ( model.get('status') === 'draft' && model.previous('status') !== 'published' || model.get('status') === 'scheduled' && model.wasChanged() ) { this.headers.cacheInvalidate = { value: urlUtils.urlFor({ relativeUrl: urlUtils.urlJoin('/p', model.get('uuid'), '/') }) }; } else { this.headers.cacheInvalidate = false; } return model; }); } }, destroy: { statusCode: 204, headers: { cacheInvalidate: true }, options: [ 'include', 'id' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, id: { required: true } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { frame.options.require = true; return models.Post.destroy(frame.options) .then(() => null) .catch(models.Post.NotFoundError, () => { return Promise.reject(new errors.NotFoundError({ message: i18n.t('errors.api.pages.pageNotFound') })); }); } } };<|fim▁end|>
<|file_name|>app.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import time import json import random import re from bottle import route, hook, response, run, static_file @route('/') def index(): return static_file('index.html', root = '.') @route('/maptweets.js') def index_css(): return static_file('maptweets.js', root = '.') @route('/cross.jpg') def index_css(): return static_file('cross.jpg', root = '.') @route('/light.png') def index_css(): return static_file('light.png', root = '.') @route('/event.png') def index_css():<|fim▁hole|><|fim▁end|>
return static_file('event.png', root = '.') run(host = '0.0.0.0', port = 80, server = 'tornado', debug = True)
<|file_name|>CommCareTestApp.java<|end_file_name|><|fim▁begin|>package org.commcare; import org.commcare.models.database.UnencryptedHybridFileBackedSqlStorage; import org.commcare.models.database.UnencryptedHybridFileBackedSqlStorageMock; import org.javarosa.core.services.storage.Persistable; /** * Delegator around CommCareApp allowing the test suite to override logic. * * @author Phillip Mates ([email protected]). */ public class CommCareTestApp extends CommCareApp { private final CommCareApp app; public CommCareTestApp(CommCareApp app) { super(app.getAppRecord()); fileRoot = app.fileRoot; setAppResourceState(app.getAppResourceState()); this.app = app; } @Override public <T extends Persistable> UnencryptedHybridFileBackedSqlStorage<T> getFileBackedStorage(String name, Class<T> c) {<|fim▁hole|> } }<|fim▁end|>
return new UnencryptedHybridFileBackedSqlStorageMock<>(name, c, app.buildAndroidDbHelper(), app);
<|file_name|>mqtt_chat_client.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ''' Created on 17/2/16. @author: love ''' import paho.mqtt.client as mqtt import json import ssl def on_connect(client, userdata, flags, rc): print("Connected with result code %d"%rc) client.publish("Login/HD_Login/1", json.dumps({"userName": user, "passWord": "Hello,anyone!"}),qos=0,retain=False) def on_message(client, userdata, msg): print ('---------------') print ("topic :"+msg.topic) print ("payload :"+msg.payload) client.subscribe([("chat",2),("aaa",2)]) client.unsubscribe(["chat"]) #client.publish("login/addUser", json.dumps({"user": user, "say": "Hello,anyone!"}),qos=2,retain=False) #print(msg.topic+":"+str(msg.payload.decode())) #print(msg.topic+":"+msg.payload.decode()) #payload = json.loads(msg.payload.decode()) #print(payload.get("user")+":"+payload.get("say")) def mylog(self,userdata,level, buf): print buf if __name__ == '__main__': client = mqtt.Client(protocol=mqtt.MQTTv31) client.username_pw_set("admin", "password") # 必须设置,否则会返回「Connected with result code 4」 client.on_connect = on_connect client.on_message = on_message #链接测试服务器 需要用tls请求 python tls功能比较弱。 # 需要一个证书,这里使用的这个网站提供的证书https://curl.haxx.se/docs/caextract.html HOST = "mqant.com" # client.tls_set(ca_certs="caextract.pem", certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, # tls_version=ssl.PROTOCOL_TLSv1, ciphers=None) client.connect(HOST, 3563, 60) #client.loop_forever() user = raw_input("请输入用户名:") client.user_data_set(user) client.loop_start() while True: s = raw_input("请先输入'join'加入房间,然后输入任意聊天字符:\n") if s: if s=="join": client.publish("Chat/HD_JoinChat/2", json.dumps({"roomName": "mqant"}),qos=0,retain=False)<|fim▁hole|> client.publish("Master/HD_Stop_Process/2", json.dumps({"ProcessID": "001"}),qos=0,retain=False) else: client.publish("Chat/HD_Say/2", json.dumps({"roomName": "mqant","from":user,"target":"*","content": s}),qos=0,retain=False)<|fim▁end|>
elif s=="start": client.publish("Master/HD_Start_Process/2", json.dumps({"ProcessID": "001"}),qos=0,retain=False) elif s=="stop":
<|file_name|>ApiConstants.js<|end_file_name|><|fim▁begin|>export const GET = 'GET'; export const PUT = 'PUT'; export const POST = 'POST';<|fim▁hole|><|fim▁end|>
export const DELETE = 'DELETE';
<|file_name|>compatibility.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import sys import django from django.utils import six try: from django.utils.text import truncate_words except ImportError: # django >=1.5 from django.utils.text import Truncator from django.utils.functional import allow_lazy def truncate_words(s, num, end_text='...'): truncate = end_text and ' %s' % end_text or '' return Truncator(s).words(num, truncate=truncate) truncate_words = allow_lazy(truncate_words, six.text_type) DJANGO_1_4 = django.VERSION < (1, 5) DJANGO_1_5 = django.VERSION < (1, 6) DJANGO_1_6 = django.VERSION < (1, 7) DJANGO_1_7 = django.VERSION < (1, 8) DJANGO_1_8 = django.VERSION < (1, 9) if not six.PY3: fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() # copied from django.utils._os (not present in Django 1.4) def upath(path): """ Always return a unicode path. """ if six.PY2 and not isinstance(path, six.text_type): return path.decode(fs_encoding) return path # copied from django-cms (for compatibility with Django 1.4) try: from django.utils.encoding import force_unicode def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass except ImportError: force_unicode = lambda s: str(s) from django.utils.encoding import python_2_unicode_compatible def get_delete_permission(opts): try: from django.contrib.auth import get_permission_codename return '%s.%s' % (opts.app_label,<|fim▁hole|> get_permission_codename('delete', opts)) except ImportError: return '%s.%s' % (opts.app_label, opts.get_delete_permission())<|fim▁end|>
<|file_name|>DenseTest.cpp<|end_file_name|><|fim▁begin|>//================================================================================================= /*! // \file src/mathtest/diagonalmatrix/DenseTest.cpp // \brief Source file for the DiagonalMatrix dense test // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. 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. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/CompressedVector.h> #include <blaze/math/DenseColumn.h> #include <blaze/math/DenseRow.h> #include <blaze/math/DenseSubmatrix.h> #include <blaze/math/DynamicVector.h> #include <blaze/math/HybridMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blaze/util/Complex.h> #include <blazetest/mathtest/diagonalmatrix/DenseTest.h> namespace blazetest { namespace mathtest { namespace diagonalmatrix { //================================================================================================= // // CONSTRUCTORS // //================================================================================================= //************************************************************************************************* /*!\brief Constructor for the DiagonalMatrix dense test. // // \exception std::runtime_error Operation error detected. */ DenseTest::DenseTest() { testConstructors(); testAssignment(); testAddAssign(); testSubAssign(); testMultAssign(); testScaling(); testFunctionCall(); testIterator(); testNonZeros(); testReset(); testClear(); testResize(); testExtend(); testReserve(); testSwap(); testIsDefault(); testSubmatrix(); testRow(); testColumn(); } //************************************************************************************************* //================================================================================================= // // TEST FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Test of the DiagonalMatrix constructors. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of all constructors of the DiagonalMatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testConstructors() { //===================================================================================== // Row-major default constructor //===================================================================================== // Default constructor (StaticMatrix) { test_ = "Row-major DiagonalMatrix default constructor (StaticMatrix)"; const blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> > diag; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 0UL ); } // Default constructor (HybridMatrix) { test_ = "Row-major DiagonalMatrix default constructor (HybridMatrix)"; const blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Default constructor (DynamicMatrix) { test_ = "Row-major DiagonalMatrix default constructor (DynamicMatrix)"; const DT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } //===================================================================================== // Row-major size constructor //===================================================================================== // Size constructor (HybridMatrix) { test_ = "Row-major DiagonalMatrix size constructor (HybridMatrix)"; const blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::rowMajor> > diag( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); checkNonZeros( diag, 0UL ); } // Size constructor (DynamicMatrix) { test_ = "Row-major DiagonalMatrix size constructor (DynamicMatrix)"; const DT diag( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); checkNonZeros( diag, 0UL ); } //===================================================================================== // Row-major copy constructor //===================================================================================== // Copy constructor (0x0) { test_ = "Row-major DiagonalMatrix copy constructor (0x0)"; const DT diag1; const DT diag2( diag1 ); checkRows ( diag2, 0UL ); checkColumns ( diag2, 0UL ); checkNonZeros( diag2, 0UL ); } // Copy constructor (3x3) { test_ = "Row-major DiagonalMatrix copy constructor (3x3)"; DT diag1( 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; const DT diag2( diag1 ); checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major conversion constructor //===================================================================================== // Conversion constructor (0x0) { test_ = "Row-major DiagonalMatrix conversion constructor (0x0)"; const blaze::DynamicMatrix<int,blaze::rowMajor> mat; const DT diag( mat ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Conversion constructor (diagonal) { test_ = "Row-major DiagonalMatrix conversion constructor (diagonal)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; const DT diag( mat ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Conversion constructor (lower) { test_ = "Row-major DiagonalMatrix conversion constructor (lower)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { const DT diag( mat ); std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of non-diagonal DiagonalMatrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Conversion constructor (upper) { test_ = "Row-major DiagonalMatrix conversion constructor (upper)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { const DT diag( mat ); std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of non-diagonal DiagonalMatrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Conversion constructor (DiagonalMatrix) { test_ = "Row-major DiagonalMatrix conversion constructor (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> > diag1; diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; const DT diag2( diag1 ); checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major default constructor //===================================================================================== // Default constructor (StaticMatrix) { test_ = "Column-major DiagonalMatrix default constructor (StaticMatrix)"; blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> > diag; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 0UL ); } // Default constructor (HybridMatrix) { test_ = "Column-major DiagonalMatrix default constructor (HybridMatrix)"; blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Default constructor (DynamicMatrix) { test_ = "Column-major DiagonalMatrix default constructor (DynamicMatrix)"; ODT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } //===================================================================================== // Column-major size constructor //===================================================================================== // Size constructor (HybridMatrix) { test_ = "Column-major DiagonalMatrix size constructor (HybridMatrix)"; blaze::DiagonalMatrix< blaze::HybridMatrix<int,3UL,3UL,blaze::columnMajor> > diag( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkNonZeros( diag, 0UL ); } // Size constructor (DynamicMatrix) { test_ = "Column-major DiagonalMatrix size constructor (DynamicMatrix)"; ODT diag( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkNonZeros( diag, 0UL ); } //===================================================================================== // Column-major copy constructor //===================================================================================== // Copy constructor (0x0) { test_ = "Column-major DiagonalMatrix copy constructor (0x0)"; const ODT diag1; const ODT diag2( diag1 ); checkRows ( diag2, 0UL ); checkColumns ( diag2, 0UL ); checkNonZeros( diag2, 0UL ); } // Copy constructor (3x3) { test_ = "Column-major DiagonalMatrix copy constructor (3x3)"; ODT diag1( 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; const ODT diag2( diag1 ); checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major conversion constructor //===================================================================================== // Conversion constructor (0x0) { test_ = "Column-major DiagonalMatrix conversion constructor (0x0)"; const blaze::DynamicMatrix<int,blaze::columnMajor> mat; const ODT diag( mat ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Conversion constructor (diagonal) { test_ = "Column-major DiagonalMatrix conversion constructor (diagonal)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; const ODT diag( mat ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Conversion constructor (lower) { test_ = "Column-major DiagonalMatrix conversion constructor (lower)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { const ODT diag( mat ); std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of non-diagonal DiagonalMatrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Conversion constructor (upper) { test_ = "Column-major DiagonalMatrix conversion constructor (upper)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { const ODT diag( mat ); std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Setup of non-diagonal DiagonalMatrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Conversion constructor (DiagonalMatrix) { test_ = "Column-major DiagonalMatrix conversion constructor (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> > diag1; diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; const ODT diag2( diag1 ); checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Construction failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the DiagonalMatrix assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of all assignment operators of the DiagonalMatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testAssignment() { //===================================================================================== // Row-major homogeneous assignment //===================================================================================== // Homogeneous assignment (3x3) { test_ = "Row-major DiagonalMatrix homogeneous assignment (3x3)"; DT diag( 3UL ); diag = 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 2 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major copy assignment //===================================================================================== // Copy assignment (0x0) { test_ = "Row-major DiagonalMatrix copy assignment (0x0)"; DT diag1, diag2; diag2 = diag1; checkRows ( diag2, 0UL ); checkColumns ( diag2, 0UL ); checkNonZeros( diag2, 0UL ); } // Copy assignment (3x3) { test_ = "Row-major DiagonalMatrix copy assignment (3x3)"; DT diag1( 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; DT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Row-major DiagonalMatrix dense matrix assignment (0x0)"; const blaze::DynamicMatrix<int,blaze::rowMajor> mat; DT diag; diag = mat; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Row-major/row-major dense matrix assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix dense matrix assignment (diagonal)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; DT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix dense matrix assignment (diagonal)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; DT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix dense matrix assignment (lower)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix dense matrix assignment (lower)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix dense matrix assignment (upper)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix dense matrix assignment (upper)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix dense matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> > diag1; diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; DT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix dense matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> > diag1; diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; DT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Row-major DiagonalMatrix sparse matrix assignment (0x0)"; const blaze::CompressedMatrix<int,blaze::rowMajor> mat; DT diag; diag = mat; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Row-major/row-major sparse matrix assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { DT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; DT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; DT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major homogeneous assignment //===================================================================================== // Homogeneous assignment (3x3) { test_ = "Column-major DiagonalMatrix homogeneous assignment (3x3)"; ODT diag( 3UL ); diag = 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 2 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major copy assignment //===================================================================================== // Copy assignment (0x0) { test_ = "Column-major DiagonalMatrix copy assignment (0x0)"; ODT diag1, diag2; diag2 = diag1; checkRows ( diag2, 0UL ); checkColumns ( diag2, 0UL ); checkNonZeros( diag2, 0UL ); } // Copy assignment (3x3) { test_ = "Column-major DiagonalMatrix copy assignment (3x3)"; ODT diag1( 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; ODT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Column-major DiagonalMatrix dense matrix assignment (0x0)"; const blaze::DynamicMatrix<int,blaze::rowMajor> mat; ODT diag; diag = mat; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Column-major/row-major dense matrix assignment (diagonal) { test_ = "Column-major/row-major DiagonalMatrix dense matrix assignment (diagonal)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; ODT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix dense matrix assignment (diagonal)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; ODT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix dense matrix assignment (lower)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix dense matrix assignment (lower)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix assignment (upper) { test_ = "Column-major/row-major DiagonalMatrix dense matrix assignment (upper)"; blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> mat; mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix dense matrix assignment (upper)"; blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> mat; mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix dense matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::rowMajor> > diag1; diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; ODT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix dense matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::StaticMatrix<int,3UL,3UL,blaze::columnMajor> > diag1; diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; ODT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix assignment //===================================================================================== // Conversion assignment (0x0) { test_ = "Column-major DiagonalMatrix sparse matrix assignment (0x0)"; const blaze::CompressedMatrix<int,blaze::rowMajor> mat; ODT diag; diag = mat; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } // Column-major/row-major sparse matrix assignment (diagonal) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,2) = 3; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag; diag = mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(1,1) = 2; mat(2,0) = 5; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix assignment (upper) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(0,0) = 1; mat(0,2) = 5; mat(1,1) = 2; mat(2,2) = 3; try { ODT diag; diag = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; ODT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 1; diag1(1,1) = 2; diag1(2,2) = 3; ODT diag2; diag2 = diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the DiagonalMatrix addition assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the addition assignment operators of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testAddAssign() { //===================================================================================== // Row-major dense matrix addition assignment //===================================================================================== // Row-major/row-major dense matrix addition assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix dense matrix addition assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = -2; mat(2,2) = 2; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix addition assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix dense matrix addition assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = -2; mat(2,2) = 2; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix addition assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix dense matrix addition assignment (lower)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix addition assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix dense matrix addition assignment (lower)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix addition assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix dense matrix addition assignment (upper)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix addition assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix dense matrix addition assignment (upper)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix addition assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix dense matrix addition assignment (DiagonalMatrix)"; DT diag1( 3UL ); diag1(1,1) = -2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix addition assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix dense matrix addition assignment (DiagonalMatrix)"; ODT diag1( 3UL ); diag1(1,1) = -2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix addition assignment //===================================================================================== // Row-major/row-major sparse matrix addition assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix addition assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = -2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix addition assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix addition assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = -2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix addition assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix addition assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix addition assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix addition assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix addition assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix addition assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix addition assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix addition assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix addition assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix addition assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 2UL ); diag1(1,1) = -2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix addition assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix addition assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 2UL ); diag1(1,1) = -2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix addition assignment //===================================================================================== // Column-major/row-major dense matrix addition assignment (diagonal) { test_ = "Column-major/row-major DiagonalMatrix dense matrix addition assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = -2; mat(2,2) = 2; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix addition assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix dense matrix addition assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = -2; mat(2,2) = 2; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix addition assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix dense matrix addition assignment (lower)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix addition assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix dense matrix addition assignment (lower)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix addition assignment (upper) { test_ = "Column-major/row-major DiagonalMatrix dense matrix addition assignment (upper)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix addition assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix dense matrix addition assignment (upper)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix addition assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix dense matrix addition assignment (DiagonalMatrix)"; DT diag1( 3UL ); diag1(1,1) = -2; diag1(2,2) = 2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix addition assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix dense matrix addition assignment (DiagonalMatrix)"; ODT diag1( 3UL ); diag1(1,1) = -2; diag1(2,2) = 2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix addition assignment //===================================================================================== // Column-major/row-major sparse matrix addition assignment (diagonal) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix addition assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = -2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix addition assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix addition assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = -2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag += mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix addition assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix addition assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix addition assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix addition assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix addition assignment (upper) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix addition assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix addition assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix addition assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag += mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix addition assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix addition assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 2UL ); diag1(1,1) = -2; diag1(2,2) = 2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix addition assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix addition assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 2UL ); diag1(1,1) = -2; diag1(2,2) = 2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 += diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Addition assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the DiagonalMatrix subtraction assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the subtraction assignment operators of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testSubAssign() { //===================================================================================== // Row-major dense matrix subtraction assignment //===================================================================================== // Row-major/row-major dense matrix subtraction assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix dense matrix subtraction assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = 2; mat(2,2) = -2; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix subtraction assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix dense matrix subtraction assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = 2; mat(2,2) = -2; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix subtraction assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix dense matrix subtraction assignment (lower)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix subtraction assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix dense matrix subtraction assignment (lower)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix subtraction assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix dense matrix subtraction assignment (upper)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix subtraction assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix dense matrix subtraction assignment (upper)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix subtraction assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix dense matrix subtraction assignment (DiagonalMatrix)"; DT diag1( 3UL ); diag1(1,1) = 2; diag1(2,2) = -2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix subtraction assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix dense matrix subtraction assignment (DiagonalMatrix)"; ODT diag1( 3UL ); diag1(1,1) = 2; diag1(2,2) = -2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix subtraction assignment //===================================================================================== // Row-major/row-major sparse matrix subtraction assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix subtraction assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = 2; mat(2,2) = -2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix subtraction assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix subtraction assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = 2; mat(2,2) = -2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix subtraction assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix subtraction assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix subtraction assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix subtraction assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix subtraction assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix subtraction assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix subtraction assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix subtraction assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix subtraction assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix subtraction assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 2UL ); diag1(1,1) = 2; diag1(2,2) = -2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix subtraction assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix subtraction assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 2UL ); diag1(1,1) = 2; diag1(2,2) = -2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix subtraction assignment //===================================================================================== // Column-major/row-major dense matrix subtraction assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix dense matrix subtraction assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = 2; mat(2,2) = -2; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix subtraction assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix dense matrix subtraction assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(1,1) = 2; mat(2,2) = -2; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix subtraction assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix dense matrix subtraction assignment (lower)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix subtraction assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix dense matrix subtraction assignment (lower)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix subtraction assignment (upper) { test_ = "Column-major/row-major DiagonalMatrix dense matrix subtraction assignment (upper)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix subtraction assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix dense matrix subtraction assignment (upper)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix subtraction assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix dense matrix subtraction assignment (DiagonalMatrix)"; DT diag1( 3UL ); diag1(1,1) = 2; diag1(2,2) = -2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix subtraction assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix dense matrix subtraction assignment (DiagonalMatrix)"; ODT diag1( 3UL ); diag1(1,1) = 2; diag1(2,2) = -2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix subtraction assignment //===================================================================================== // Column-major/row-major sparse matrix subtraction assignment (diagonal) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix subtraction assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = 2; mat(2,2) = -2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix subtraction assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix subtraction assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 4UL ); mat(1,1) = 2; mat(2,2) = -2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag -= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix subtraction assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix subtraction assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix subtraction assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix subtraction assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix subtraction assignment (upper) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix subtraction assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix subtraction assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix subtraction assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag -= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix subtraction assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix subtraction assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 2UL ); diag1(1,1) = 2; diag1(2,2) = -2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix subtraction assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix subtraction assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 2UL ); diag1(1,1) = 2; diag1(2,2) = -2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 -= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 0UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 0 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Subtraction assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the DiagonalMatrix multiplication assignment operators. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the multiplication assignment operators of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testMultAssign() { //===================================================================================== // Row-major dense matrix multiplication assignment //===================================================================================== // Row-major/row-major dense matrix multiplication assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix dense matrix multiplication assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix multiplication assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix dense matrix multiplication assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major dense matrix multiplication assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix dense matrix multiplication assignment (lower)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix multiplication assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix dense matrix multiplication assignment (lower)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix multiplication assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix dense matrix multiplication assignment (upper)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major dense matrix multiplication assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix dense matrix multiplication assignment (upper)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major dense matrix multiplication assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix dense matrix multiplication assignment (DiagonalMatrix)"; DT diag1( 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major dense matrix multiplication assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix dense matrix multiplication assignment (DiagonalMatrix)"; ODT diag1( 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major sparse matrix multiplication assignment //===================================================================================== // Row-major/row-major sparse matrix multiplication assignment (diagonal) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix multiplication assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix multiplication assignment (diagonal) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix multiplication assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/row-major sparse matrix multiplication assignment (lower) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix multiplication assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix multiplication assignment (lower) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix multiplication assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix multiplication assignment (upper) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix multiplication assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/column-major sparse matrix multiplication assignment (upper) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix multiplication assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Row-major/row-major sparse matrix multiplication assignment (DiagonalMatrix) { test_ = "Row-major/row-major DiagonalMatrix sparse matrix multiplication assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Row-major/column-major sparse matrix multiplication assignment (DiagonalMatrix) { test_ = "Row-major/column-major DiagonalMatrix sparse matrix multiplication assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix multiplication assignment //===================================================================================== // Column-major/row-major dense matrix multiplication assignment (diagonal) { test_ = "Column-major/row-major DiagonalMatrix dense matrix multiplication assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix multiplication assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix dense matrix multiplication assignment (diagonal)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major dense matrix multiplication assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix dense matrix multiplication assignment (lower)"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix multiplication assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix dense matrix multiplication assignment (lower)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix multiplication assignment (upper) { test_ = "Column"; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major dense matrix multiplication assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix dense matrix multiplication assignment (upper)"; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 0 ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major dense matrix multiplication assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix dense matrix multiplication assignment (DiagonalMatrix)"; ODT diag1( 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; DT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major dense matrix multiplication assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix dense matrix multiplication assignment (DiagonalMatrix)"; ODT diag1( 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major sparse matrix multiplication assignment //===================================================================================== // Column-major/row-major sparse matrix multiplication assignment (diagonal) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix multiplication assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix multiplication assignment (diagonal) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix multiplication assignment (diagonal)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 5UL ); mat(0,0) = 2; mat(1,1) = 2; mat(2,2) = 2; mat.insert( 1UL, 2UL, 0 ); mat.insert( 2UL, 1UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag *= mat; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/row-major sparse matrix multiplication assignment (lower) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix multiplication assignment (lower)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix multiplication assignment (lower) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix multiplication assignment (lower)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(2,0) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of lower column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix multiplication assignment (upper) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix multiplication assignment (upper)"; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper row-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/column-major sparse matrix multiplication assignment (upper) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix multiplication assignment (upper)"; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 3UL, 3UL, 1UL ); mat(0,2) = 5; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; try { diag *= mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment of upper column-major matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Column-major/row-major sparse matrix multiplication assignment (DiagonalMatrix) { test_ = "Column-major/row-major DiagonalMatrix sparse matrix multiplication assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::rowMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } // Column-major/column-major sparse matrix multiplication assignment (DiagonalMatrix) { test_ = "Column-major/column-major DiagonalMatrix sparse matrix multiplication assignment (DiagonalMatrix)"; blaze::DiagonalMatrix< blaze::CompressedMatrix<int,blaze::columnMajor> > diag1( 3UL, 3UL ); diag1(0,0) = 2; diag1(1,1) = 2; diag1(2,2) = 2; ODT diag2( 3UL ); diag2(0,0) = 1; diag2(1,1) = 2; diag2(2,2) = 3; diag2 *= diag1; checkRows ( diag2, 3UL ); checkColumns ( diag2, 3UL ); checkCapacity( diag2, 9UL ); checkNonZeros( diag2, 3UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); checkNonZeros( diag2, 2UL, 1UL ); if( diag2(0,0) != 2 || diag2(0,1) != 0 || diag2(0,2) != 0 || diag2(1,0) != 0 || diag2(1,1) != 4 || diag2(1,2) != 0 || diag2(2,0) != 0 || diag2(2,1) != 0 || diag2(2,2) != 6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Multiplication assignment failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 2 0 0 )\n( 0 4 0 )\n( 0 0 6 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of all DiagonalMatrix (self-)scaling operations. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of all available ways to scale an instance of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testScaling() { //===================================================================================== // Row-major self-scaling (M*=s) //===================================================================================== { test_ = "Row-major self-scaling (M*=s)"; DT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; diag *= 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major self-scaling (M=M*s) //===================================================================================== { test_ = "Row-major self-scaling (M=M*s)"; DT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; diag = diag * 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major self-scaling (M=s*M) //===================================================================================== { test_ = "Row-major self-scaling (M=s*M)"; DT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; diag = 2 * diag; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major self-scaling (M/=s) //===================================================================================== { test_ = "Row-major self-scaling (M/=s)"; DT diag( 3UL ); diag(1,1) = 4; diag(2,2) = -6; diag /= 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major self-scaling (M=M/s) //===================================================================================== { test_ = "Row-major self-scaling (M=M/s)"; DT diag( 3UL ); diag(1,1) = 4; diag(2,2) = -6; diag = diag / 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major DiagonalMatrix::scale() //===================================================================================== { test_ = "Row-major DiagonalMatrix::scale()"; // Initialization check DT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } // Integral scaling of the matrix diag.scale( 2 ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Scale operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } // Floating point scaling of the matrix diag.scale( 0.5 ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Row-major DiagonalMatrix::scale() (complex)"; using blaze::complex; blaze::DiagonalMatrix< blaze::DynamicMatrix<complex<float>,blaze::rowMajor> > diag( 2UL ); diag(0,0) = complex<float>( 1.0F, 0.0F ); diag(1,1) = complex<float>( 2.0F, 0.0F ); diag.scale( complex<float>( 3.0F, 0.0F ) ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); if( diag(0,0) != complex<float>( 3.0F, 0.0F ) || diag(0,1) != complex<float>( 0.0F, 0.0F ) || diag(1,0) != complex<float>( 0.0F, 0.0F ) || diag(1,1) != complex<float>( 6.0F, 0.0F ) ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Scale operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( (3,0) (0,0)\n(0,0) (6,0) )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major self-scaling (M*=s) //===================================================================================== { test_ = "Column-major self-scaling (M*=s)"; ODT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; diag *= 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major self-scaling (M=M*s) //===================================================================================== { test_ = "Column-major self-scaling (M=M*s)"; ODT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; diag = diag * 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major self-scaling (M=s*M) //===================================================================================== { test_ = "Column-major self-scaling (M=s*M)"; ODT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; diag = 2 * diag; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major self-scaling (M/=s) //===================================================================================== { test_ = "Column-major self-scaling (M/=s)"; ODT diag( 3UL ); diag(1,1) = 4; diag(2,2) = -6; diag /= 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major self-scaling (M=M/s) //===================================================================================== { test_ = "Column-major self-scaling (M=M/s)"; ODT diag( 3UL ); diag(1,1) = 4; diag(2,2) = -6; diag = diag / 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed self-scaling operation\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major DiagonalMatrix::scale() //===================================================================================== { test_ = "Column-major DiagonalMatrix::scale()"; // Initialization check ODT diag( 3UL ); diag(1,1) = 2; diag(2,2) = -3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } // Integral scaling of the matrix diag.scale( 2 ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 4 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Scale operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 4 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } // Floating point scaling of the matrix diag.scale( 0.5 ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 2 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } } { test_ = "Column-major DiagonalMatrix::scale() (complex)"; using blaze::complex; blaze::DiagonalMatrix< blaze::DynamicMatrix<complex<float>,blaze::columnMajor> > diag( 2UL ); diag(0,0) = complex<float>( 1.0F, 0.0F ); diag(1,1) = complex<float>( 2.0F, 0.0F ); diag.scale( complex<float>( 3.0F, 0.0F ) ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); if( diag(0,0) != complex<float>( 3.0F, 0.0F ) || diag(0,1) != complex<float>( 0.0F, 0.0F ) || diag(1,0) != complex<float>( 0.0F, 0.0F ) || diag(1,1) != complex<float>( 6.0F, 0.0F ) ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Scale operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( (3,0) (0,0)\n(0,0) (6,0) )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the DiagonalMatrix function call operator. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of adding and accessing elements via the function call operator // of the DiagonalMatrix specialization. In case an error is detected, a \a std::runtime_error // exception is thrown. */ void DenseTest::testFunctionCall() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix::operator()"; DT diag( 3UL ); // Writing the element (1,1) diag(1,1) = 1; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 1UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 1 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } // Writing the element (2,2) diag(2,2) = 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 1 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Adding to the element (0,0) diag(0,0) += 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 1 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Subtracting from the element (1,1) diag(1,1) -= 4; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -3 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 -3 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Multiplying the element (2,2) diag(2,2) *= -3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -3 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 -3 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } // Dividing the element (2,2) diag(2,2) /= 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -3 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 -3 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } // Trying to write the element (2,1) try { diag(2,1) = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} // Trying to write the element (1,2) try { diag(1,2) = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix::operator()"; ODT diag( 3UL ); // Writing the element (1,1) diag(1,1) = 1; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 1UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 1 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } // Writing the element (2,2) diag(2,2) = 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 1 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Adding to the element (0,0) diag(0,0) += 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 1 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Subtracting from the element (1,1) diag(1,1) -= 4; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -3 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 -3 0 )\n( 0 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Multiplying the element (2,2) diag(2,2) *= -3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -3 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -6 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 -3 0 )\n( 0 0 -6 )\n"; throw std::runtime_error( oss.str() ); } // Dividing the element (2,2) diag(2,2) /= 2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 3 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -3 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 3 0 0 )\n( 0 -3 0 )\n( 0 0 -3 )\n"; throw std::runtime_error( oss.str() ); } // Trying to write the element (2,1) try { diag(2,1) = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} // Trying to write the element (1,2) try { diag(1,2) = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the DiagonalMatrix iterator implementation. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the iterator implementation of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testIterator() { //===================================================================================== // Row-major matrix tests //===================================================================================== { typedef DT::Iterator Iterator; typedef DT::ConstIterator ConstIterator; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = -2; diag(2,2) = 3; // Testing conversion from Iterator to ConstIterator { test_ = "Row-major Iterator/ConstIterator conversion"; ConstIterator it( begin( diag, 1UL ) ); if( it == end( diag, 1UL ) || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed iterator conversion detected\n"; throw std::runtime_error( oss.str() ); } } // Counting the number of elements in 0th row via Iterator { test_ = "Row-major Iterator subtraction"; const size_t number( end( diag, 0UL ) - begin( diag, 0UL ) ); if( number != 3UL ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid number of elements detected\n" << " Details:\n" << " Number of elements : " << number << "\n" << " Expected number of elements: 3\n"; throw std::runtime_error( oss.str() ); } } // Counting the number of elements in 1st row via ConstIterator { test_ = "Row-major ConstIterator subtraction"; const size_t number( cend( diag, 1UL ) - cbegin( diag, 1UL ) ); if( number != 3UL ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid number of elements detected\n" << " Details:\n" << " Number of elements : " << number << "\n" << " Expected number of elements: 3\n"; throw std::runtime_error( oss.str() ); } } // Testing read-only access via ConstIterator { test_ = "Row-major read-only access via ConstIterator"; ConstIterator it ( cbegin( diag, 2UL ) ); ConstIterator end( cend( diag, 2UL ) ); if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid initial iterator detected\n"; throw std::runtime_error( oss.str() ); } ++it; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator pre-increment failed\n"; throw std::runtime_error( oss.str() ); } --it; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator pre-decrement failed\n"; throw std::runtime_error( oss.str() ); } it++; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator post-increment failed\n"; throw std::runtime_error( oss.str() ); } it--; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator post-decrement failed\n"; throw std::runtime_error( oss.str() ); } it += 2UL; if( it == end || *it != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator addition assignment failed\n"; throw std::runtime_error( oss.str() ); } it -= 2UL; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator subtraction assignment failed\n"; throw std::runtime_error( oss.str() ); } it = it + 2UL; if( it == end || *it != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator/scalar addition failed\n"; throw std::runtime_error( oss.str() ); } it = it - 2UL; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator/scalar subtraction failed\n"; throw std::runtime_error( oss.str() ); } it = 3UL + it; if( it != end ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Scalar/iterator addition failed\n"; throw std::runtime_error( oss.str() ); } } // Testing assignment to diagonal elements via Iterator { test_ = "Row-major assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 0UL ); *it = 4; if( diag(0,0) != 4 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 4 0 0 )\n( 0 -2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Testing assignment to lower elements via Iterator { test_ = "Row-major assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 1UL ); *it = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing assignment to upper elements via Iterator { test_ = "Row-major assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 1UL; *it = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing addition assignment to diagonal elements via Iterator { test_ = "Row-major addition assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 1UL ) + 1UL; *it += 3; if( diag(0,0) != 4 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 4 0 0 )\n( 0 1 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Testing addition assignment to lower elements via Iterator { test_ = "Row-major addition assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 2UL ); *it += 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing addition assignment to upper elements via Iterator { test_ = "Row-major addition assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 2UL; *it += 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing subtraction assignment to diagonal elements via Iterator { test_ = "Row-major subtraction assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 2UL ) + 2UL; *it -= 4; if( diag(0,0) != 4 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -1 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 4 0 0 )\n( 0 1 0 )\n( 0 0 -1 )\n"; throw std::runtime_error( oss.str() ); } } // Testing subtraction assignment to lower elements via Iterator { test_ = "Row-major subtraction assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 2UL ) + 1UL; *it += 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing subtraction assignment to upper elements via Iterator { test_ = "Row-major subtraction assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 1UL ) + 2UL; *it -= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing multiplication assignment to diagonal elements via Iterator { test_ = "Row-major multiplication assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 0UL ); *it *= 2; if( diag(0,0) != 8 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -1 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 8 0 0 )\n( 0 1 0 )\n( 0 0 -1 )\n"; throw std::runtime_error( oss.str() ); } } // Testing multiplication assignment to lower elements via Iterator { test_ = "Row-major multiplication assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 1UL ); *it *= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing multiplication assignment to upper elements via Iterator { test_ = "Row-major multiplication assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 1UL; *it *= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing division assignment to diagonal elements via Iterator { test_ = "Row-major division assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 0UL ); *it /= 4; if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -1 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 1 0 )\n( 0 0 -1 )\n"; throw std::runtime_error( oss.str() ); } } // Testing division assignment to lower elements via Iterator { test_ = "Row-major division assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 2UL ); *it /= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing division assignment to upper elements via Iterator { test_ = "Row-major division assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 2UL; *it /= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } } //===================================================================================== // Column-major matrix tests //===================================================================================== { typedef ODT::Iterator Iterator; typedef ODT::ConstIterator ConstIterator; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = -2; diag(2,2) = 3; // Testing conversion from Iterator to ConstIterator { test_ = "Row-major Iterator/ConstIterator conversion"; ConstIterator it( begin( diag, 1UL ) ); if( it == end( diag, 1UL ) || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Failed iterator conversion detected\n"; throw std::runtime_error( oss.str() ); } } // Counting the number of elements in 0th row via Iterator { test_ = "Row-major Iterator subtraction"; const size_t number( end( diag, 0UL ) - begin( diag, 0UL ) ); if( number != 3UL ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid number of elements detected\n" << " Details:\n" << " Number of elements : " << number << "\n" << " Expected number of elements: 3\n"; throw std::runtime_error( oss.str() ); } } // Counting the number of elements in 1st row via ConstIterator { test_ = "Row-major ConstIterator subtraction"; const size_t number( cend( diag, 1UL ) - cbegin( diag, 1UL ) ); if( number != 3UL ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid number of elements detected\n" << " Details:\n" << " Number of elements : " << number << "\n" << " Expected number of elements: 3\n"; throw std::runtime_error( oss.str() ); } } // Testing read-only access via ConstIterator { test_ = "Row-major read-only access via ConstIterator"; ConstIterator it ( cbegin( diag, 2UL ) ); ConstIterator end( cend( diag, 2UL ) ); if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid initial iterator detected\n"; throw std::runtime_error( oss.str() ); } ++it; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator pre-increment failed\n"; throw std::runtime_error( oss.str() ); } --it; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator pre-decrement failed\n"; throw std::runtime_error( oss.str() ); } it++; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator post-increment failed\n"; throw std::runtime_error( oss.str() ); } it--; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator post-decrement failed\n"; throw std::runtime_error( oss.str() ); } it += 2UL; if( it == end || *it != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator addition assignment failed\n"; throw std::runtime_error( oss.str() ); } it -= 2UL; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator subtraction assignment failed\n"; throw std::runtime_error( oss.str() ); } it = it + 2UL; if( it == end || *it != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator/scalar addition failed\n"; throw std::runtime_error( oss.str() ); } it = it - 2UL; if( it == end || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator/scalar subtraction failed\n"; throw std::runtime_error( oss.str() ); } it = 3UL + it; if( it != end ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Scalar/iterator addition failed\n"; throw std::runtime_error( oss.str() ); } } // Testing assignment to diagonal elements via Iterator { test_ = "Row-major assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 0UL ); *it = 4; if( diag(0,0) != 4 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 4 0 0 )\n( 0 -2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Testing assignment to lower elements via Iterator { test_ = "Row-major assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 1UL ); *it = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing assignment to upper elements via Iterator { test_ = "Row-major assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 1UL; *it = 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing addition assignment to diagonal elements via Iterator { test_ = "Row-major addition assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 1UL ) + 1UL; *it += 3; if( diag(0,0) != 4 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 4 0 0 )\n( 0 1 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // Testing addition assignment to lower elements via Iterator { test_ = "Row-major addition assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 2UL ); *it += 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing addition assignment to upper elements via Iterator { test_ = "Row-major addition assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 2UL; *it += 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing subtraction assignment to diagonal elements via Iterator { test_ = "Row-major subtraction assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 2UL ) + 2UL; *it -= 4; if( diag(0,0) != 4 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -1 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 4 0 0 )\n( 0 1 0 )\n( 0 0 -1 )\n"; throw std::runtime_error( oss.str() ); } } // Testing subtraction assignment to lower elements via Iterator { test_ = "Row-major subtraction assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 2UL ) + 1UL; *it += 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing subtraction assignment to upper elements via Iterator { test_ = "Row-major subtraction assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 1UL ) + 2UL; *it -= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing multiplication assignment to diagonal elements via Iterator { test_ = "Row-major multiplication assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 0UL ); *it *= 2; if( diag(0,0) != 8 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -1 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 8 0 0 )\n( 0 1 0 )\n( 0 0 -1 )\n"; throw std::runtime_error( oss.str() ); } } // Testing multiplication assignment to lower elements via Iterator { test_ = "Row-major multiplication assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 1UL ); *it *= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing multiplication assignment to upper elements via Iterator { test_ = "Row-major multiplication assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 1UL; *it *= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing division assignment to diagonal elements via Iterator { test_ = "Row-major division assignment to diagonal elements via Iterator"; const Iterator it = begin( diag, 0UL ); *it /= 4; if( diag(0,0) != 2 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 1 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != -1 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment via iterator failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 2 0 0 )\n( 0 1 0 )\n( 0 0 -1 )\n"; throw std::runtime_error( oss.str() ); } } // Testing division assignment to lower elements via Iterator { test_ = "Row-major division assignment to lower elements via Iterator"; try { const Iterator it = begin( diag, 2UL ); *it /= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to lower matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // Testing division assignment to upper elements via Iterator { test_ = "Row-major division assignment to upper elements via Iterator"; try { const Iterator it = begin( diag, 0UL ) + 2UL; *it /= 5; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to upper matrix element succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c nonZeros() member function of the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c nonZeros() member function of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testNonZeros() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix::nonZeros()"; // Empty matrix { DT diag( 3UL ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 0UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Partially filled matrix { DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = -2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 -2 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Fully filled matrix { DT diag( 3UL ); diag(0,0) = -1; diag(1,1) = 2; diag(2,2) = 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != -1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( -1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix::nonZeros()"; // Empty matrix { ODT diag( 3UL ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 0UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Partially filled matrix { ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = -2; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 -2 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } // Fully filled matrix { ODT diag( 3UL ); diag(0,0) = -1; diag(1,1) = 2; diag(2,2) = 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != -1 || diag(0,1) != 0 || diag(0,2) != 0 ||<|fim▁hole|> diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( -1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c reset() member function of the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c reset() member function of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testReset() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix::reset()"; // Initialization check DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting a diagonal element reset( diag(1,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting a lower element reset( diag(1,0) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting an upper element reset( diag(0,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting row 2 reset( diag, 2UL ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 1UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } // Resetting the entire matrix reset( diag ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 0UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix::reset()"; // Initialization check ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting a diagonal element reset( diag(1,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting a lower element reset( diag(1,0) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting an upper element reset( diag(0,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Resetting row 2 reset( diag, 2UL ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 1UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } // Resetting the entire matrix reset( diag ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 0UL ); checkNonZeros( diag, 0UL, 0UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 0UL ); if( diag(0,0) != 0 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Reset operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c clear() member function of the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c clear() member function of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testClear() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix::clear()"; // Initialization check DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing a diagonal element clear( diag(1,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Clear operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing a lower element clear( diag(1,0) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Clear operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing an upper element clear( diag(0,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Clear operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing the matrix clear( diag ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix::clear()"; // Initialization check ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Initialization failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 2 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing a diagonal element clear( diag(1,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Clear operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing a lower element clear( diag(1,0) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Clear operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing an upper element clear( diag(0,1) ); checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkCapacity( diag, 9UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 0UL ); checkNonZeros( diag, 2UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Clear operation failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } // Clearing the matrix clear( diag ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c resize() member function of the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c resize() member function of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testResize() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix::resize()"; // Initialization check DT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); // Resizing to 2x2 diag.resize( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); if( diag(0,1) != 0 || diag(1,0) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Resizing the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( x 0 )\n( 0 x )\n"; throw std::runtime_error( oss.str() ); } // Resizing to 4x4 and preserving the elements diag(0,0) = 1; diag(1,1) = 2; diag.resize( 4UL, true ); checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkCapacity( diag, 16UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Resizing the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n( 0 2 0 0 )\n( 0 0 x 0 )\n( 0 0 0 x )\n"; throw std::runtime_error( oss.str() ); } // Resizing to 2x2 diag(2,2) = 3; diag.resize( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(1,0) != 0 || diag(1,1) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Resizing the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 )\n( 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Resizing to 0x0 diag.resize( 0UL ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix::resize()"; // Initialization check ODT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); // Resizing to 2x2 diag.resize( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); if( diag(0,1) != 0 || diag(1,0) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Resizing the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( x 0 )\n( 0 x )\n"; throw std::runtime_error( oss.str() ); } // Resizing to 4x4 and preserving the elements diag(0,0) = 1; diag(1,1) = 2; diag.resize( 4UL, true ); checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkCapacity( diag, 16UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Resizing the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n( 0 2 0 0 )\n( 0 0 x 0 )\n( 0 0 0 x )\n"; throw std::runtime_error( oss.str() ); } // Resizing to 2x2 diag(2,2) = 3; diag.resize( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); checkNonZeros( diag, 2UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(1,0) != 0 || diag(1,1) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Resizing the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 )\n( 0 2 )\n"; throw std::runtime_error( oss.str() ); } // Resizing to 0x0 diag.resize( 0UL ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c extend() member function of the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c extend() member function of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testExtend() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix::extend()"; // Initialization check DT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); // Extending the size of the matrix to 2x2 diag.extend( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); if( diag(0,1) != 0 || diag(1,0) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Extending the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( x 0 )\n( 0 x )\n"; throw std::runtime_error( oss.str() ); } // Extending to 4x4 and preserving the elements diag(0,0) = 1; diag(1,1) = 2; diag.extend( 2UL, true ); checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkCapacity( diag, 16UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Extending the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n( 0 2 0 0 )\n( 0 0 x 0 )\n( 0 0 0 x )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix::extend()"; // Initialization check ODT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); // Extending the size of the matrix to 2x2 diag.extend( 2UL ); checkRows ( diag, 2UL ); checkColumns ( diag, 2UL ); checkCapacity( diag, 4UL ); if( diag(0,1) != 0 || diag(1,0) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Extending the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( x 0 )\n( 0 x )\n"; throw std::runtime_error( oss.str() ); } // Extending to 4x4 and preserving the elements diag(0,0) = 1; diag(1,1) = 2; diag.extend( 2UL, true ); checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkCapacity( diag, 16UL ); if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Extending the matrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n( 0 2 0 0 )\n( 0 0 x 0 )\n( 0 0 0 x )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c reserve() member function of the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c reserve() member function of the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testReserve() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix::reserve()"; // Initialization check DT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); // Increasing the capacity of the matrix diag.reserve( 10UL ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkCapacity( diag, 10UL ); checkNonZeros( diag, 0UL ); // Further increasing the capacity of the matrix diag.reserve( 20UL ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkCapacity( diag, 20UL ); checkNonZeros( diag, 0UL ); } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix::reserve()"; // Initialization check ODT diag; checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkNonZeros( diag, 0UL ); // Increasing the capacity of the matrix diag.reserve( 10UL ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkCapacity( diag, 10UL ); checkNonZeros( diag, 0UL ); // Further increasing the capacity of the matrix diag.reserve( 20UL ); checkRows ( diag, 0UL ); checkColumns ( diag, 0UL ); checkCapacity( diag, 20UL ); checkNonZeros( diag, 0UL ); } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c swap() functionality of the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c swap() function of the DiagonalMatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testSwap() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major DiagonalMatrix swap"; DT diag1( 2UL ); diag1(0,0) = 1; diag1(1,1) = 2; DT diag2( 3UL ); diag2(0,0) = 3; diag2(1,1) = 4; diag2(2,2) = 5; swap( diag1, diag2 ); checkRows ( diag1, 3UL ); checkColumns ( diag1, 3UL ); checkCapacity( diag1, 9UL ); checkNonZeros( diag1, 3UL ); checkNonZeros( diag1, 0UL, 1UL ); checkNonZeros( diag1, 1UL, 1UL ); checkNonZeros( diag1, 2UL, 1UL ); if( diag1(0,0) != 3 || diag1(0,1) != 0 || diag1(0,2) != 0 || diag1(1,0) != 0 || diag1(1,1) != 4 || diag1(1,2) != 0 || diag1(2,0) != 0 || diag1(2,1) != 0 || diag1(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Swapping the first matrix failed\n" << " Details:\n" << " Result:\n" << diag1 << "\n" << " Expected result:\n( 3 0 0 )\n( 0 4 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } checkRows ( diag2, 2UL ); checkColumns ( diag2, 2UL ); checkCapacity( diag2, 4UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Swapping the second matrix failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 )\n( 0 2 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major DiagonalMatrix swap"; ODT diag1( 2UL ); diag1(0,0) = 1; diag1(1,1) = 2; ODT diag2( 3UL ); diag2(0,0) = 3; diag2(1,1) = 4; diag2(2,2) = 5; swap( diag1, diag2 ); checkRows ( diag1, 3UL ); checkColumns ( diag1, 3UL ); checkCapacity( diag1, 9UL ); checkNonZeros( diag1, 3UL ); checkNonZeros( diag1, 0UL, 1UL ); checkNonZeros( diag1, 1UL, 1UL ); checkNonZeros( diag1, 2UL, 1UL ); if( diag1(0,0) != 3 || diag1(0,1) != 0 || diag1(0,2) != 0 || diag1(1,0) != 0 || diag1(1,1) != 4 || diag1(1,2) != 0 || diag1(2,0) != 0 || diag1(2,1) != 0 || diag1(2,2) != 5 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Swapping the first matrix failed\n" << " Details:\n" << " Result:\n" << diag1 << "\n" << " Expected result:\n( 3 0 0 )\n( 0 4 0 )\n( 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } checkRows ( diag2, 2UL ); checkColumns ( diag2, 2UL ); checkCapacity( diag2, 4UL ); checkNonZeros( diag2, 2UL ); checkNonZeros( diag2, 0UL, 1UL ); checkNonZeros( diag2, 1UL, 1UL ); if( diag2(0,0) != 1 || diag2(0,1) != 0 || diag2(1,0) != 0 || diag2(1,1) != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Swapping the second matrix failed\n" << " Details:\n" << " Result:\n" << diag2 << "\n" << " Expected result:\n( 1 0 )\n( 0 2 )\n"; throw std::runtime_error( oss.str() ); } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c isDefault() function with the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c isDefault() function with the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testIsDefault() { //===================================================================================== // Row-major matrix tests //===================================================================================== { test_ = "Row-major isDefault() function"; // isDefault with 0x0 matrix { DT diag; if( isDefault( diag ) != true ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } } // isDefault with default matrix { DT diag( 3UL ); if( isDefault( diag(1,1) ) != true ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix element:\n" << diag(1,1) << "\n"; throw std::runtime_error( oss.str() ); } if( isDefault( diag ) != false ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } } // isDefault with non-default matrix { DT diag( 3UL ); diag(1,1) = 1; if( isDefault( diag(1,1) ) != false ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix element:\n" << diag(1,1) << "\n"; throw std::runtime_error( oss.str() ); } if( isDefault( diag ) != false ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } } } //===================================================================================== // Column-major matrix tests //===================================================================================== { test_ = "Column-major isDefault() function"; // isDefault with 0x0 matrix { ODT diag; if( isDefault( diag ) != true ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } } // isDefault with default matrix { ODT diag( 3UL ); if( isDefault( diag(1,1) ) != true ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix element:\n" << diag(1,1) << "\n"; throw std::runtime_error( oss.str() ); } if( isDefault( diag ) != false ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } } // isDefault with non-default matrix { ODT diag( 3UL ); diag(1,1) = 1; if( isDefault( diag(1,1) ) != false ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix element:\n" << diag(1,1) << "\n"; throw std::runtime_error( oss.str() ); } if( isDefault( diag ) != false ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Invalid isDefault evaluation\n" << " Details:\n" << " Matrix:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } } } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c submatrix() function with the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c submatrix() function with the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testSubmatrix() { //===================================================================================== // Row-major general tests //===================================================================================== { test_ = "Row-major submatrix() function"; typedef blaze::DenseSubmatrix<DT> SMT; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); if( sm(1,1) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator access failed\n" << " Details:\n" << " Result: " << sm(1,1) << "\n" << " Expected result: 3\n"; throw std::runtime_error( oss.str() ); } SMT::Iterator it = sm.begin(0UL); if( it == sm.end(0UL) || *it != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator access failed\n" << " Details:\n" << " Result: " << *it << "\n" << " Expected result: 2\n"; throw std::runtime_error( oss.str() ); } sm(0,0) = -5; if( sm(0,0) != -5 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix access failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( -5 0 )\n( 0 3 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -5 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 -5 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } reset( sm ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix reset failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major scalar assignment //===================================================================================== // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 12 0 0 ) // ( 0 0 3 0 ) ( 0 0 12 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (scalar assignment test 1)"; typedef blaze::DenseSubmatrix<DT> SMT; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 12 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 12 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 12 0 )\n( 0 12 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 12 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 12 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 12 0 0 )\n" "( 0 0 12 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 12 0 0 ) // ( 0 0 3 0 ) ( 0 0 12 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (scalar assignment test 2)"; typedef blaze::DenseSubmatrix<DT> SMT; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 12 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 12 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 12 0 0 )\n( 0 0 12 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 12 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 12 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 12 0 0 )\n" "( 0 0 12 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 2 0 0 ) // ( 0 0 3 0 ) ( 0 0 3 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (scalar assignment test 3)"; typedef blaze::DenseSubmatrix<DT> SMT; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 2UL, 2UL, 2UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 2 0 0 )\n" "( 0 0 3 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 2 0 0 ) // ( 0 0 3 0 ) ( 0 0 3 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (scalar assignment test 4)"; typedef blaze::DenseSubmatrix<DT> SMT; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 2UL, 0UL, 2UL, 2UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 2 0 0 )\n" "( 0 0 3 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense matrix assignment //===================================================================================== // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (row-major dense matrix assignment test 1)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 4UL, 2UL, 0 ); mat(1,0) = 18; mat(2,1) = 11; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (row-major dense matrix assignment test 2)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 2UL, 4UL, 0 ); mat(0,1) = 18; mat(1,2) = 11; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 1 5 ) ( 0 0 0 5 ) { test_ = "Row-major submatrix() function (row-major dense matrix assignment test 3)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 1 5 ) ( 0 0 0 5 ) { test_ = "Row-major submatrix() function (row-major dense matrix assignment test 4)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major dense matrix assignment test 1)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 4UL, 2UL, 0 ); mat(1,0) = 18; mat(2,1) = 11; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major dense matrix assignment test 2)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 2UL, 4UL, 0 ); mat(0,1) = 18; mat(1,2) = 11; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major dense matrix assignment test 3)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major dense matrix assignment test 4)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Row-major sparse matrix assignment //===================================================================================== // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (row-major sparse matrix assignment test 1)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 4UL, 2UL, 4UL ); mat(1,0) = 18; mat(2,1) = 11; mat.insert( 1UL, 1UL, 0 ); mat.insert( 2UL, 0UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (row-major sparse matrix assignment test 2)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 2UL, 4UL, 4UL ); mat(0,1) = 18; mat(1,2) = 11; mat.insert( 0UL, 2UL, 0 ); mat.insert( 1UL, 1UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (row-major sparse matrix assignment test 3)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; mat.insert( 1UL, 0UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (row-major sparse matrix assignment test 4)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; mat.insert( 0UL, 1UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major sparse matrix assignment test 1)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 4UL, 2UL, 4UL ); mat(1,0) = 18; mat(2,1) = 11; mat.insert( 1UL, 1UL, 0 ); mat.insert( 2UL, 0UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major sparse matrix assignment test 2)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 2UL, 4UL, 4UL ); mat(0,1) = 18; mat(1,2) = 11; mat.insert( 0UL, 2UL, 0 ); mat.insert( 1UL, 1UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major sparse matrix assignment test 3)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; mat.insert( 1UL, 0UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Row-major submatrix() function (column-major sparse matrix assignment test 4)"; typedef blaze::DenseSubmatrix<DT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; mat.insert( 0UL, 1UL, 0 ); DT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Column-major general tests //===================================================================================== { test_ = "Column-major submatrix() function"; typedef blaze::DenseSubmatrix<ODT> SMT; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); if( sm(1,1) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator access failed\n" << " Details:\n" << " Result: " << sm(1,1) << "\n" << " Expected result: 3\n"; throw std::runtime_error( oss.str() ); } SMT::Iterator it = sm.begin(0UL); if( it == sm.end(0UL) || *it != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator access failed\n" << " Details:\n" << " Result: " << *it << "\n" << " Expected result: 2\n"; throw std::runtime_error( oss.str() ); } sm(0,0) = -5; if( sm(0,0) != -5 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix access failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( -5 0 )\n( 0 3 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -5 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 -5 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } reset( sm ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix reset failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Submatrix reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major scalar assignment //===================================================================================== // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 12 0 0 ) // ( 0 0 3 0 ) ( 0 0 12 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (scalar assignment test 1)"; typedef blaze::DenseSubmatrix<ODT> SMT; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 12 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 12 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 12 0 )\n( 0 12 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 12 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 12 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 12 0 0 )\n" "( 0 0 12 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 12 0 0 ) // ( 0 0 3 0 ) ( 0 0 12 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (scalar assignment test 2)"; typedef blaze::DenseSubmatrix<ODT> SMT; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 12 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 12 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 12 0 0 )\n( 0 0 12 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 12 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 12 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 12 0 0 )\n" "( 0 0 12 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 2 0 0 ) // ( 0 0 3 0 ) ( 0 0 3 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (scalar assignment test 3)"; typedef blaze::DenseSubmatrix<ODT> SMT; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 2UL, 2UL, 2UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 2 0 0 )\n" "( 0 0 3 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 2 0 0 ) // ( 0 0 3 0 ) ( 0 0 3 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (scalar assignment test 4)"; typedef blaze::DenseSubmatrix<ODT> SMT; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 2UL, 0UL, 2UL, 2UL ); sm = 12; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 0 || sm(1,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 2 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 2 0 0 )\n" "( 0 0 3 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense matrix assignment //===================================================================================== // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (row-major dense matrix assignment test 1)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 4UL, 2UL, 0 ); mat(1,0) = 18; mat(2,1) = 11; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (row-major dense matrix assignment test 2)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 2UL, 4UL, 0 ); mat(0,1) = 18; mat(1,2) = 11; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 1 5 ) ( 0 0 0 5 ) { test_ = "Column-major submatrix() function (row-major dense matrix assignment test 3)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 1 5 ) ( 0 0 0 5 ) { test_ = "Column-major submatrix() function (row-major dense matrix assignment test 4)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major dense matrix assignment test 1)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 4UL, 2UL, 0 ); mat(1,0) = 18; mat(2,1) = 11; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 5 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major dense matrix assignment test 2)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 2UL, 4UL, 0 ); mat(0,1) = 18; mat(1,2) = 11; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major dense matrix assignment test 3)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major dense matrix assignment test 4)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::DynamicMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 0 ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Column-major sparse matrix assignment //===================================================================================== // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (row-major sparse matrix assignment test 1)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 4UL, 2UL, 4UL ); mat(1,0) = 18; mat(2,1) = 11; mat.insert( 1UL, 1UL, 0 ); mat.insert( 2UL, 0UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (row-major sparse matrix assignment test 2)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 2UL, 4UL, 4UL ); mat(0,1) = 18; mat(1,2) = 11; mat.insert( 0UL, 2UL, 0 ); mat.insert( 1UL, 1UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (row-major sparse matrix assignment test 3)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; mat.insert( 1UL, 0UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (row-major sparse matrix assignment test 4)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::rowMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; mat.insert( 0UL, 1UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major sparse matrix assignment test 1)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 4UL, 2UL, 4UL ); mat(1,0) = 18; mat(2,1) = 11; mat.insert( 1UL, 1UL, 0 ); mat.insert( 2UL, 0UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 0UL, 1UL, 4UL, 2UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 0 || sm(1,0) != 18 || sm(1,1) != 0 || sm(2,0) != 0 || sm(2,1) != 11 || sm(3,0) != 0 || sm(3,1) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 0 )\n( 18 0 )\n( 0 11 )\n( 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 18 0 0 ) // ( 0 0 3 0 ) ( 0 0 11 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major sparse matrix assignment test 2)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 2UL, 4UL, 4UL ); mat(0,1) = 18; mat(1,2) = 11; mat.insert( 0UL, 2UL, 0 ); mat.insert( 1UL, 1UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 0UL, 2UL, 4UL ); sm = mat; checkRows ( diag, 4UL ); checkColumns ( diag, 4UL ); checkNonZeros( diag, 4UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); checkNonZeros( diag, 3UL, 1UL ); if( sm(0,0) != 0 || sm(0,1) != 18 || sm(0,2) != 0 || sm(0,3) != 0 || sm(1,0) != 0 || sm(1,1) != 0 || sm(1,2) != 11 || sm(1,3) != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << sm << "\n" << " Expected result:\n( 0 18 0 0 )\n( 0 0 11 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(0,3) != 0 || diag(1,0) != 0 || diag(1,1) != 18 || diag(1,2) != 0 || diag(1,3) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 11 || diag(2,3) != 0 || diag(3,0) != 0 || diag(3,1) != 0 || diag(3,2) != 0 || diag(3,3) != 4 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment to submatrix failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 0 )\n" "( 0 18 0 0 )\n" "( 0 0 11 0 )\n" "( 0 0 0 4 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 12 0 ) // ( 0 0 3 0 ) ( 0 0 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major sparse matrix assignment test 3)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(0,1) = 12; mat(1,1) = 14; mat.insert( 1UL, 0UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 0 ) ( 1 0 0 0 ) // ( 0 2 0 0 ) => ( 0 11 0 0 ) // ( 0 0 3 0 ) ( 0 13 14 0 ) // ( 0 0 0 4 ) ( 0 0 0 4 ) { test_ = "Column-major submatrix() function (column-major sparse matrix assignment test 4)"; typedef blaze::DenseSubmatrix<ODT> SMT; blaze::CompressedMatrix<int,blaze::columnMajor> mat( 2UL, 2UL, 4UL ); mat(0,0) = 11; mat(1,0) = 13; mat(1,1) = 14; mat.insert( 0UL, 1UL, 0 ); ODT diag( 4UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; diag(3,3) = 4; SMT sm = submatrix( diag, 1UL, 1UL, 2UL, 2UL ); try { sm = mat; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid matrix succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c row() function with the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c row() function with the DiagonalMatrix specialization. // In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testRow() { //===================================================================================== // Row-major general tests //===================================================================================== { test_ = "Row-major row() function"; typedef blaze::DenseRow<DT> RT; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); if( row1[1] != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator access failed\n" << " Details:\n" << " Result: " << row1[1] << "\n" << " Expected result: 2\n"; throw std::runtime_error( oss.str() ); } RT::Iterator it = row1.begin(); if( it == row1.end() || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator access failed\n" << " Details:\n" << " Result: " << *it << "\n" << " Expected result: 0\n"; throw std::runtime_error( oss.str() ); } row1[1] = -5; if( row1[0] != 0 || row1[1] != -5 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 -5 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -5 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( -4 -5 0 )\n( 7 0 3 )\n"; throw std::runtime_error( oss.str() ); } reset( row1 ); if( row1[0] != 0 || row1[1] != 0 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major scalar assignment //===================================================================================== { test_ = "Row-major row() function (scalar assignment test)"; typedef blaze::DenseRow<DT> RT; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); row1 = 8; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( row1[0] != 0 || row1[1] != 8 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major row() function (dense vector assignment test 1)"; typedef blaze::DenseRow<DT> RT; blaze::DynamicVector<int,blaze::rowVector> vec( 3UL, 0 ); vec[1] = 8; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); row1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( row1[0] != 0 || row1[1] != 8 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 2 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major row() function (dense vector assignment test 2)"; typedef blaze::DenseRow<DT> RT; blaze::DynamicVector<int,blaze::rowVector> vec( 3UL, 0 ); vec[0] = 2; vec[1] = 8; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 9 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major row() function (dense vector assignment test 3)"; typedef blaze::DenseRow<DT> RT; blaze::DynamicVector<int,blaze::rowVector> vec( 3UL, 0 ); vec[1] = 8; vec[2] = 9; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Row-major sparse vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major row() function (sparse vector assignment test 1)"; typedef blaze::DenseRow<DT> RT; blaze::CompressedVector<int,blaze::rowVector> vec( 3UL, 3UL ); vec[1] = 8; vec.insert( 0UL, 0 ); vec.insert( 2UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); row1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( row1[0] != 0 || row1[1] != 8 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 2 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 2 8 0 ) // ( 0 0 3 ) ( 7 0 3 ) { test_ = "Row-major row() function (sparse vector assignment test 2)"; typedef blaze::DenseRow<DT> RT; blaze::CompressedVector<int,blaze::rowVector> vec( 3UL, 3UL ); vec[0] = 2; vec[1] = 8; vec.insert( 2UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 9 ) // ( 0 0 3 ) ( 7 0 3 ) { test_ = "Row-major row() function (sparse vector assignment test 3)"; typedef blaze::DenseRow<DT> RT; blaze::CompressedVector<int,blaze::rowVector> vec( 3UL, 3UL ); vec[1] = 8; vec[2] = 9; vec.insert( 0UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Column-major general tests //===================================================================================== { test_ = "Column-major row() function"; typedef blaze::DenseRow<ODT> RT; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); if( row1[1] != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator access failed\n" << " Details:\n" << " Result: " << row1[1] << "\n" << " Expected result: 2\n"; throw std::runtime_error( oss.str() ); } RT::Iterator it = row1.begin(); if( it == row1.end() || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator access failed\n" << " Details:\n" << " Result: " << *it << "\n" << " Expected result: 0\n"; throw std::runtime_error( oss.str() ); } row1[1] = -5; if( row1[0] != 0 || row1[1] != -5 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( -4 -5 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -5 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 -5 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } reset( row1 ); if( row1[0] != 0 || row1[1] != 0 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major scalar assignment //===================================================================================== { test_ = "Column-major row() function (scalar assignment test)"; typedef blaze::DenseRow<ODT> RT; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); row1 = 8; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( row1[0] != 0 || row1[1] != 8 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major row() function (dense vector assignment test 1)"; typedef blaze::DenseRow<ODT> RT; blaze::DynamicVector<int,blaze::rowVector> vec( 3UL, 0 ); vec[1] = 8; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); row1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( row1[0] != 0 || row1[1] != 8 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 2 8 0 ) // ( 0 0 3 ) ( 7 0 3 ) { test_ = "Column-major row() function (dense vector assignment test 2)"; typedef blaze::DenseRow<ODT> RT; blaze::DynamicVector<int,blaze::rowVector> vec( 3UL, 0 ); vec[0] = 2; vec[1] = 8; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 9 ) // ( 0 0 3 ) ( 7 0 3 ) { test_ = "Column-major row() function (dense vector assignment test 3)"; typedef blaze::DenseRow<ODT> RT; blaze::DynamicVector<int,blaze::rowVector> vec( 3UL, 0 ); vec[1] = 8; vec[2] = 9; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Column-major sparse vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major row() function (sparse vector assignment test 1)"; typedef blaze::DenseRow<ODT> RT; blaze::CompressedVector<int,blaze::rowVector> vec( 3UL, 3UL ); vec[1] = 8; vec.insert( 0UL, 0 ); vec.insert( 2UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); row1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( row1[0] != 0 || row1[1] != 8 || row1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << row1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Row reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major row() function (sparse vector assignment test 2)"; typedef blaze::DenseRow<ODT> RT; blaze::CompressedVector<int,blaze::rowVector> vec( 3UL, 3UL ); vec[0] = 2; vec[1] = 8; vec.insert( 2UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 9 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major row() function (sparse vector assignment test 3)"; typedef blaze::DenseRow<ODT> RT; blaze::CompressedVector<int,blaze::rowVector> vec( 3UL, 3UL ); vec[1] = 8; vec[2] = 9; vec.insert( 0UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; RT row1 = row( diag, 1UL ); try { row1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } } //************************************************************************************************* //************************************************************************************************* /*!\brief Test of the \c column() function with the DiagonalMatrix specialization. // // \return void // \exception std::runtime_error Error detected. // // This function performs a test of the \c column() function with the DiagonalMatrix // specialization. In case an error is detected, a \a std::runtime_error exception is thrown. */ void DenseTest::testColumn() { //===================================================================================== // Row-major general tests //===================================================================================== { test_ = "Row-major column() function"; typedef blaze::DenseColumn<DT> CT; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); if( col1[1] != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator access failed\n" << " Details:\n" << " Result: " << col1[1] << "\n" << " Expected result: 2\n"; throw std::runtime_error( oss.str() ); } CT::Iterator it = col1.begin(); if( it == col1.end() || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator access failed\n" << " Details:\n" << " Result: " << *it << "\n" << " Expected result: 0\n"; throw std::runtime_error( oss.str() ); } col1[1] = -5; if( col1[0] != 0 || col1[1] != -5 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 -5 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -5 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 -5 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } reset( col1 ); if( col1[0] != 0 || col1[1] != 0 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major scalar assignment //===================================================================================== { test_ = "Row-major column() function (scalar assignment test)"; typedef blaze::DenseColumn<DT> CT; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); col1 = 8; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( col1[0] != 0 || col1[1] != 8 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 8 8 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Row-major dense vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major column() function (dense vector assignment test 1)"; typedef blaze::DenseColumn<DT> CT; blaze::DynamicVector<int,blaze::columnVector> vec( 3UL, 0 ); vec[1] = 8; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); col1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( col1[0] != 0 || col1[1] != 8 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 9 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major column() function (dense vector assignment test 2)"; typedef blaze::DenseColumn<DT> CT; blaze::DynamicVector<int,blaze::columnVector> vec( 3UL, 0 ); vec[0] = 9; vec[1] = 8; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 2 3 ) { test_ = "Row-major column() function (dense vector assignment test 3)"; typedef blaze::DenseColumn<DT> CT; blaze::DynamicVector<int,blaze::columnVector> vec( 3UL, 0 ); vec[1] = 8; vec[2] = 2; DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Row-major sparse vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major column() function (sparse vector assignment test 1)"; typedef blaze::DenseColumn<DT> CT; blaze::CompressedVector<int,blaze::columnVector> vec( 3UL, 3UL ); vec[1] = 8; vec.insert( 0UL, 0 ); vec.insert( 2UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); col1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( col1[0] != 0 || col1[1] != 8 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 9 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Row-major column() function (sparse vector assignment test 2)"; typedef blaze::DenseColumn<DT> CT; blaze::CompressedVector<int,blaze::columnVector> vec( 3UL, 3UL ); vec[0] = 9; vec[1] = 8; vec.insert( 2UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 2 3 ) { test_ = "Row-major column() function (sparse vector assignment test 3)"; typedef blaze::DenseColumn<DT> CT; blaze::CompressedVector<int,blaze::columnVector> vec( 3UL, 3UL ); vec[1] = 8; vec[2] = 2; vec.insert( 0UL, 0 ); DT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Column-major general tests //===================================================================================== { test_ = "Column-major column() function"; typedef blaze::DenseColumn<ODT> CT; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); if( col1[1] != 2 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Function call operator access failed\n" << " Details:\n" << " Result: " << col1[1] << "\n" << " Expected result: 2\n"; throw std::runtime_error( oss.str() ); } CT::Iterator it = col1.begin(); if( it == col1.end() || *it != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Iterator access failed\n" << " Details:\n" << " Result: " << *it << "\n" << " Expected result: 0\n"; throw std::runtime_error( oss.str() ); } col1[1] = -5; if( col1[0] != 0 || col1[1] != -5 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 -5 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != -5 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 -5 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } reset( col1 ); if( col1[0] != 0 || col1[1] != 0 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 0 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 0 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 0 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major scalar assignment //===================================================================================== { test_ = "Column-major column() function (scalar assignment test)"; typedef blaze::DenseColumn<ODT> CT; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); col1 = 8; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( col1[0] != 0 || col1[1] != 8 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column access failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } //===================================================================================== // Column-major dense vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major column() function (dense vector assignment test 1)"; typedef blaze::DenseColumn<ODT> CT; blaze::DynamicVector<int,blaze::columnVector> vec( 3UL, 0 ); vec[1] = 8; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); col1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( col1[0] != 0 || col1[1] != 8 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 9 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major column() function (dense vector assignment test 2)"; typedef blaze::DenseColumn<ODT> CT; blaze::DynamicVector<int,blaze::columnVector> vec( 3UL, 0 ); vec[0] = 9; vec[1] = 8; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 2 3 ) { test_ = "Column-major column() function (dense vector assignment test 3)"; typedef blaze::DenseColumn<ODT> CT; blaze::DynamicVector<int,blaze::columnVector> vec( 3UL, 0 ); vec[1] = 8; vec[2] = 2; ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } //===================================================================================== // Column-major sparse vector assignment //===================================================================================== // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major column() function (sparse vector assignment test 1)"; typedef blaze::DenseColumn<ODT> CT; blaze::CompressedVector<int,blaze::columnVector> vec( 3UL, 3UL ); vec[1] = 8; vec.insert( 0UL, 0 ); vec.insert( 2UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); col1 = vec; checkRows ( diag, 3UL ); checkColumns ( diag, 3UL ); checkNonZeros( diag, 3UL ); checkNonZeros( diag, 0UL, 1UL ); checkNonZeros( diag, 1UL, 1UL ); checkNonZeros( diag, 2UL, 1UL ); if( col1[0] != 0 || col1[1] != 8 || col1[2] != 0 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << col1 << "\n" << " Expected result:\n( 0 8 0 )\n"; throw std::runtime_error( oss.str() ); } if( diag(0,0) != 1 || diag(0,1) != 0 || diag(0,2) != 0 || diag(1,0) != 0 || diag(1,1) != 8 || diag(1,2) != 0 || diag(2,0) != 0 || diag(2,1) != 0 || diag(2,2) != 3 ) { std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Column reset failed\n" << " Details:\n" << " Result:\n" << diag << "\n" << " Expected result:\n( 1 0 0 )\n( 0 8 0 )\n( 0 0 3 )\n"; throw std::runtime_error( oss.str() ); } } // ( 1 0 0 ) ( 1 9 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 0 3 ) { test_ = "Column-major column() function (sparse vector assignment test 2)"; typedef blaze::DenseColumn<ODT> CT; blaze::CompressedVector<int,blaze::columnVector> vec( 3UL, 3UL ); vec[0] = 9; vec[1] = 8; vec.insert( 2UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } // ( 1 0 0 ) ( 1 0 0 ) // ( 0 2 0 ) => ( 0 8 0 ) // ( 0 0 3 ) ( 0 2 3 ) { test_ = "Column-major column() function (sparse vector assignment test 3)"; typedef blaze::DenseColumn<ODT> CT; blaze::CompressedVector<int,blaze::columnVector> vec( 3UL, 3UL ); vec[1] = 8; vec[2] = 2; vec.insert( 0UL, 0 ); ODT diag( 3UL ); diag(0,0) = 1; diag(1,1) = 2; diag(2,2) = 3; CT col1 = column( diag, 1UL ); try { col1 = vec; std::ostringstream oss; oss << " Test: " << test_ << "\n" << " Error: Assignment of invalid vector succeeded\n" << " Details:\n" << " Result:\n" << diag << "\n"; throw std::runtime_error( oss.str() ); } catch( std::invalid_argument& ) {} } } //************************************************************************************************* } // namespace diagonalmatrix } // namespace mathtest } // namespace blazetest //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running DiagonalMatrix dense test..." << std::endl; try { RUN_DIAGONALMATRIX_DENSE_TEST; } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during DiagonalMatrix dense test:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************<|fim▁end|>
<|file_name|>r12writer.py<|end_file_name|><|fim▁begin|># Copyright (c) 2020 Manfred Moitzi # License: MIT License from pathlib import Path from time import perf_counter import math from ezdxf.addons import MengerSponge from ezdxf.addons import r12writer from ezdxf.render.forms import sphere, circle, translate DIR = Path("~/Desktop/Outbox").expanduser() def menger_sponge(filename, level=1, kind=0): t0 = perf_counter() sponge = MengerSponge(level=level, kind=kind).mesh() t1 = perf_counter() print(f"Build menger sponge <{kind}> in {t1 - t0:.5f}s.")<|fim▁hole|> with r12writer(filename) as r12: r12.add_polyface(sponge.vertices, sponge.faces, color=1) print(f'saved as "{filename}".') def polymesh(filename, size=(10, 10)): m, n = size # rows, cols dx = math.pi / m * 2 dy = math.pi / n * 2 vertices = [] for x in range(m): # rows second z1 = math.sin(dx * x) for y in range(n): # cols first z2 = math.sin(dy * y) z = z1 * z2 vertices.append((x, y, z)) with r12writer(filename) as r12: r12.add_polymesh(vertices, size=size, color=1) print(f'saved as "{filename}".') def polyface_sphere(filename): mesh = sphere(16, 8, quads=True) with r12writer(filename) as r12: r12.add_polyface(mesh.vertices, mesh.faces, color=1) print(f'saved as "{filename}".') def polylines(filename): with r12writer(filename) as r12: r12.add_polyline_2d(circle(8), color=1, closed=False) r12.add_polyline_2d( translate(circle(8), vec=(3, 0)), color=3, closed=True ) r12.add_polyline_2d( [(0, 4), (4, 4, 1), (8, 4, 0, 0.2, 0.000001), (12, 4)], format="xybse", start_width=0.1, end_width=0.1, color=5, ) print(f'saved as "{filename}".') if __name__ == "__main__": menger_sponge(DIR / "menger_sponge_r12.dxf", level=2) polymesh(DIR / "polymesh.dxf", size=(20, 10)) polyface_sphere(DIR / "sphere.dxf") polylines(DIR / "polylines.dxf")<|fim▁end|>
<|file_name|>foo.go<|end_file_name|><|fim▁begin|>// Copyright 2018 The Wire Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "fmt" "io/ioutil" "strings" ) func main() { r := injectedReader(strings.NewReader("hello world")) buf, _ := ioutil.ReadAll(r)<|fim▁hole|><|fim▁end|>
fmt.Println(string(buf)) }
<|file_name|>package.py<|end_file_name|><|fim▁begin|>############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public<|fim▁hole|>############################################################################## from spack import * class PyMarkupsafe(PythonPackage): """MarkupSafe is a library for Python that implements a unicode string that is aware of HTML escaping rules and can be used to implement automatic string escaping. It is used by Jinja 2, the Mako templating engine, the Pylons web framework and many more.""" homepage = "http://www.pocoo.org/projects/markupsafe/" url = "https://pypi.io/packages/source/M/MarkupSafe/MarkupSafe-1.0.tar.gz" import_modules = ['markupsafe'] version('1.0', '2fcedc9284d50e577b5192e8e3578355') version('0.23', 'f5ab3deee4c37cd6a922fb81e730da6e') version('0.22', 'cb3ec29fd5361add24cfd0c6e2953b3e') version('0.21', 'fde838d9337fa51744283f46a1db2e74') version('0.20', '7da066d9cb191a70aa85d0a3d43565d1') version('0.19', 'ccb3f746c807c5500850987006854a6d') depends_on('py-setuptools', type='build')<|fim▁end|>
# License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
<|file_name|>handshake.js<|end_file_name|><|fim▁begin|>var crypto = require('crypto'); var lob = require('lob-enc') var hashname = require('hashname'); var log = require("./log")("Handshake") module.exports = { bootstrap : handshake_bootstrap, validate : handshake_validate, from : handshake_from, types : handshake_types, collect : handshake_collect }; var hcache = {} setInterval(function(){hcache = {}}, 60 * 1000) /** * collect incoming handshakes to accept them * @param {object} id * @param {handshake} handshake * @param {pipe} pipe * @param {Buffer} message */ function handshake_collect(mesh, id, handshake, pipe, message) { handshake = handshake_bootstrap(handshake); if (!handshake) return false; var valid = handshake_validate(id,handshake, message, mesh); if (!valid) return false; // get all from cache w/ matching at, by type var types = handshake_types(handshake, id); // bail unless we have a link if(!types.link) { log.debug('handshakes w/ no link yet',id,types); return false; } // build a from json container var from = handshake_from(handshake, pipe, types.link)<|fim▁hole|> // if we already linked this hashname, just update w/ the new info if(mesh.index[from.hashname]) { log.debug('refresh link handshake') from.sync = false; // tell .link to not auto-sync! return mesh.link(from); } else { } log.debug('untrusted hashname',from); from.received = {packet:types.link._message, pipe:pipe} // optimization hints as link args from.handshake = types; // include all handshakes if(mesh.accept) mesh.accept(from); return false; } function handshake_bootstrap(handshake){ // default an at for bare key handshakes if not given if(typeof handshake.json.at === 'undefined') handshake.json.at = Date.now(); // verify at if(typeof handshake.json.at != 'number' || handshake.json.at <= 0) { log.debug('invalid handshake at',handshake.json); return false; } // default the handshake type if(typeof handshake.json.type != 'string') handshake.json.type = 'link'; // upvert deprecated key to link type if(handshake.json.type == 'key') { // map only csid keys into attachment header var json = {}; hashname.ids(handshake.json).forEach(function(csid){ if(handshake.json[csid] === true) handshake.json.csid = csid; // cruft json[csid] = handshake.json[csid]; }); if(message) json[message.head.toString('hex')] = true; var attach = lob.encode(json, handshake.body); handshake.json.type = 'link'; handshake.body = attach; } return handshake } function handshake_validate(id,handshake, message, mesh){ if(handshake.json.type == 'link') { // if it came from an encrypted message if(message) { // make sure the link csid matches the message csid handshake.json.csid = message.head.toString('hex'); // stash inside the handshake, can be used later to create the exchange immediately handshake._message = message; } var attach = lob.decode(handshake.body); if(!attach) { log.debug('invalid link handshake attachment',handshake.body); return false; } // make sure key info is at least correct var keys = {}; keys[handshake.json.csid] = attach.body; var csid = hashname.match(mesh.keys, keys, null, attach.json); if(handshake.json.csid != csid) { log.debug('invalid key handshake, unsupported csid',attach.json, keys); return false; } handshake.json.hashname = hashname.fromKeys(keys, attach.json); if(!handshake.json.hashname) { log.debug('invalid key handshake, no hashname',attach.json, keys); return false; } // hashname is valid now, so stash key bytes in handshake handshake.body = attach.body; } // add it to the cache hcache[id] = (hcache[id] || [] ).concat([handshake]); return true; } function handshake_types (handshake, id){ var types = {} hcache[id].forEach(function(hs){ if(hs.json.at === handshake.json.at) types[hs.json.type] = hs; }); return types; } function handshake_from (handshake, pipe, link){ return { paths : (pipe.path) ? [pipe.path] : [], hashname : link.json.hashname, csid : link.json.csid, key : link.body }; }<|fim▁end|>
<|file_name|>SelectorDimFilter.java<|end_file_name|><|fim▁begin|>/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.query.filter; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; import com.google.common.collect.TreeRangeSet; import com.google.common.primitives.Floats; import io.druid.common.guava.GuavaUtils; import io.druid.java.util.common.StringUtils; import io.druid.query.extraction.ExtractionFn; import io.druid.segment.filter.DimensionPredicateFilter; import io.druid.segment.filter.SelectorFilter; import java.nio.ByteBuffer; import java.util.Objects; /** */ public class SelectorDimFilter implements DimFilter { private final String dimension; private final String value; private final ExtractionFn extractionFn; private final Object initLock = new Object(); private DruidLongPredicate longPredicate; private DruidFloatPredicate floatPredicate; @JsonCreator public SelectorDimFilter( @JsonProperty("dimension") String dimension, @JsonProperty("value") String value, @JsonProperty("extractionFn") ExtractionFn extractionFn ) { Preconditions.checkArgument(dimension != null, "dimension must not be null"); this.dimension = dimension; this.value = Strings.nullToEmpty(value); this.extractionFn = extractionFn; } @Override public byte[] getCacheKey() { byte[] dimensionBytes = StringUtils.toUtf8(dimension); byte[] valueBytes = (value == null) ? new byte[]{} : StringUtils.toUtf8(value); byte[] extractionFnBytes = extractionFn == null ? new byte[0] : extractionFn.getCacheKey(); return ByteBuffer.allocate(3 + dimensionBytes.length + valueBytes.length + extractionFnBytes.length) .put(DimFilterUtils.SELECTOR_CACHE_ID) .put(dimensionBytes) .put(DimFilterUtils.STRING_SEPARATOR) .put(valueBytes) .put(DimFilterUtils.STRING_SEPARATOR)<|fim▁hole|> @Override public DimFilter optimize() { return new InDimFilter(dimension, ImmutableList.of(value), extractionFn).optimize(); } @Override public Filter toFilter() { if (extractionFn == null) { return new SelectorFilter(dimension, value); } else { final String valueOrNull = Strings.emptyToNull(value); final DruidPredicateFactory predicateFactory = new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { return Predicates.equalTo(valueOrNull); } @Override public DruidLongPredicate makeLongPredicate() { initLongPredicate(); return longPredicate; } @Override public DruidFloatPredicate makeFloatPredicate() { initFloatPredicate(); return floatPredicate; } }; return new DimensionPredicateFilter(dimension, predicateFactory, extractionFn); } } @JsonProperty public String getDimension() { return dimension; } @JsonProperty public String getValue() { return value; } @JsonProperty public ExtractionFn getExtractionFn() { return extractionFn; } @Override public String toString() { if (extractionFn != null) { return String.format("%s(%s) = %s", extractionFn, dimension, value); } else { return String.format("%s = %s", dimension, value); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SelectorDimFilter that = (SelectorDimFilter) o; if (!dimension.equals(that.dimension)) { return false; } if (value != null ? !value.equals(that.value) : that.value != null) { return false; } return extractionFn != null ? extractionFn.equals(that.extractionFn) : that.extractionFn == null; } @Override public RangeSet<String> getDimensionRangeSet(String dimension) { if (!Objects.equals(getDimension(), dimension) || getExtractionFn() != null) { return null; } RangeSet<String> retSet = TreeRangeSet.create(); retSet.add(Range.singleton(Strings.nullToEmpty(value))); return retSet; } @Override public int hashCode() { int result = dimension.hashCode(); result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (extractionFn != null ? extractionFn.hashCode() : 0); return result; } private void initLongPredicate() { if (longPredicate != null) { return; } synchronized (initLock) { if (longPredicate != null) { return; } final Long valueAsLong = GuavaUtils.tryParseLong(value); if (valueAsLong == null) { longPredicate = DruidLongPredicate.ALWAYS_FALSE; } else { // store the primitive, so we don't unbox for every comparison final long unboxedLong = valueAsLong.longValue(); longPredicate = new DruidLongPredicate() { @Override public boolean applyLong(long input) { return input == unboxedLong; } }; } } } private void initFloatPredicate() { if (floatPredicate != null) { return; } synchronized (initLock) { if (floatPredicate != null) { return; } final Float valueAsFloat = Floats.tryParse(value); if (valueAsFloat == null) { floatPredicate = DruidFloatPredicate.ALWAYS_FALSE; } else { final int floatBits = Float.floatToIntBits(valueAsFloat); floatPredicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return Float.floatToIntBits(input) == floatBits; } }; } } } }<|fim▁end|>
.put(extractionFnBytes) .array(); }
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from math import ceil from django.db import models, IntegrityError, connection from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature from django.utils.six.moves import range from .models import (R, RChild, S, T, A, M, MR, MRNull, create_a, get_default_r, User, Avatar, HiddenUser, HiddenUserProfile, M2MTo, M2MFrom, Parent, Child, Base) class OnDeleteTests(TestCase): def setUp(self): self.DEFAULT = get_default_r() def test_auto(self): a = create_a('auto') a.auto.delete() self.assertFalse(A.objects.filter(name='auto').exists()) def test_auto_nullable(self): a = create_a('auto_nullable') a.auto_nullable.delete() self.assertFalse(A.objects.filter(name='auto_nullable').exists()) def test_setvalue(self): a = create_a('setvalue') a.setvalue.delete() a = A.objects.get(pk=a.pk) self.assertEqual(self.DEFAULT, a.setvalue) def test_setnull(self): a = create_a('setnull') a.setnull.delete() a = A.objects.get(pk=a.pk) self.assertEqual(None, a.setnull) def test_setdefault(self): a = create_a('setdefault') a.setdefault.delete() a = A.objects.get(pk=a.pk) self.assertEqual(self.DEFAULT, a.setdefault) def test_setdefault_none(self): a = create_a('setdefault_none') a.setdefault_none.delete() a = A.objects.get(pk=a.pk) self.assertEqual(None, a.setdefault_none) def test_cascade(self): a = create_a('cascade') a.cascade.delete() self.assertFalse(A.objects.filter(name='cascade').exists()) def test_cascade_nullable(self): a = create_a('cascade_nullable') a.cascade_nullable.delete() self.assertFalse(A.objects.filter(name='cascade_nullable').exists()) def test_protect(self): a = create_a('protect') self.assertRaises(IntegrityError, a.protect.delete) def test_do_nothing(self): # Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model, # so we connect to pre_delete and set the fk to a known value. replacement_r = R.objects.create() def check_do_nothing(sender, **kwargs): obj = kwargs['instance'] obj.donothing_set.update(donothing=replacement_r) models.signals.pre_delete.connect(check_do_nothing) a = create_a('do_nothing') a.donothing.delete() a = A.objects.get(pk=a.pk) self.assertEqual(replacement_r, a.donothing) models.signals.pre_delete.disconnect(check_do_nothing) def test_do_nothing_qscount(self): """ Test that a models.DO_NOTHING relation doesn't trigger a query. """ b = Base.objects.create() with self.assertNumQueries(1): # RelToBase should not be queried. b.delete() self.assertEqual(Base.objects.count(), 0) def test_inheritance_cascade_up(self): child = RChild.objects.create() child.delete() self.assertFalse(R.objects.filter(pk=child.pk).exists()) def test_inheritance_cascade_down(self): child = RChild.objects.create() parent = child.r_ptr parent.delete() self.assertFalse(RChild.objects.filter(pk=child.pk).exists()) def test_cascade_from_child(self): a = create_a('child') a.child.delete() self.assertFalse(A.objects.filter(name='child').exists()) self.assertFalse(R.objects.filter(pk=a.child_id).exists()) def test_cascade_from_parent(self): a = create_a('child') R.objects.get(pk=a.child_id).delete() self.assertFalse(A.objects.filter(name='child').exists()) self.assertFalse(RChild.objects.filter(pk=a.child_id).exists()) def test_setnull_from_child(self): a = create_a('child_setnull') a.child_setnull.delete() self.assertFalse(R.objects.filter(pk=a.child_setnull_id).exists()) a = A.objects.get(pk=a.pk) self.assertEqual(None, a.child_setnull) def test_setnull_from_parent(self): a = create_a('child_setnull') R.objects.get(pk=a.child_setnull_id).delete() self.assertFalse(RChild.objects.filter(pk=a.child_setnull_id).exists()) a = A.objects.get(pk=a.pk) self.assertEqual(None, a.child_setnull) def test_o2o_setnull(self): a = create_a('o2o_setnull') a.o2o_setnull.delete() a = A.objects.get(pk=a.pk) self.assertEqual(None, a.o2o_setnull) class DeletionTests(TestCase): def test_m2m(self): m = M.objects.create() r = R.objects.create() MR.objects.create(m=m, r=r) r.delete() self.assertFalse(MR.objects.exists()) r = R.objects.create() MR.objects.create(m=m, r=r) m.delete() self.assertFalse(MR.objects.exists()) m = M.objects.create() r = R.objects.create() m.m2m.add(r) r.delete() through = M._meta.get_field('m2m').rel.through self.assertFalse(through.objects.exists()) r = R.objects.create() m.m2m.add(r) m.delete() self.assertFalse(through.objects.exists()) m = M.objects.create() r = R.objects.create() MRNull.objects.create(m=m, r=r) r.delete() self.assertFalse(not MRNull.objects.exists()) self.assertFalse(m.m2m_through_null.exists()) def test_bulk(self): s = S.objects.create(r=R.objects.create()) for i in range(2 * GET_ITERATOR_CHUNK_SIZE): T.objects.create(s=s) # 1 (select related `T` instances) # + 1 (select related `U` instances) # + 2 (delete `T` instances in batches) # + 1 (delete `s`) self.assertNumQueries(5, s.delete) self.assertFalse(S.objects.exists()) def test_instance_update(self): deleted = [] related_setnull_sets = [] def pre_delete(sender, **kwargs): obj = kwargs['instance'] deleted.append(obj) if isinstance(obj, R): related_setnull_sets.append(list(a.pk for a in obj.setnull_set.all())) models.signals.pre_delete.connect(pre_delete) a = create_a('update_setnull') a.setnull.delete() a = create_a('update_cascade') a.cascade.delete() for obj in deleted: self.assertEqual(None, obj.pk) for pk_list in related_setnull_sets: for a in A.objects.filter(id__in=pk_list): self.assertEqual(None, a.setnull) models.signals.pre_delete.disconnect(pre_delete) def test_deletion_order(self): pre_delete_order = [] post_delete_order = [] def log_post_delete(sender, **kwargs): pre_delete_order.append((sender, kwargs['instance'].pk)) def log_pre_delete(sender, **kwargs): post_delete_order.append((sender, kwargs['instance'].pk)) models.signals.post_delete.connect(log_post_delete) models.signals.pre_delete.connect(log_pre_delete) r = R.objects.create(pk=1) s1 = S.objects.create(pk=1, r=r) s2 = S.objects.create(pk=2, r=r) T.objects.create(pk=1, s=s1) T.objects.create(pk=2, s=s2) r.delete() self.assertEqual( pre_delete_order, [(T, 2), (T, 1), (S, 2), (S, 1), (R, 1)] ) self.assertEqual( post_delete_order, [(T, 1), (T, 2), (S, 1), (S, 2), (R, 1)] ) models.signals.post_delete.disconnect(log_post_delete) models.signals.pre_delete.disconnect(log_pre_delete) def test_relational_post_delete_signals_happen_before_parent_object(self): deletions = [] def log_post_delete(instance, **kwargs): self.assertTrue(R.objects.filter(pk=instance.r_id)) self.assertIs(type(instance), S) deletions.append(instance.id) r = R.objects.create(pk=1) S.objects.create(pk=1, r=r) models.signals.post_delete.connect(log_post_delete, sender=S) try: r.delete() finally: models.signals.post_delete.disconnect(log_post_delete) self.assertEqual(len(deletions), 1) self.assertEqual(deletions[0], 1) @skipUnlessDBFeature("can_defer_constraint_checks") def test_can_defer_constraint_checks(self): u = User.objects.create( avatar=Avatar.objects.create() ) a = Avatar.objects.get(pk=u.avatar_id) # 1 query to find the users for the avatar. # 1 query to delete the user # 1 query to delete the avatar # The important thing is that when we can defer constraint checks there # is no need to do an UPDATE on User.avatar to null it out. # Attach a signal to make sure we will not do fast_deletes. calls = [] def noop(*args, **kwargs): calls.append('') models.signals.post_delete.connect(noop, sender=User) self.assertNumQueries(3, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) self.assertEqual(len(calls), 1) models.signals.post_delete.disconnect(noop, sender=User) @skipIfDBFeature("can_defer_constraint_checks") def test_cannot_defer_constraint_checks(self): u = User.objects.create( avatar=Avatar.objects.create() ) # Attach a signal to make sure we will not do fast_deletes. calls = [] def noop(*args, **kwargs): calls.append('') models.signals.post_delete.connect(noop, sender=User) a = Avatar.objects.get(pk=u.avatar_id) # The below doesn't make sense... Why do we need to null out # user.avatar if we are going to delete the user immediately after it, # and there are no more cascades. # 1 query to find the users for the avatar. # 1 query to delete the user # 1 query to null out user.avatar, because we can't defer the constraint # 1 query to delete the avatar self.assertNumQueries(4, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) self.assertEqual(len(calls), 1) models.signals.post_delete.disconnect(noop, sender=User) def test_hidden_related(self): r = R.objects.create() h = HiddenUser.objects.create(r=r) HiddenUserProfile.objects.create(user=h) r.delete() self.assertEqual(HiddenUserProfile.objects.count(), 0) def test_large_delete(self): TEST_SIZE = 2000 objs = [Avatar() for i in range(0, TEST_SIZE)] Avatar.objects.bulk_create(objs) # Calculate the number of queries needed. batch_size = connection.ops.bulk_batch_size(['pk'], objs) # The related fetches are done in batches. batches = int(ceil(float(len(objs)) / batch_size)) # One query for Avatar.objects.all() and then one related fast delete for # each batch. fetches_to_mem = 1 + batches # The Avatar objects are going to be deleted in batches of GET_ITERATOR_CHUNK_SIZE queries = fetches_to_mem + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE self.assertNumQueries(queries, Avatar.objects.all().delete) self.assertFalse(Avatar.objects.exists()) def test_large_delete_related(self): TEST_SIZE = 2000 s = S.objects.create(r=R.objects.create()) for i in range(TEST_SIZE): T.objects.create(s=s)<|fim▁hole|> # + 1 (select related `U` instances) # + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE (delete `T` instances in batches) # + 1 (delete `s`) expected_num_queries = (ceil(TEST_SIZE // batch_size) + ceil(TEST_SIZE // GET_ITERATOR_CHUNK_SIZE) + 2) self.assertNumQueries(expected_num_queries, s.delete) self.assertFalse(S.objects.exists()) self.assertFalse(T.objects.exists()) class FastDeleteTests(TestCase): def test_fast_delete_fk(self): u = User.objects.create( avatar=Avatar.objects.create() ) a = Avatar.objects.get(pk=u.avatar_id) # 1 query to fast-delete the user # 1 query to delete the avatar self.assertNumQueries(2, a.delete) self.assertFalse(User.objects.exists()) self.assertFalse(Avatar.objects.exists()) def test_fast_delete_m2m(self): t = M2MTo.objects.create() f = M2MFrom.objects.create() f.m2m.add(t) # 1 to delete f, 1 to fast-delete m2m for f self.assertNumQueries(2, f.delete) def test_fast_delete_revm2m(self): t = M2MTo.objects.create() f = M2MFrom.objects.create() f.m2m.add(t) # 1 to delete t, 1 to fast-delete t's m_set self.assertNumQueries(2, f.delete) def test_fast_delete_qs(self): u1 = User.objects.create() u2 = User.objects.create() self.assertNumQueries(1, User.objects.filter(pk=u1.pk).delete) self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.filter(pk=u2.pk).exists()) def test_fast_delete_joined_qs(self): a = Avatar.objects.create(desc='a') User.objects.create(avatar=a) u2 = User.objects.create() expected_queries = 1 if connection.features.update_can_self_select else 2 self.assertNumQueries(expected_queries, User.objects.filter(avatar__desc='a').delete) self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.filter(pk=u2.pk).exists()) def test_fast_delete_inheritance(self): c = Child.objects.create() p = Parent.objects.create() # 1 for self, 1 for parent # However, this doesn't work as child.parent access creates a query, # and this means we will be generating extra queries (a lot for large # querysets). This is not a fast-delete problem. # self.assertNumQueries(2, c.delete) c.delete() self.assertFalse(Child.objects.exists()) self.assertEqual(Parent.objects.count(), 1) self.assertEqual(Parent.objects.filter(pk=p.pk).count(), 1) # 1 for self delete, 1 for fast delete of empty "child" qs. self.assertNumQueries(2, p.delete) self.assertFalse(Parent.objects.exists()) # 1 for self delete, 1 for fast delete of empty "child" qs. c = Child.objects.create() p = c.parent_ptr self.assertNumQueries(2, p.delete) self.assertFalse(Parent.objects.exists()) self.assertFalse(Child.objects.exists()) def test_fast_delete_large_batch(self): User.objects.bulk_create(User() for i in range(0, 2000)) # No problems here - we aren't going to cascade, so we will fast # delete the objects in a single query. self.assertNumQueries(1, User.objects.all().delete) a = Avatar.objects.create(desc='a') User.objects.bulk_create(User(avatar=a) for i in range(0, 2000)) # We don't hit parameter amount limits for a, so just one query for # that + fast delete of the related objs. self.assertNumQueries(2, a.delete) self.assertEqual(User.objects.count(), 0)<|fim▁end|>
batch_size = max(connection.ops.bulk_batch_size(['pk'], range(TEST_SIZE)), 1) # TEST_SIZE // batch_size (select related `T` instances)
<|file_name|>test_actions.py<|end_file_name|><|fim▁begin|>from servicemanager.actions import actions from servicemanager.smcontext import SmApplication, SmContext, ServiceManagerException from servicemanager.smprocess import SmProcess from servicemanager.service.smplayservice import SmPlayService from servicemanager.serviceresolver import ServiceResolver import pytest from .testbase import TestBase class TestActions(TestBase): def test_start_and_stop_one(self): context = SmContext(SmApplication(self.config_dir_override), None, False, False) result = actions.start_one(context, "TEST_ONE", False, True, False, None, port=None) self.assertTrue(result) self.waitForCondition((lambda: len(context.get_service("TEST_ONE").status())), 1) context.kill("TEST_ONE", True) self.assertEqual(context.get_service("TEST_ONE").status(), []) def test_start_and_stop_one_with_append_args(self): context = SmContext(SmApplication(self.config_dir_override), None, False, False) actions.start_one(context, "TEST_FOUR", False, True, False, None, None, ["2"]) self.waitForCondition((lambda: len(context.get_service("TEST_FOUR").status())), 1) context.kill("TEST_FOUR", True) self.assertEqual(context.get_service("TEST_FOUR").status(), []) @pytest.mark.online def test_dropwizard_from_source(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) servicetostart = "DROPWIZARD_NEXUS_END_TO_END_TEST" actions.start_and_wait( service_resolver, context, [servicetostart], False, False, False, None, port=None, seconds_to_wait=90, append_args=None, ) self.assertIsNotNone(context.get_service(servicetostart).status()) context.kill(servicetostart, True) self.assertEqual(context.get_service(servicetostart).status(), []) def test_dropwizard_from_jar(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) self.startFakeNexus() servicetostart = "DROPWIZARD_NEXUS_END_TO_END_TEST" actions.start_and_wait( service_resolver, context, [servicetostart], False, True, False, None, port=None, seconds_to_wait=90, append_args=None, ) self.assertIsNotNone(context.get_service(servicetostart).status()) context.kill(servicetostart, True) self.assertEqual(context.get_service(servicetostart).status(), []) @pytest.mark.online def test_play_from_source(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) <|fim▁hole|> secondsToWait = 90 append_args = None actions.start_and_wait( service_resolver, context, [servicetostart], True, False, False, None, port, secondsToWait, append_args, ) self.assertIsNotNone(context.get_service(servicetostart).status()) context.kill(servicetostart, True) self.assertEqual(context.get_service(servicetostart).status(), []) def test_play_from_default_run_from_source(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) servicetostart = "PLAY_NEXUS_END_TO_END_DEFAULT_SOURCE_TEST" port = None secondsToWait = 90 append_args = None actions.start_and_wait( service_resolver, context, [servicetostart], False, False, False, None, port, secondsToWait, append_args, ) self.assertIsNotNone(context.get_service(servicetostart).status()) context.kill(servicetostart, True) self.assertEqual(context.get_service(servicetostart).status(), []) def test_play_from_source_default(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) servicetostart = "PLAY_NEXUS_END_TO_END_TEST" port = None secondsToWait = 90 append_args = None actions.start_and_wait( service_resolver, context, [servicetostart], False, False, False, None, port, secondsToWait, append_args, ) self.assertIsNotNone(context.get_service(servicetostart).status()) context.kill(servicetostart, True) self.assertEqual(context.get_service(servicetostart).status(), []) def test_successful_play_from_jar_without_waiting(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) context.kill_everything(True) self.startFakeNexus() fatJar = True release = False proxy = None port = None seconds_to_wait = None append_args = None try: servicetostart = ["PLAY_NEXUS_END_TO_END_TEST"] actions.start_and_wait( service_resolver, context, servicetostart, False, fatJar, release, proxy, port, seconds_to_wait, append_args, ) finally: context.kill_everything(True) def test_successful_play_default_run_from_jar_without_waiting(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) context.kill_everything(True) self.startFakeNexus() source = False fatJar = True release = False proxy = None port = None seconds_to_wait = None append_args = None try: servicetostart = ["PLAY_NEXUS_END_TO_END_DEFAULT_JAR_TEST"] actions.start_and_wait( service_resolver, context, servicetostart, source, fatJar, release, proxy, port, seconds_to_wait, append_args, ) finally: context.kill_everything(True) def test_successful_play_from_jar_without_waiting_with_append_args(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) context.kill_everything(True) self.startFakeNexus() servicetostart = ["PLAY_NEXUS_END_TO_END_TEST"] appendArgs = {"PLAY_NEXUS_END_TO_END_TEST": ["-DFoo=Bar"]} fatJar = True release = False proxy = None port = None seconds_to_wait = None actions.start_and_wait( service_resolver, context, servicetostart, False, fatJar, release, proxy, port, seconds_to_wait, appendArgs, ) service = SmPlayService(context, "PLAY_NEXUS_END_TO_END_TEST") self.waitForCondition(lambda: len(SmProcess.processes_matching(service.pattern)), 1) processes = SmProcess.processes_matching(service.pattern) self.assertTrue("-DFoo=Bar" in processes[0].args) def test_failing_play_from_jar(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) context.kill_everything(True) self.startFakeNexus() try: servicetostart = ["BROKEN_PLAY_PROJECT"] actions.start_and_wait( service_resolver, context, servicetostart, source=False, fatjar=True, release=False, proxy=None, port=None, seconds_to_wait=2, append_args=None, ) self.fail("Did not expect the project to startup.") except ServiceManagerException as sme: self.assertEqual("Timed out starting service(s): BROKEN_PLAY_PROJECT", sme.args[0]) finally: context.kill_everything(True) def test_start_and_stop_one_duplicate(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) actions.start_and_wait( service_resolver, context, ["TEST_ONE"], False, False, False, None, port=None, seconds_to_wait=90, append_args=None, ) self.assertIsNotNone(context.get_service("TEST_ONE").status()) result = actions.start_one(context, "TEST_ONE", False, True, False, None, port=None) self.assertFalse(result) context.kill("TEST_ONE", True) self.assertEqual(context.get_service("TEST_ONE").status(), []) def test_assets_server(self): context = SmContext(SmApplication(self.config_dir_override), None, False, False) context.kill_everything(True) self.startFakeArtifactory() actions.start_one( context, "PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND", False, True, False, None, port=None, ) self.assertIsNotNone(context.get_service("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND").status()) context.kill("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND", wait=True) self.assertEqual(context.get_service("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND").status(), []) def test_wait_on_assets_server(self): sm_application = SmApplication(self.config_dir_override) context = SmContext(sm_application, None, False, False) service_resolver = ServiceResolver(sm_application) context.kill_everything(True) self.startFakeArtifactory() port = None seconds_to_wait = 5 append_args = None actions.start_and_wait( service_resolver, context, ["PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND"], False, True, False, None, port, seconds_to_wait, append_args, ) self.assertIsNotNone(context.get_service("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND").status()) context.kill("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND", True) self.assertEqual(context.get_service("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND").status(), []) def test_python_server_offline(self): context = SmContext(SmApplication(self.config_dir_override), None, True, False) port = None append_args = None actions.start_one( context, "PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND", False, True, False, None, port, append_args, ) self.assertIsNotNone(context.get_service("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND").status()) context.kill("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND", True) self.assertEqual(context.get_service("PYTHON_SIMPLE_SERVER_ASSETS_FRONTEND").status(), [])<|fim▁end|>
servicetostart = "PLAY_NEXUS_END_TO_END_TEST" port = None
<|file_name|>power_bi_embedded_management_client_enums.py<|end_file_name|><|fim▁begin|># coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class AccessKeyName(str, Enum): key1 = "key1" key2 = "key2" <|fim▁hole|> unavailable = "Unavailable" invalid = "Invalid"<|fim▁end|>
class CheckNameReason(str, Enum):
<|file_name|>processDefinitionCtrl.js<|end_file_name|><|fim▁begin|>ngDefine( 'cockpit.plugin.statistics-plugin.controllers', function(module) { module .controller( 'processDefinitionCtrl', [ '$scope', 'DataFactory', 'Uri', function($scope, DataFactory, Uri) { $scope.options = { chart : { type : 'pieChart', height : 500, x : function(d) { return d.key; }, y : function(d) { return d.y; }, showLabels : true, transitionDuration : 500, labelThreshold : 0.01, tooltips : true, tooltipContent : function(key, y, e, graph) { if (key == "finished") { return '<h3>' + key + '</h3>' + '<p>count:<b>' + y + '</b><br/>' + 'average Duration:<b>' + (e.point.avg / 1000 / 60).toFixed(2) + ' min</b><br/>minimal Duration:<b>' + (e.point.min / 1000 / 60).toFixed(2) + ' min</b><br/>maximal Duration:<b>' + (e.point.max / 1000 / 60).toFixed(2) + ' min</b></p>' } else { return '<h3>' + key + '</h3>' + '<p>' + y + '</p>' } }, noData : "No Processes met the requirements", legend : { margin : { top : 5, right : 5, bottom : 5, left : 5 } } } }; DataFactory .getAllProcessInstanceCountsByState( $scope.processDefinition.key) .then(<|fim▁hole|> var processDefinitionCounts = DataFactory.allProcessInstanceCountsByState[$scope.processDefinition.key]; var counts = []; counts .push({ "key" : "running", "y" : processDefinitionCounts[0].runningInstanceCount }); counts .push({ "key" : "failed", "y" : processDefinitionCounts[0].failedInstanceCount }); counts .push({ "key" : "finished", "y" : processDefinitionCounts[0].endedInstanceCount, "avg" : processDefinitionCounts[0].duration, "min" : processDefinitionCounts[0].minDuration, "max" : processDefinitionCounts[0].maxDuration }); $scope.statesOfDefinition = counts; }); } ]); });<|fim▁end|>
function() {
<|file_name|>cartridge.hpp<|end_file_name|><|fim▁begin|>class Cartridge : property<Cartridge> { public: enum class Mode : unsigned { Normal, BsxSlotted, Bsx, SufamiTurbo, SuperGameBoy, }; enum class Region : unsigned { NTSC, PAL, }; //assigned externally to point to file-system datafiles (msu1 and serial) //example: "/path/to/filename.sfc" would set this to "/path/to/filename" readwrite<string> basename; readonly<bool> loaded; readonly<unsigned> crc32; readonly<string> sha256; readonly<Mode> mode; readonly<Region> region; readonly<unsigned> ram_size; readonly<bool> has_bsx_slot; readonly<bool> has_superfx; readonly<bool> has_sa1; readonly<bool> has_necdsp; readonly<bool> has_srtc; readonly<bool> has_sdd1; readonly<bool> has_spc7110; readonly<bool> has_spc7110rtc; readonly<bool> has_cx4; readonly<bool> has_obc1; readonly<bool> has_st0018; readonly<bool> has_msu1; readonly<bool> has_serial; struct Mapping { Memory *memory; MMIO *mmio; Bus::MapMode mode; unsigned banklo; unsigned bankhi; unsigned addrlo; unsigned addrhi; unsigned offset; unsigned size;<|fim▁hole|> Mapping(); Mapping(Memory&); Mapping(MMIO&); }; array<Mapping> mapping; void load(Mode, const lstring&); void unload(); void serialize(serializer&); Cartridge(); ~Cartridge(); private: void parse_xml(const lstring&); void parse_xml_cartridge(const char*); void parse_xml_bsx(const char*); void parse_xml_sufami_turbo(const char*, bool); void parse_xml_gameboy(const char*); void xml_parse_rom(xml_element&); void xml_parse_ram(xml_element&); void xml_parse_icd2(xml_element&); void xml_parse_superfx(xml_element&); void xml_parse_sa1(xml_element&); void xml_parse_necdsp(xml_element&); void xml_parse_bsx(xml_element&); void xml_parse_sufamiturbo(xml_element&); void xml_parse_supergameboy(xml_element&); void xml_parse_srtc(xml_element&); void xml_parse_sdd1(xml_element&); void xml_parse_spc7110(xml_element&); void xml_parse_cx4(xml_element&); void xml_parse_obc1(xml_element&); void xml_parse_setarisc(xml_element&); void xml_parse_msu1(xml_element&); void xml_parse_serial(xml_element&); void xml_parse_address(Mapping&, const string&); void xml_parse_mode(Mapping&, const string&); }; namespace memory { extern MappedRAM cartrom, cartram, cartrtc; extern MappedRAM bsxflash, bsxram, bsxpram; extern MappedRAM stArom, stAram; extern MappedRAM stBrom, stBram; }; extern Cartridge cartridge;<|fim▁end|>
<|file_name|>stylesheet.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use context::QuirksMode; use cssparser::{Parser, ParserInput, RuleListParser}; use error_reporting::{ContextualParseError, ParseErrorReporter}; use fallible::FallibleVec; use fxhash::FxHashMap; use invalidation::media_queries::{MediaListKey, ToMediaListKey}; #[cfg(feature = "gecko")] use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf}; use media_queries::{Device, MediaList}; use parking_lot::RwLock; use parser::ParserContext; use servo_arc::Arc; use shared_lock::{ DeepCloneParams, DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, }; use std::mem; use std::sync::atomic::{AtomicBool, Ordering}; use style_traits::ParsingMode; use stylesheets::loader::StylesheetLoader; use stylesheets::rule_parser::{State, TopLevelRuleParser}; use stylesheets::rules_iterator::{EffectiveRules, EffectiveRulesIterator}; use stylesheets::rules_iterator::{NestedRuleIterationCondition, RulesIterator}; use stylesheets::{CssRule, CssRules, Origin, UrlExtraData}; use use_counters::UseCounters; use {Namespace, Prefix}; /// This structure holds the user-agent and user stylesheets. pub struct UserAgentStylesheets { /// The lock used for user-agent stylesheets. pub shared_lock: SharedRwLock, /// The user or user agent stylesheets. pub user_or_user_agent_stylesheets: Vec<DocumentStyleSheet>, /// The quirks mode stylesheet. pub quirks_mode_stylesheet: DocumentStyleSheet, } /// A set of namespaces applying to a given stylesheet. /// /// The namespace id is used in gecko #[derive(Clone, Debug, Default, MallocSizeOf)] #[allow(missing_docs)] pub struct Namespaces { pub default: Option<Namespace>, pub prefixes: FxHashMap<Prefix, Namespace>, } /// The contents of a given stylesheet. This effectively maps to a /// StyleSheetInner in Gecko. #[derive(Debug)] pub struct StylesheetContents { /// List of rules in the order they were found (important for /// cascading order) pub rules: Arc<Locked<CssRules>>, /// The origin of this stylesheet. pub origin: Origin, /// The url data this stylesheet should use. pub url_data: RwLock<UrlExtraData>, /// The namespaces that apply to this stylesheet. pub namespaces: RwLock<Namespaces>, /// The quirks mode of this stylesheet. pub quirks_mode: QuirksMode, /// This stylesheet's source map URL. pub source_map_url: RwLock<Option<String>>, /// This stylesheet's source URL. pub source_url: RwLock<Option<String>>, } impl StylesheetContents { /// Parse a given CSS string, with a given url-data, origin, and /// quirks mode. pub fn from_str( css: &str, url_data: UrlExtraData, origin: Origin, shared_lock: &SharedRwLock, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: Option<&ParseErrorReporter>, quirks_mode: QuirksMode, line_number_offset: u32, use_counters: Option<&UseCounters>, ) -> Self { let namespaces = RwLock::new(Namespaces::default()); let (rules, source_map_url, source_url) = Stylesheet::parse_rules( css, &url_data, origin, &mut *namespaces.write(), &shared_lock, stylesheet_loader, error_reporter, quirks_mode, line_number_offset, use_counters, ); Self { rules: CssRules::new(rules, &shared_lock), origin: origin, url_data: RwLock::new(url_data), namespaces: namespaces, quirks_mode: quirks_mode, source_map_url: RwLock::new(source_map_url), source_url: RwLock::new(source_url), } } /// Returns a reference to the list of rules. #[inline] pub fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] { &self.rules.read_with(guard).0 } /// Measure heap usage. #[cfg(feature = "gecko")] pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { // Measurement of other fields may be added later. self.rules.unconditional_shallow_size_of(ops) + self.rules.read_with(guard).size_of(guard, ops) } } impl DeepCloneWithLock for StylesheetContents { fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, params: &DeepCloneParams, ) -> Self { // Make a deep clone of the rules, using the new lock. let rules = self .rules .read_with(guard) .deep_clone_with_lock(lock, guard, params); Self { rules: Arc::new(lock.wrap(rules)), quirks_mode: self.quirks_mode, origin: self.origin, url_data: RwLock::new((*self.url_data.read()).clone()), namespaces: RwLock::new((*self.namespaces.read()).clone()), source_map_url: RwLock::new((*self.source_map_url.read()).clone()), source_url: RwLock::new((*self.source_url.read()).clone()), } } } /// The structure servo uses to represent a stylesheet. #[derive(Debug)] pub struct Stylesheet { /// The contents of this stylesheet. pub contents: StylesheetContents, /// The lock used for objects inside this stylesheet pub shared_lock: SharedRwLock, /// List of media associated with the Stylesheet. pub media: Arc<Locked<MediaList>>, /// Whether this stylesheet should be disabled. pub disabled: AtomicBool, } macro_rules! rule_filter { ($( $method: ident($variant:ident => $rule_type: ident), )+) => { $( #[allow(missing_docs)] fn $method<F>(&self, device: &Device, guard: &SharedRwLockReadGuard, mut f: F) where F: FnMut(&::stylesheets::$rule_type), { use stylesheets::CssRule; for rule in self.effective_rules(device, guard) { if let CssRule::$variant(ref lock) = *rule { let rule = lock.read_with(guard); f(&rule) } } } )+ } } /// A trait to represent a given stylesheet in a document. pub trait StylesheetInDocument: ::std::fmt::Debug { /// Get the stylesheet origin. fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin; /// Get the stylesheet quirks mode. fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode; /// Get whether this stylesheet is enabled. fn enabled(&self) -> bool; /// Get the media associated with this stylesheet. fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList>; /// Returns a reference to the list of rules in this stylesheet. fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule]; /// Return an iterator using the condition `C`. #[inline] fn iter_rules<'a, 'b, C>( &'a self, device: &'a Device, guard: &'a SharedRwLockReadGuard<'b>, ) -> RulesIterator<'a, 'b, C> where C: NestedRuleIterationCondition, { RulesIterator::new(device, self.quirks_mode(guard), guard, self.rules(guard)) } /// Returns whether the style-sheet applies for the current device. fn is_effective_for_device(&self, device: &Device, guard: &SharedRwLockReadGuard) -> bool { match self.media(guard) { Some(medialist) => medialist.evaluate(device, self.quirks_mode(guard)), None => true, } } /// Return an iterator over the effective rules within the style-sheet, as /// according to the supplied `Device`. #[inline] fn effective_rules<'a, 'b>( &'a self, device: &'a Device, guard: &'a SharedRwLockReadGuard<'b>, ) -> EffectiveRulesIterator<'a, 'b> { self.iter_rules::<EffectiveRules>(device, guard) } rule_filter! { effective_style_rules(Style => StyleRule), effective_media_rules(Media => MediaRule), effective_font_face_rules(FontFace => FontFaceRule), effective_font_face_feature_values_rules(FontFeatureValues => FontFeatureValuesRule), effective_counter_style_rules(CounterStyle => CounterStyleRule), effective_viewport_rules(Viewport => ViewportRule), effective_keyframes_rules(Keyframes => KeyframesRule), effective_supports_rules(Supports => SupportsRule), effective_page_rules(Page => PageRule), effective_document_rules(Document => DocumentRule), } } impl StylesheetInDocument for Stylesheet { fn origin(&self, _guard: &SharedRwLockReadGuard) -> Origin { self.contents.origin } fn quirks_mode(&self, _guard: &SharedRwLockReadGuard) -> QuirksMode { self.contents.quirks_mode } fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> { Some(self.media.read_with(guard)) } fn enabled(&self) -> bool { !self.disabled() } #[inline] fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] { self.contents.rules(guard) } } /// A simple wrapper over an `Arc<Stylesheet>`, with pointer comparison, and /// suitable for its use in a `StylesheetSet`. #[derive(Clone, Debug)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] pub struct DocumentStyleSheet( #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")] pub Arc<Stylesheet>, ); impl PartialEq for DocumentStyleSheet { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } impl ToMediaListKey for DocumentStyleSheet { fn to_media_list_key(&self) -> MediaListKey { self.0.to_media_list_key() } } impl StylesheetInDocument for DocumentStyleSheet { fn origin(&self, guard: &SharedRwLockReadGuard) -> Origin { self.0.origin(guard) } fn quirks_mode(&self, guard: &SharedRwLockReadGuard) -> QuirksMode { self.0.quirks_mode(guard) } fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> { self.0.media(guard) } fn enabled(&self) -> bool { self.0.enabled() } #[inline] fn rules<'a, 'b: 'a>(&'a self, guard: &'b SharedRwLockReadGuard) -> &'a [CssRule] { self.0.rules(guard) } } impl Stylesheet { /// Updates an empty stylesheet from a given string of text. pub fn update_from_str( existing: &Stylesheet, css: &str, url_data: UrlExtraData, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: Option<&ParseErrorReporter>, line_number_offset: u32, ) { let namespaces = RwLock::new(Namespaces::default()); // FIXME: Consider adding use counters to Servo? let (rules, source_map_url, source_url) = Self::parse_rules( css, &url_data, existing.contents.origin, &mut *namespaces.write(), &existing.shared_lock, stylesheet_loader, error_reporter, existing.contents.quirks_mode, line_number_offset, /* use_counters = */ None, ); *existing.contents.url_data.write() = url_data; mem::swap( &mut *existing.contents.namespaces.write(), &mut *namespaces.write(), );<|fim▁hole|> *existing.contents.rules.write_with(&mut guard) = CssRules(rules); *existing.contents.source_map_url.write() = source_map_url; *existing.contents.source_url.write() = source_url; } fn parse_rules( css: &str, url_data: &UrlExtraData, origin: Origin, namespaces: &mut Namespaces, shared_lock: &SharedRwLock, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: Option<&ParseErrorReporter>, quirks_mode: QuirksMode, line_number_offset: u32, use_counters: Option<&UseCounters>, ) -> (Vec<CssRule>, Option<String>, Option<String>) { let mut rules = Vec::new(); let mut input = ParserInput::new_with_line_number_offset(css, line_number_offset); let mut input = Parser::new(&mut input); let context = ParserContext::new( origin, url_data, None, ParsingMode::DEFAULT, quirks_mode, error_reporter, use_counters, ); let rule_parser = TopLevelRuleParser { shared_lock, loader: stylesheet_loader, context, state: State::Start, dom_error: None, insert_rule_context: None, namespaces, }; { let mut iter = RuleListParser::new_for_stylesheet(&mut input, rule_parser); while let Some(result) = iter.next() { match result { Ok(rule) => { // Use a fallible push here, and if it fails, just // fall out of the loop. This will cause the page to // be shown incorrectly, but it's better than OOMing. if rules.try_push(rule).is_err() { break; } }, Err((error, slice)) => { let location = error.location; let error = ContextualParseError::InvalidRule(slice, error); iter.parser.context.log_css_error(location, error); }, } } } let source_map_url = input.current_source_map_url().map(String::from); let source_url = input.current_source_url().map(String::from); (rules, source_map_url, source_url) } /// Creates an empty stylesheet and parses it with a given base url, origin /// and media. /// /// Effectively creates a new stylesheet and forwards the hard work to /// `Stylesheet::update_from_str`. pub fn from_str( css: &str, url_data: UrlExtraData, origin: Origin, media: Arc<Locked<MediaList>>, shared_lock: SharedRwLock, stylesheet_loader: Option<&StylesheetLoader>, error_reporter: Option<&ParseErrorReporter>, quirks_mode: QuirksMode, line_number_offset: u32, ) -> Self { // FIXME: Consider adding use counters to Servo? let contents = StylesheetContents::from_str( css, url_data, origin, &shared_lock, stylesheet_loader, error_reporter, quirks_mode, line_number_offset, /* use_counters = */ None, ); Stylesheet { contents, shared_lock, media, disabled: AtomicBool::new(false), } } /// Returns whether the stylesheet has been explicitly disabled through the /// CSSOM. pub fn disabled(&self) -> bool { self.disabled.load(Ordering::SeqCst) } /// Records that the stylesheet has been explicitly disabled through the /// CSSOM. /// /// Returns whether the the call resulted in a change in disabled state. /// /// Disabled stylesheets remain in the document, but their rules are not /// added to the Stylist. pub fn set_disabled(&self, disabled: bool) -> bool { self.disabled.swap(disabled, Ordering::SeqCst) != disabled } } #[cfg(feature = "servo")] impl Clone for Stylesheet { fn clone(&self) -> Self { // Create a new lock for our clone. let lock = self.shared_lock.clone(); let guard = self.shared_lock.read(); // Make a deep clone of the media, using the new lock. let media = self.media.read_with(&guard).clone(); let media = Arc::new(lock.wrap(media)); let contents = self .contents .deep_clone_with_lock(&lock, &guard, &DeepCloneParams); Stylesheet { contents, media: media, shared_lock: lock, disabled: AtomicBool::new(self.disabled.load(Ordering::SeqCst)), } } }<|fim▁end|>
// Acquire the lock *after* parsing, to minimize the exclusive section. let mut guard = existing.shared_lock.write();
<|file_name|>noreferences.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- """ This script adds a missing references section to pages. It goes over multiple pages, searches for pages where <references /> is missing although a <ref> tag is present, and in that case adds a new references section. These command line parameters can be used to specify which pages to work on: &params; -xml Retrieve information from a local XML dump (pages-articles or pages-meta-current, see https://download.wikimedia.org). Argument can also be given as "-xml:filename". -namespace:n Number or name of namespace to process. The parameter can be used multiple times. It works in combination with all other parameters, except for the -start parameter. If you e.g. want to iterate over all categories starting at M, use -start:Category:M. -always Don't prompt you for each replacement. -quiet Use this option to get less output If neither a page title nor a page generator is given, it takes all pages from the default maintenance category. It is strongly recommended not to run this script over the entire article namespace (using the -start) parameter, as that would consume too much bandwidth. Instead, use the -xml parameter, or use another way to generate a list of affected articles """ # # (C) Pywikibot team, 2007-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import re import pywikibot from pywikibot import i18n, pagegenerators, textlib, Bot # This is required for the text that is shown when you run this script # with the parameter -help. docuReplacements = { '&params;': pagegenerators.parameterHelp, } # References sections are usually placed before further reading / external # link sections. This dictionary defines these sections, sorted by priority. # For example, on an English wiki, the script would place the "References" # section in front of the "Further reading" section, if that existed. # Otherwise, it would try to put it in front of the "External links" section, # or if that fails, the "See also" section, etc. placeBeforeSections = { 'ar': [ # no explicit policy on where to put the references u'وصلات خارجية', u'انظر أيضا', u'ملاحظات' ], 'ca': [ u'Bibliografia', u'Bibliografia complementària', u'Vegeu també', u'Enllaços externs', u'Enllaços', ], 'cs': [ u'Externí odkazy', u'Poznámky', ], 'da': [ # no explicit policy on where to put the references u'Eksterne links' ], 'de': [ # no explicit policy on where to put the references u'Literatur', u'Weblinks', u'Siehe auch', u'Weblink', # bad, but common singular form of Weblinks ], 'dsb': [ u'Nožki', ], 'en': [ # no explicit policy on where to put the references u'Further reading', u'External links', u'See also', u'Notes' ], 'ru': [ u'Ссылки', u'Литература', ], 'eo': [ u'Eksteraj ligiloj', u'Ekstera ligilo', u'Eksteraj ligoj', u'Ekstera ligo', u'Rete' ], 'es': [ u'Enlaces externos', u'Véase también', u'Notas', ], 'fa': [ u'پیوند به بیرون', u'پانویس', u'جستارهای وابسته' ], 'fi': [ u'Kirjallisuutta', u'Aiheesta muualla', u'Ulkoiset linkit', u'Linkkejä', ], 'fr': [ u'Liens externes', u'Voir aussi', u'Notes' ], 'he': [ u'ראו גם', u'לקריאה נוספת', u'קישורים חיצוניים', u'הערות שוליים', ], 'hsb': [ u'Nóžki', ],<|fim▁hole|> 'hu': [ u'Külső hivatkozások', u'Lásd még', ], 'it': [ u'Bibliografia', u'Voci correlate', u'Altri progetti', u'Collegamenti esterni', u'Vedi anche', ], 'ja': [ u'関連項目', u'参考文献', u'外部リンク', ], 'ko': [ # no explicit policy on where to put the references u'외부 링크', u'외부링크', u'바깥 고리', u'바깥고리', u'바깥 링크', u'바깥링크' u'외부 고리', u'외부고리' ], 'lt': [ # no explicit policy on where to put the references u'Nuorodos' ], 'nl': [ # no explicit policy on where to put the references u'Literatuur', u'Zie ook', u'Externe verwijzingen', u'Externe verwijzing', ], 'pdc': [ u'Beweisunge', u'Quelle unn Literatur', u'Gwelle', u'Gwuelle', u'Auswenniche Gleecher', u'Gewebbgleecher', u'Guckt mol aa', u'Seh aa', ], 'pl': [ u'Źródła', u'Bibliografia', u'Zobacz też', u'Linki zewnętrzne', ], 'pt': [ u'Ligações externas', u'Veja também', u'Ver também', u'Notas', ], 'sk': [ u'Pozri aj', ], 'szl': [ u'Przipisy', u'Připisy', ], 'th': [ u'อ่านเพิ่มเติม', u'แหล่งข้อมูลอื่น', u'ดูเพิ่ม', u'หมายเหตุ', ], 'zh': [ u'外部链接', u'外部連结', u'外部連結', u'外部连接', ], } # Titles of sections where a reference tag would fit into. # The first title should be the preferred one: It's the one that # will be used when a new section has to be created. referencesSections = { 'ar': [ # not sure about which ones are preferred. u'مراجع', u'المراجع', u'مصادر', u'المصادر', u'مراجع ومصادر', u'مصادر ومراجع', u'المراجع والمصادر', u'المصادر والمراجع', ], 'ca': [ u'Referències', ], 'cs': [ u'Reference', u'Poznámky', ], 'da': [ u'Noter', ], 'de': [ # see [[de:WP:REF]] u'Einzelnachweise', u'Anmerkungen', u'Belege', u'Endnoten', u'Fußnoten', u'Fuß-/Endnoten', u'Quellen', u'Quellenangaben', ], 'dsb': [ u'Nožki', ], 'en': [ # not sure about which ones are preferred. u'References', u'Footnotes', u'Notes', ], 'ru': [ u'Примечания', u'Сноски', u'Источники', ], 'eo': [ u'Referencoj', ], 'es': [ u'Referencias', u'Notas', ], 'fa': [ u'منابع', u'منبع' ], 'fi': [ u'Lähteet', u'Viitteet', ], 'fr': [ # [[fr:Aide:Note]] u'Notes et références', u'Références', u'References', u'Notes' ], 'he': [ u'הערות שוליים', ], 'hsb': [ u'Nóžki', ], 'hu': [ u'Források és jegyzetek', u'Források', u'Jegyzetek', u'Hivatkozások', u'Megjegyzések', ], 'is': [ u'Heimildir', u'Tilvísanir', ], 'it': [ u'Note', u'Riferimenti', ], 'ja': [ u'脚注', u'脚注欄', u'脚注・出典', u'出典', u'注釈', u'註', ], 'ko': [ u'주석', u'각주' u'주석 및 참고 자료' u'주석 및 참고자료', u'주석 및 참고 출처' ], 'lt': [ # not sure about which ones are preferred. u'Šaltiniai', u'Literatūra', ], 'nl': [ # not sure about which ones are preferred. u'Voetnoten', u'Voetnoot', u'Referenties', u'Noten', u'Bronvermelding', ], 'pdc': [ u'Aamarrickunge', ], 'pl': [ u'Przypisy', u'Uwagi', ], 'pt': [ u'Referências', ], 'sk': [ u'Referencie', ], 'szl': [ u'Przipisy', u'Připisy', ], 'th': [ u'อ้างอิง', u'เชิงอรรถ', u'หมายเหตุ', ], 'zh': [ u'參考資料', u'参考资料', u'參考文獻', u'参考文献', u'資料來源', u'资料来源', ], } # Templates which include a <references /> tag. If there is no such template # on your wiki, you don't have to enter anything here. referencesTemplates = { 'wikipedia': { 'ar': ['Reflist', 'مراجع', 'ثبت المراجع', 'ثبت_المراجع', 'بداية المراجع', 'نهاية المراجع'], 'be': [u'Зноскі', u'Примечания', u'Reflist', u'Спіс заўваг', u'Заўвагі'], 'be-tarask': [u'Зноскі'], 'ca': [u'Referències', u'Reflist', u'Listaref', u'Referència', u'Referencies', u'Referències2', u'Amaga', u'Amaga ref', u'Amaga Ref', u'Amaga Ref2', u'Apèndix'], 'da': [u'Reflist'], 'dsb': [u'Referency'], 'en': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference', u'Ref-list', u'Reference list', u'References-small', u'Reflink', u'Footnotes', u'FootnotesSmall'], 'eo': [u'Referencoj'], 'es': ['Listaref', 'Reflist', 'muchasref'], 'fa': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference', u'پانویس', u'پانویس‌ها ', u'پانویس ۲', u'پانویس۲', u'فهرست منابع'], 'fi': [u'Viitteet', u'Reflist'], 'fr': [u'Références', u'Notes', u'References', u'Reflist'], 'he': [u'הערות שוליים', u'הערה'], 'hsb': [u'Referency'], 'hu': [u'reflist', u'források', u'references', u'megjegyzések'], 'is': [u'reflist'], 'it': [u'References'], 'ja': [u'Reflist', u'脚注リスト'], 'ko': [u'주석', u'Reflist'], 'lt': [u'Reflist', u'Ref', u'Litref'], 'nl': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference', u'Ref-list', u'Reference list', u'References-small', u'Reflink', u'Referenties', u'Bron', u'Bronnen/noten/referenties', u'Bron2', u'Bron3', u'ref', u'references', u'appendix', u'Noot', u'FootnotesSmall'], 'pl': [u'Przypisy', u'Przypisy-lista', u'Uwagi'], 'pt': [u'Notas', u'ref-section', u'Referências', u'Reflist'], 'ru': [u'Reflist', u'Ref-list', u'Refs', u'Sources', u'Примечания', u'Список примечаний', u'Сноска', u'Сноски'], 'szl': [u'Przipisy', u'Připisy'], 'th': [u'รายการอ้างอิง'], 'zh': [u'Reflist', u'RefFoot', u'NoteFoot'], }, } # Text to be added instead of the <references /> tag. # Define this only if required by your wiki. referencesSubstitute = { 'wikipedia': { 'ar': u'{{مراجع}}', 'be': u'{{зноскі}}', 'da': u'{{reflist}}', 'dsb': u'{{referency}}', 'fa': u'{{پانویس}}', 'fi': u'{{viitteet}}', 'he': u'{{הערות שוליים}}', 'hsb': u'{{referency}}', 'hu': u'{{Források}}', 'pl': u'{{Przypisy}}', 'ru': u'{{примечания}}', 'szl': u'{{Przipisy}}', 'th': u'{{รายการอ้างอิง}}', 'zh': u'{{reflist}}', }, } # Sites where no title is required for references template # as it is already included there # like pl.wiki where {{Przypisy}} generates # == Przypisy == # <references /> noTitleRequired = [u'pl', u'be', u'szl'] maintenance_category = 'cite_error_refs_without_references_category' class XmlDumpNoReferencesPageGenerator: """ Generator which will yield Pages that might lack a references tag. These pages will be retrieved from a local XML dump file (pages-articles or pages-meta-current). """ def __init__(self, xmlFilename): """ Constructor. Arguments: * xmlFilename - The dump's path, either absolute or relative """ self.xmlFilename = xmlFilename self.refR = re.compile('</ref>', re.IGNORECASE) # The references tab can contain additional spaces and a group # attribute. self.referencesR = re.compile('<references.*?/>', re.IGNORECASE) def __iter__(self): """XML iterator.""" from pywikibot import xmlreader dump = xmlreader.XmlDump(self.xmlFilename) for entry in dump.parse(): text = textlib.removeDisabledParts(entry.text) if self.refR.search(text) and not self.referencesR.search(text): yield pywikibot.Page(pywikibot.Site(), entry.title) class NoReferencesBot(Bot): """References section bot.""" def __init__(self, generator, **kwargs): """Constructor.""" self.availableOptions.update({ 'verbose': True, }) super(NoReferencesBot, self).__init__(**kwargs) self.generator = pagegenerators.PreloadingGenerator(generator) self.site = pywikibot.Site() self.comment = i18n.twtranslate(self.site, 'noreferences-add-tag') self.refR = re.compile('</ref>', re.IGNORECASE) self.referencesR = re.compile('<references.*?/>', re.IGNORECASE) self.referencesTagR = re.compile('<references>.*?</references>', re.IGNORECASE | re.DOTALL) try: self.referencesTemplates = referencesTemplates[ self.site.family.name][self.site.code] except KeyError: self.referencesTemplates = [] try: self.referencesText = referencesSubstitute[ self.site.family.name][self.site.code] except KeyError: self.referencesText = u'<references />' def lacksReferences(self, text): """Check whether or not the page is lacking a references tag.""" oldTextCleaned = textlib.removeDisabledParts(text) if self.referencesR.search(oldTextCleaned) or \ self.referencesTagR.search(oldTextCleaned): if self.getOption('verbose'): pywikibot.output(u'No changes necessary: references tag found.') return False elif self.referencesTemplates: templateR = u'{{(' + u'|'.join(self.referencesTemplates) + ')' if re.search(templateR, oldTextCleaned, re.IGNORECASE | re.UNICODE): if self.getOption('verbose'): pywikibot.output( u'No changes necessary: references template found.') return False if not self.refR.search(oldTextCleaned): if self.getOption('verbose'): pywikibot.output(u'No changes necessary: no ref tags found.') return False else: if self.getOption('verbose'): pywikibot.output(u'Found ref without references.') return True def addReferences(self, oldText): """ Add a references tag into an existing section where it fits into. If there is no such section, creates a new section containing the references tag. * Returns : The modified pagetext """ # Do we have a malformed <reference> tag which could be repaired? # Repair two opening tags or a opening and an empty tag pattern = re.compile(r'< *references *>(.*?)' r'< */?\s*references */? *>', re.DOTALL) if pattern.search(oldText): pywikibot.output('Repairing references tag') return re.sub(pattern, '<references>\1</references>', oldText) # Repair single unclosed references tag pattern = re.compile(r'< *references *>') if pattern.search(oldText): pywikibot.output('Repairing references tag') return re.sub(pattern, '<references />', oldText) # Is there an existing section where we can add the references tag? for section in i18n.translate(self.site, referencesSections): sectionR = re.compile(r'\r?\n=+ *%s *=+ *\r?\n' % section) index = 0 while index < len(oldText): match = sectionR.search(oldText, index) if match: if textlib.isDisabled(oldText, match.start()): pywikibot.output( 'Existing %s section is commented out, skipping.' % section) index = match.end() else: pywikibot.output( 'Adding references tag to existing %s section...\n' % section) newText = ( oldText[:match.end()] + u'\n' + self.referencesText + u'\n' + oldText[match.end():] ) return newText else: break # Create a new section for the references tag for section in i18n.translate(self.site, placeBeforeSections): # Find out where to place the new section sectionR = re.compile(r'\r?\n(?P<ident>=+) *%s *(?P=ident) *\r?\n' % section) index = 0 while index < len(oldText): match = sectionR.search(oldText, index) if match: if textlib.isDisabled(oldText, match.start()): pywikibot.output( 'Existing %s section is commented out, won\'t add ' 'the references in front of it.' % section) index = match.end() else: pywikibot.output( u'Adding references section before %s section...\n' % section) index = match.start() ident = match.group('ident') return self.createReferenceSection(oldText, index, ident) else: break # This gets complicated: we want to place the new references # section over the interwiki links and categories, but also # over all navigation bars, persondata, and other templates # that are at the bottom of the page. So we need some advanced # regex magic. # The strategy is: create a temporary copy of the text. From that, # keep removing interwiki links, templates etc. from the bottom. # At the end, look at the length of the temp text. That's the position # where we'll insert the references section. catNamespaces = '|'.join(self.site.namespaces.CATEGORY) categoryPattern = r'\[\[\s*(%s)\s*:[^\n]*\]\]\s*' % catNamespaces interwikiPattern = r'\[\[([a-zA-Z\-]+)\s?:([^\[\]\n]*)\]\]\s*' # won't work with nested templates # the negative lookahead assures that we'll match the last template # occurrence in the temp text. # FIXME: # {{commons}} or {{commonscat}} are part of Weblinks section # * {{template}} is mostly part of a section # so templatePattern must be fixed templatePattern = r'\r?\n{{((?!}}).)+?}}\s*' commentPattern = r'<!--((?!-->).)*?-->\s*' metadataR = re.compile(r'(\r?\n)?(%s|%s|%s|%s)$' % (categoryPattern, interwikiPattern, templatePattern, commentPattern), re.DOTALL) tmpText = oldText while True: match = metadataR.search(tmpText) if match: tmpText = tmpText[:match.start()] else: break pywikibot.output( u'Found no section that can be preceeded by a new references ' u'section.\nPlacing it before interwiki links, categories, and ' u'bottom templates.') index = len(tmpText) return self.createReferenceSection(oldText, index) def createReferenceSection(self, oldText, index, ident='=='): """Create a reference section and insert it into the given text.""" if self.site.code in noTitleRequired: newSection = u'\n%s\n' % (self.referencesText) else: newSection = u'\n%s %s %s\n%s\n' % (ident, i18n.translate( self.site, referencesSections)[0], ident, self.referencesText) return oldText[:index] + newSection + oldText[index:] def run(self): """Run the bot.""" for page in self.generator: self.current_page = page try: text = page.text except pywikibot.NoPage: pywikibot.output(u"Page %s does not exist?!" % page.title(asLink=True)) continue except pywikibot.IsRedirectPage: pywikibot.output(u"Page %s is a redirect; skipping." % page.title(asLink=True)) continue except pywikibot.LockedPage: pywikibot.output(u"Page %s is locked?!" % page.title(asLink=True)) continue if page.isDisambig(): pywikibot.output(u"Page %s is a disambig; skipping." % page.title(asLink=True)) continue if self.site.sitename == 'wikipedia:en' and page.isIpEdit(): pywikibot.output( u"Page %s is edited by IP. Possible vandalized" % page.title(asLink=True)) continue if self.lacksReferences(text): newText = self.addReferences(text) try: self.userPut(page, page.text, newText, summary=self.comment) except pywikibot.EditConflict: pywikibot.output(u'Skipping %s because of edit conflict' % page.title()) except pywikibot.SpamfilterError as e: pywikibot.output( u'Cannot change %s because of blacklist entry %s' % (page.title(), e.url)) except pywikibot.LockedPage: pywikibot.output(u'Skipping %s (locked page)' % page.title()) def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg.startswith('-xml'): if len(arg) == 4: xmlFilename = i18n.input('pywikibot-enter-xml-filename') else: xmlFilename = arg[5:] genFactory.gens.append(XmlDumpNoReferencesPageGenerator(xmlFilename)) elif arg == '-always': options['always'] = True elif arg == '-quiet': options['verbose'] = False else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if not gen: site = pywikibot.Site() try: cat = site.expand_text( site.mediawiki_message(maintenance_category)) except: pass else: cat = pywikibot.Category(site, "%s:%s" % ( site.namespaces.CATEGORY, cat)) gen = cat.articles(namespaces=genFactory.namespaces or [0]) if gen: bot = NoReferencesBot(gen, **options) bot.run() return True else: pywikibot.bot.suggest_help(missing_generator=True) return False if __name__ == "__main__": main()<|fim▁end|>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#[cfg(test)] pub mod mocks; #[cfg(test)] mod spec_tests; use crate::{ cart::Cart, ppu::{control_register::IncrementAmount, write_latch::LatchState}, }; use std::cell::Cell; pub trait IVram: Default { fn write_ppu_addr(&self, latch_state: LatchState); fn write_ppu_data<C: Cart>(&mut self, val: u8, inc_amount: IncrementAmount, cart: &mut C); fn read_ppu_data<C: Cart>(&self, inc_amount: IncrementAmount, cart: &C) -> u8; fn ppu_data<C: Cart>(&self, cart: &C) -> u8; fn read<C: Cart>(&self, addr: u16, cart: &C) -> u8; fn read_palette(&self, addr: u16) -> u8; fn addr(&self) -> u16; fn scroll_write(&self, latch_state: LatchState); fn control_write(&self, val: u8); fn coarse_x_increment(&self); fn fine_y_increment(&self); fn copy_horizontal_pos_to_addr(&self); fn copy_vertical_pos_to_addr(&self); fn fine_x(&self) -> u8; } pub struct Vram { address: Cell<u16>, name_tables: [u8; 0x1000], palette: [u8; 0x20], ppu_data_buffer: Cell<u8>, t: Cell<u16>, fine_x: Cell<u8>, } impl Default for Vram { fn default() -> Self { Vram { address: Cell::new(0), name_tables: [0; 0x1000], palette: [0; 0x20], ppu_data_buffer: Cell::new(0), t: Cell::new(0), fine_x: Cell::new(0), } } } impl IVram for Vram { fn write_ppu_addr(&self, latch_state: LatchState) { // Addresses greater than 0x3fff are mirrored down match latch_state { LatchState::FirstWrite(val) => { // t: ..FEDCBA ........ = d: ..FEDCBA // t: .X...... ........ = 0 let t = self.t.get() & 0b1000_0000_1111_1111; self.t.set(((u16::from(val) & 0b0011_1111) << 8) | t) } LatchState::SecondWrite(val) => { // t: ....... HGFEDCBA = d: HGFEDCBA // v = t let t = u16::from(val) | (self.t.get() & 0b0111_1111_0000_0000); self.t.set(t); self.address.set(t); } } } fn write_ppu_data<C: Cart>(&mut self, val: u8, inc_amount: IncrementAmount, cart: &mut C) { let addr = self.address.get(); if addr < 0x2000 { cart.write_chr(addr, val); } else if addr < 0x3f00 { self.name_tables[addr as usize & 0x0fff] = val; } else if addr < 0x4000 { let addr = addr as usize & 0x1f; // Certain sprite addresses are mirrored back into background addresses let addr = match addr & 0xf { 0x0 => 0x0, 0x4 => 0x4, 0x8 => 0x8, 0xc => 0xc, _ => addr, }; self.palette[addr] = val; } <|fim▁hole|> IncrementAmount::One => self.address.set(self.address.get() + 1), IncrementAmount::ThirtyTwo => self.address.set(self.address.get() + 32), } } fn read_ppu_data<C: Cart>(&self, inc_amount: IncrementAmount, cart: &C) -> u8 { let val = self.ppu_data(cart); match inc_amount { IncrementAmount::One => self.address.set(self.address.get() + 1), IncrementAmount::ThirtyTwo => self.address.set(self.address.get() + 32), } val } fn ppu_data<C: Cart>(&self, cart: &C) -> u8 { let addr = self.address.get(); let val = self.read(addr, cart); // When reading while the VRAM address is in the range 0-$3EFF (i.e., before the palettes), // the read will return the contents of an internal read buffer. This internal buffer is // updated only when reading PPUDATA, and so is preserved across frames. After the CPU reads // and gets the contents of the internal buffer, the PPU will immediately update the // internal buffer with the byte at the current VRAM address if addr < 0x3f00 { let buffered_val = self.ppu_data_buffer.get(); self.ppu_data_buffer.set(val); buffered_val } else { val } } fn read<C: Cart>(&self, addr: u16, cart: &C) -> u8 { if addr < 0x2000 { cart.read_chr(addr) } else if addr < 0x3f00 { self.name_tables[addr as usize & 0x0fff] } else if addr < 0x4000 { let addr = addr & 0x1f; self.read_palette(addr) } else { panic!("Invalid vram read") } } fn read_palette(&self, addr: u16) -> u8 { // Certain sprite addresses are mirrored back into background addresses let addr = match addr & 0xf { 0x0 => 0x0, 0x4 => 0x4, 0x8 => 0x8, 0xc => 0xc, _ => addr, }; self.palette[addr as usize] } fn addr(&self) -> u16 { self.address.get() } fn scroll_write(&self, latch_state: LatchState) { match latch_state { LatchState::FirstWrite(val) => { // t: ....... ...HGFED = d: HGFED... let t = self.t.get() & 0b_1111_1111_1110_0000; self.t.set(((u16::from(val) & 0b_1111_1000) >> 3) | t); //x: CBA = d: .....CBA self.fine_x.set(val & 0b_0000_0111); } LatchState::SecondWrite(val) => { // t: CBA..HG FED..... = d: HGFEDCBA let t = self.t.get() & 0b_0000_1100_0001_1111; let cba_mask = (u16::from(val) & 0b_0000_0111) << 12; let hgfed_mask = (u16::from(val) & 0b_1111_1000) << 2; self.t.set((cba_mask | hgfed_mask) | t); } } } fn control_write(&self, val: u8) { // t: ...BA.. ........ = d: ......BA let t = self.t.get() & 0b0111_0011_1111_1111; let new_t = ((u16::from(val) & 0b0011) << 10) | t; self.t.set(new_t); } fn coarse_x_increment(&self) { let v = self.address.get(); // The coarse X component of v needs to be incremented when the next tile is reached. Bits // 0-4 are incremented, with overflow toggling bit 10. This means that bits 0-4 count from 0 // to 31 across a single nametable, and bit 10 selects the current nametable horizontally. let v = if v & 0x001F == 31 { // set coarse X = 0 and switch horizontal nametable (v & !0x001F) ^ 0x0400 } else { // increment coarse X v + 1 }; self.address.set(v); } fn fine_y_increment(&self) { let v = self.address.get(); let v = if v & 0x7000 != 0x7000 { // if fine Y < 7, increment fine Y v + 0x1000 } else { // if fine Y = 0... let v = v & !0x7000; // let y = coarse Y let mut y = (v & 0x03E0) >> 5; let v = if y == 29 { // set coarse Y to 0 y = 0; // switch vertical nametable v ^ 0x0800 } else if y == 31 { // set coarse Y = 0, nametable not switched y = 0; v } else { // increment coarse Y y += 1; v }; // put coarse Y back into v (v & !0x03E0) | (y << 5) }; self.address.set(v); } fn copy_horizontal_pos_to_addr(&self) { // At dot 257 of each scanline, if rendering is enabled, the PPU copies all bits related to // horizontal position from t to v: // v: ....F.. ...EDCBA = t: ....F.. ...EDCBA let v = self.address.get() & 0b0111_1011_1110_0000; self.address.set((self.t.get() & 0b0000_0100_0001_1111) | v) } fn copy_vertical_pos_to_addr(&self) { // During dots 280 to 304 of the pre-render scanline (end of vblank), if rendering is // enabled, at the end of vblank, shortly after the horizontal bits are copied from t to v // at dot 257, the PPU will repeatedly copy the vertical bits from t to v from dots 280 to // 304, completing the full initialization of v from t: // v: IHGF.ED CBA..... = t: IHGF.ED CBA..... let v = self.address.get() & 0b0000_0100_0001_1111; self.address.set((self.t.get() & 0b0111_1011_1110_0000) | v) } fn fine_x(&self) -> u8 { self.fine_x.get() } }<|fim▁end|>
match inc_amount {
<|file_name|>model_support.py<|end_file_name|><|fim▁begin|>from cuescience_shop.models import Client, Address, Order from natspec_utils.decorators import TextSyntax from cart.cart import Cart from django.test.client import Client as TestClient class ClientTestSupport(object): def __init__(self, test_case): self.test_case = test_case self.client = TestClient() @TextSyntax("Create address #1 #2 #3 #4", types=["str", "str", "str", "str"], return_type="Address") def create_address(self, street, number, postcode, city): address = Address(street=street, number=number, postcode=postcode, city=city) address.save() return address @TextSyntax("Create client #1 #2", types=["str", "str", "Address"], return_type="Client") def create_client(self, first_name, last_name, address): client = Client(first_name=first_name, last_name=last_name, shipping_address=address, billing_address=address) client.save() return client @TextSyntax("Create order", types=["Client"], return_type="Order") def create_order(self, client): cart = Cart(self.client) cart.create_cart() cart = cart.cart<|fim▁hole|> return order @TextSyntax("Assert client number is #1", types=["str", "Client"]) def assert_client_number(self, client_number, client): self.test_case.assertEqual(client_number, client.client_number) @TextSyntax("Assert order number is #1", types=["str", "Order"]) def assert_order_number(self, order_number, order): self.test_case.assertEqual(order_number, order.order_number)<|fim▁end|>
order = Order(client=client, cart=cart) order.save()
<|file_name|>TestSlotInfo.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler.declarative.allocator; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.jobmaster.SlotInfo; import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; /** Test {@link SlotInfo} implementation. */ class TestSlotInfo implements SlotInfo {<|fim▁hole|> private final AllocationID allocationId = new AllocationID(); @Override public AllocationID getAllocationId() { return allocationId; } @Override public TaskManagerLocation getTaskManagerLocation() { return new LocalTaskManagerLocation(); } @Override public int getPhysicalSlotNumber() { return 0; } @Override public ResourceProfile getResourceProfile() { return ResourceProfile.ANY; } @Override public boolean willBeOccupiedIndefinitely() { return false; } }<|fim▁end|>
<|file_name|>utils.js<|end_file_name|><|fim▁begin|>import { Dimensions, PixelRatio } from 'react-native'; const Utils = { ratio: PixelRatio.get(), pixel: 1 / PixelRatio.get(), size: { width: Dimensions.get('window').width, height: Dimensions.get('window').height, }, post(url, data, callback) { const fetchOptions = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(data), }; fetch(url, fetchOptions) .then(response => { response.json(); }) .then(responseData => { callback(responseData); }); }, };<|fim▁hole|><|fim▁end|>
export default Utils;
<|file_name|>forme.cpp<|end_file_name|><|fim▁begin|>#include "forme.h" /// /// \brief Forme::Forme /// Forme::Forme() { } /// /// \brief Forme::GetSize /// \return Nombre de points constituant la forme /// int Forme::GetSize() const { return L.size(); } /// /// \brief Forme::GetPoint /// \param i Indice du point /// \return Retourne le i-ème point(s) de la forme /// Nécessite que l'indice soit VALIDE. /// QPointF Forme::GetPoint(int i) const { return L.at(i); } <|fim▁hole|>/// \brief Forme::AddPoint Ajoute le point P à la forme /// \param P QPointF /// /// void Forme::AddPoint(const QPointF &P) { L.append(P); } /// /// \brief operator == Teste si les deux formes sont egales /// \param A Forme 1 /// \param B Forme 2 /// \return /// bool operator ==(Forme const &A, Forme const &B) { if (A.GetSize() != B.GetSize()) return false; for(int i=0; i<A.GetSize(); ++i) { if (A.GetPoint(i)!=B.GetPoint(i)) return false; } return true; } /// /// \brief Forme::generateExisting Génére une forme par défaut /// \n n=0 : Segment /// \n n=1 : Triangle /// \param n /// void Forme::generateExisting(quint32 n) { if(n==0) { //Segment0-1 this->AddPoint(QPointF(0.,0.)); this->AddPoint(QPointF(1.,0.)); } else if(n==1) { //Triangle this->AddPoint(QPointF(0.,0.)); this->AddPoint(QPointF(1.,0.)); this->AddPoint(QPointF(1./2.,qSqrt(3./4.))); } }<|fim▁end|>
///
<|file_name|>script.py<|end_file_name|><|fim▁begin|><|fim▁hole|>../../../../../../../share/pyshared/orca/scripts/apps/nautilus/script.py<|fim▁end|>
<|file_name|>in_process_lease.rs<|end_file_name|><|fim▁begin|>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::Result; use async_trait::async_trait; use context::CoreContext; use futures::{ channel::oneshot::{channel, Receiver, Sender}, future::Shared, future::{BoxFuture, FutureExt}, }; use std::collections::{hash_map::Entry, HashMap}; use std::sync::Arc; use tokio::sync::Mutex; use crate::LeaseOps;<|fim▁hole|>#[derive(Clone, Debug)] pub struct InProcessLease { leases: Arc<Mutex<HashMap<String, (Sender<()>, Shared<Receiver<()>>)>>>, } impl std::fmt::Display for InProcessLease { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "InProcessLease") } } impl InProcessLease { pub fn new() -> Self { Self { leases: Arc::new(Mutex::new(HashMap::new())), } } } #[async_trait] impl LeaseOps for InProcessLease { async fn try_add_put_lease(&self, key: &str) -> Result<bool> { let key = key.to_string(); let mut in_flight_leases = self.leases.lock().await; let entry = in_flight_leases.entry(key); if let Entry::Occupied(_) = entry { Ok(false) } else { let (send, recv) = channel(); entry.or_insert((send, recv.shared())); Ok(true) } } fn renew_lease_until(&self, _ctx: CoreContext, key: &str, done: BoxFuture<'static, ()>) { let this = self.clone(); let key = key.to_string(); tokio::spawn(async move { done.await; this.release_lease(&key).await; }); } async fn wait_for_other_leases(&self, key: &str) { let key = key.to_string(); let in_flight_leases = self.leases.lock().await; if let Some((_, fut)) = in_flight_leases.get(&key) { let _ = fut.clone().await; } } async fn release_lease(&self, key: &str) { let key = key.to_string(); let mut in_flight_leases = self.leases.lock().await; if let Some((sender, _)) = in_flight_leases.remove(&key) { // Don't care if there's no-one listening - just want to wake them up if possible. let _ = sender.send(()); } } }<|fim▁end|>
/// LeaseOps that use in-memory data structures to avoid two separate tasks writing to the same key
<|file_name|>meta_strategies.py<|end_file_name|><|fim▁begin|># Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Meta-strategy solvers for PSRO.""" import numpy as np from open_spiel.python.algorithms import lp_solver from open_spiel.python.algorithms import projected_replicator_dynamics import pyspiel EPSILON_MIN_POSITIVE_PROBA = 1e-8 def uniform_strategy(solver, return_joint=False): """Returns a Random Uniform distribution on policies. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: uniform distribution on strategies. """ policies = solver.get_policies() policy_lengths = [len(pol) for pol in policies] result = [np.ones(pol_len) / pol_len for pol_len in policy_lengths] if not return_joint: return result else: joint_strategies = get_joint_strategy_from_marginals(result) return result, joint_strategies def softmax_on_range(number_policies): x = np.array(list(range(number_policies))) x = np.exp(x-x.max()) x /= np.sum(x) return x def uniform_biased_strategy(solver, return_joint=False): """Returns a Biased Random Uniform distribution on policies. The uniform distribution is biased to prioritize playing against more recent policies (Policies that were appended to the policy list later in training) instead of older ones. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: uniform distribution on strategies. """ policies = solver.get_policies() if not isinstance(policies[0], list): policies = [policies] policy_lengths = [len(pol) for pol in policies] result = [softmax_on_range(pol_len) for pol_len in policy_lengths] if not return_joint: return result else: joint_strategies = get_joint_strategy_from_marginals(result) return result, joint_strategies def renormalize(probabilities): """Replaces all negative entries with zeroes and normalizes the result. Args: probabilities: probability vector to renormalize. Has to be one-dimensional. Returns: Renormalized probabilities. """ probabilities[probabilities < 0] = 0 probabilities = probabilities / np.sum(probabilities) return probabilities def get_joint_strategy_from_marginals(probabilities): """Returns a joint strategy matrix from a list of marginals. Args: probabilities: list of probabilities. Returns: A joint strategy from a list of marginals. """ probas = [] for i in range(len(probabilities)): probas_shapes = [1] * len(probabilities) probas_shapes[i] = -1 probas.append(probabilities[i].reshape(*probas_shapes)) result = np.product(probas) return result.reshape(-1) def nash_strategy(solver, return_joint=False): """Returns nash distribution on meta game matrix. This method only works for two player zero-sum games. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: Nash distribution on strategies. """ meta_games = solver.get_meta_game() if not isinstance(meta_games, list): meta_games = [meta_games, -meta_games] meta_games = [x.tolist() for x in meta_games] if len(meta_games) != 2: raise NotImplementedError( "nash_strategy solver works only for 2p zero-sum" "games, but was invoked for a {} player game".format(len(meta_games))) nash_prob_1, nash_prob_2, _, _ = ( lp_solver.solve_zero_sum_matrix_game( pyspiel.create_matrix_game(*meta_games))) result = [ renormalize(np.array(nash_prob_1).reshape(-1)), renormalize(np.array(nash_prob_2).reshape(-1)) ] if not return_joint: return result else: joint_strategies = get_joint_strategy_from_marginals(result) return result, joint_strategies <|fim▁hole|> """Computes Projected Replicator Dynamics strategies. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: PRD-computed strategies. """ meta_games = solver.get_meta_game() if not isinstance(meta_games, list): meta_games = [meta_games, -meta_games] kwargs = solver.get_kwargs() result = projected_replicator_dynamics.projected_replicator_dynamics( meta_games, **kwargs) if not return_joint: return result else: joint_strategies = get_joint_strategy_from_marginals(result) return result, joint_strategies META_STRATEGY_METHODS = { "uniform_biased": uniform_biased_strategy, "uniform": uniform_strategy, "nash": nash_strategy, "prd": prd_strategy, }<|fim▁end|>
def prd_strategy(solver, return_joint=False):
<|file_name|>impls_misc.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 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. //! This module contains `HashStable` implementations for various data types<|fim▁hole|>//! that don't fit into any of the other impls_xxx modules. impl_stable_hash_for!(enum ::session::search_paths::PathKind { Native, Crate, Dependency, Framework, ExternFlag, All }); impl_stable_hash_for!(enum ::rustc_target::spec::PanicStrategy { Abort, Unwind });<|fim▁end|>
<|file_name|>js__7hlBWPf1ttIudqF3iXkeU8oj7-zn_KRtVHFZdJJJ7v0__aTMdf5d7seM9dLI2fkwXQ2X0SNki2Q_-7ojT8gPzfnw__f87EqBUvTXEvjkncqMkj5xIZ6nPMQzVQhJdgieC7TpU.js<|end_file_name|><|fim▁begin|>(function($) { /** * Initialize editor instances. * * @todo Is the following note still valid for 3.x? * This function needs to be called before the page is fully loaded, as * calling tinyMCE.init() after the page is loaded breaks IE6. * * @param editorSettings * An object containing editor settings for each input format. */ Drupal.wysiwyg.editor.init.tinymce = function(settings) { // Fix Drupal toolbar obscuring editor toolbar in fullscreen mode. var $drupalToolbar = $('#toolbar', Drupal.overlayChild ? window.parent.document : document); tinyMCE.onAddEditor.add(function (mgr, ed) { if (ed.id == 'mce_fullscreen') { $drupalToolbar.hide(); } }); tinyMCE.onRemoveEditor.add(function (mgr, ed) { if (ed.id == 'mce_fullscreen') {<|fim▁hole|> } }); // Initialize editor configurations. for (var format in settings) { if (Drupal.settings.wysiwyg.plugins[format]) { // Load native external plugins. // Array syntax required; 'native' is a predefined token in JavaScript. for (var plugin in Drupal.settings.wysiwyg.plugins[format]['native']) { tinymce.PluginManager.load(plugin, Drupal.settings.wysiwyg.plugins[format]['native'][plugin]); } // Load Drupal plugins. for (var plugin in Drupal.settings.wysiwyg.plugins[format].drupal) { Drupal.wysiwyg.editor.instance.tinymce.addPlugin(plugin, Drupal.settings.wysiwyg.plugins[format].drupal[plugin], Drupal.settings.wysiwyg.plugins.drupal[plugin]); } } } }; /** * Attach this editor to a target element. * * See Drupal.wysiwyg.editor.attach.none() for a full desciption of this hook. */ Drupal.wysiwyg.editor.attach.tinymce = function(context, params, settings) { // Configure editor settings for this input format. var ed = new tinymce.Editor(params.field, settings); // Reset active instance id on any event. ed.onEvent.add(function(ed, e) { Drupal.wysiwyg.activeId = ed.id; }); // Indicate that the DOM has been loaded (in case of Ajax). tinymce.dom.Event.domLoaded = true; // Make toolbar buttons wrappable (required for IE). ed.onPostRender.add(function (ed) { var $toolbar = $('<div class="wysiwygToolbar"></div>'); $('#' + ed.editorContainer + ' table.mceToolbar > tbody > tr > td').each(function () { $('<div></div>').addClass(this.className).append($(this).children()).appendTo($toolbar); }); $('#' + ed.editorContainer + ' table.mceLayout td.mceToolbar').append($toolbar); $('#' + ed.editorContainer + ' table.mceToolbar').remove(); }); // Remove TinyMCE's internal mceItem class, which was incorrectly added to // submitted content by Wysiwyg <2.1. TinyMCE only temporarily adds the class // for placeholder elements. If preemptively set, the class prevents (native) // editor plugins from gaining an active state, so we have to manually remove // it prior to attaching the editor. This is done on the client-side instead // of the server-side, as Wysiwyg has no way to figure out where content is // stored, and the class only affects editing. $field = $('#' + params.field); $field.val($field.val().replace(/(<.+?\s+class=['"][\w\s]*?)\bmceItem\b([\w\s]*?['"].*?>)/ig, '$1$2')); // Attach editor. ed.render(); }; /** * Detach a single or all editors. * * See Drupal.wysiwyg.editor.detach.none() for a full desciption of this hook. */ Drupal.wysiwyg.editor.detach.tinymce = function (context, params, trigger) { if (typeof params != 'undefined') { var instance = tinyMCE.get(params.field); if (instance) { instance.save(); if (trigger != 'serialize') { instance.remove(); } } } else { // Save contents of all editors back into textareas. tinyMCE.triggerSave(); if (trigger != 'serialize') { // Remove all editor instances. for (var instance in tinyMCE.editors) { tinyMCE.editors[instance].remove(); } } } }; Drupal.wysiwyg.editor.instance.tinymce = { addPlugin: function(plugin, settings, pluginSettings) { if (typeof Drupal.wysiwyg.plugins[plugin] != 'object') { return; } tinymce.create('tinymce.plugins.' + plugin, { /** * Initialize the plugin, executed after the plugin has been created. * * @param ed * The tinymce.Editor instance the plugin is initialized in. * @param url * The absolute URL of the plugin location. */ init: function(ed, url) { // Register an editor command for this plugin, invoked by the plugin's button. ed.addCommand(plugin, function() { if (typeof Drupal.wysiwyg.plugins[plugin].invoke == 'function') { var data = { format: 'html', node: ed.selection.getNode(), content: ed.selection.getContent() }; // TinyMCE creates a completely new instance for fullscreen mode. var instanceId = ed.id == 'mce_fullscreen' ? ed.getParam('fullscreen_editor_id') : ed.id; Drupal.wysiwyg.plugins[plugin].invoke(data, pluginSettings, instanceId); } }); // Register the plugin button. ed.addButton(plugin, { title : settings.iconTitle, cmd : plugin, image : settings.icon }); // Load custom CSS for editor contents on startup. ed.onInit.add(function() { if (settings.css) { ed.dom.loadCSS(settings.css); } }); // Attach: Replace plain text with HTML representations. ed.onBeforeSetContent.add(function(ed, data) { var editorId = (ed.id == 'mce_fullscreen' ? ed.getParam('fullscreen_editor_id') : ed.id); if (typeof Drupal.wysiwyg.plugins[plugin].attach == 'function') { data.content = Drupal.wysiwyg.plugins[plugin].attach(data.content, pluginSettings, editorId); data.content = Drupal.wysiwyg.editor.instance.tinymce.prepareContent(data.content); } }); // Detach: Replace HTML representations with plain text. ed.onGetContent.add(function(ed, data) { var editorId = (ed.id == 'mce_fullscreen' ? ed.getParam('fullscreen_editor_id') : ed.id); if (typeof Drupal.wysiwyg.plugins[plugin].detach == 'function') { data.content = Drupal.wysiwyg.plugins[plugin].detach(data.content, pluginSettings, editorId); } }); // isNode: Return whether the plugin button should be enabled for the // current selection. ed.onNodeChange.add(function(ed, command, node) { if (typeof Drupal.wysiwyg.plugins[plugin].isNode == 'function') { command.setActive(plugin, Drupal.wysiwyg.plugins[plugin].isNode(node)); } }); }, /** * Return information about the plugin as a name/value array. */ getInfo: function() { return { longname: settings.title }; } }); // Register plugin. tinymce.PluginManager.add(plugin, tinymce.plugins[plugin]); }, openDialog: function(dialog, params) { var instanceId = this.getInstanceId(); var editor = tinyMCE.get(instanceId); editor.windowManager.open({ file: dialog.url + '/' + instanceId, width: dialog.width, height: dialog.height, inline: 1 }, params); }, closeDialog: function(dialog) { var editor = tinyMCE.get(this.getInstanceId()); editor.windowManager.close(dialog); }, prepareContent: function(content) { // Certain content elements need to have additional DOM properties applied // to prevent this editor from highlighting an internal button in addition // to the button of a Drupal plugin. var specialProperties = { img: { 'class': 'mceItem' } }; var $content = $('<div>' + content + '</div>'); // No .outerHTML() in jQuery :( // Find all placeholder/replacement content of Drupal plugins. $content.find('.drupal-content').each(function() { // Recursively process DOM elements below this element to apply special // properties. var $drupalContent = $(this); $.each(specialProperties, function(element, properties) { $drupalContent.find(element).andSelf().each(function() { for (var property in properties) { if (property == 'class') { $(this).addClass(properties[property]); } else { $(this).attr(property, properties[property]); } } }); }); }); return $content.html(); }, insert: function(content) { content = this.prepareContent(content); tinyMCE.execInstanceCommand(this.getInstanceId(), 'mceInsertContent', false, content); }, setContent: function (content) { content = this.prepareContent(content); tinyMCE.execInstanceCommand(this.getInstanceId(), 'mceSetContent', false, content); }, getContent: function () { return tinyMCE.get(this.getInstanceId()).getContent(); }, isFullscreen: function() { // TinyMCE creates a completely new instance for fullscreen mode. return tinyMCE.activeEditor.id == 'mce_fullscreen' && tinyMCE.activeEditor.getParam('fullscreen_editor_id') == this.field; }, getInstanceId: function () { return this.isFullscreen() ? 'mce_fullscreen' : this.field; } }; })(jQuery); ;/**/ (function($) { /** * Attach this editor to a target element. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * An object containing input format parameters. Default parameters are: * - editor: The internal editor name. * - theme: The name/key of the editor theme/profile to use. * - field: The CSS id of the target element. * @param settings * An object containing editor settings for all enabled editor themes. */ Drupal.wysiwyg.editor.attach.none = function(context, params, settings) { if (params.resizable) { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.addClass('resizable'); if (Drupal.behaviors.textarea) { Drupal.behaviors.textarea.attach(); } } }; /** * Detach a single or all editors. * * The editor syncs its contents back to the original field before its instance * is removed. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * (optional) An object containing input format parameters. If defined, * only the editor instance in params.field should be detached. Otherwise, * all editors should be detached and saved, so they can be submitted in * AJAX/AHAH applications. * @param trigger * A string describing why the editor is being detached. * Possible triggers are: * - unload: (default) Another or no editor is about to take its place. * - move: Currently expected to produce the same result as unload. * - serialize: The form is about to be serialized before an AJAX request or * a normal form submission. If possible, perform a quick detach and leave * the editor's GUI elements in place to avoid flashes or scrolling issues. * @see Drupal.detachBehaviors */ Drupal.wysiwyg.editor.detach.none = function (context, params, trigger) { if (typeof params != 'undefined' && (trigger != 'serialize')) { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.removeOnce('textarea').removeClass('.resizable-textarea') .find('.grippie').remove(); } }; /** * Instance methods for plain text areas. */ Drupal.wysiwyg.editor.instance.none = { insert: function(content) { var editor = document.getElementById(this.field); // IE support. if (document.selection) { editor.focus(); var sel = document.selection.createRange(); sel.text = content; } // Mozilla/Firefox/Netscape 7+ support. else if (editor.selectionStart || editor.selectionStart == '0') { var startPos = editor.selectionStart; var endPos = editor.selectionEnd; editor.value = editor.value.substring(0, startPos) + content + editor.value.substring(endPos, editor.value.length); } // Fallback, just add to the end of the content. else { editor.value += content; } }, setContent: function (content) { $('#' + this.field).val(content); }, getContent: function () { return $('#' + this.field).val(); } }; })(jQuery); ;/**/ /** * @file: Popup dialog interfaces for the media project. * * Drupal.media.popups.mediaBrowser * Launches the media browser which allows users to pick a piece of media. * * Drupal.media.popups.mediaStyleSelector * Launches the style selection form where the user can choose * what format / style they want their media in. * */ (function ($) { namespace('Drupal.media.popups'); /** * Media browser popup. Creates a media browser dialog. * * @param {function} * onSelect Callback for when dialog is closed, received (Array * media, Object extra); * @param {Object} * globalOptions Global options that will get passed upon initialization of the browser. * @see Drupal.media.popups.mediaBrowser.getDefaults(); * * @param {Object} * pluginOptions Options for specific plugins. These are passed * to the plugin upon initialization. If a function is passed here as * a callback, it is obviously not passed, but is accessible to the plugin * in Drupal.settings.variables. * * Example * pluginOptions = {library: {url_include_patterns:'/foo/bar'}}; * * @param {Object} * widgetOptions Options controlling the appearance and behavior of the * modal dialog. * @see Drupal.media.popups.mediaBrowser.getDefaults(); */ Drupal.media.popups.mediaBrowser = function (onSelect, globalOptions, pluginOptions, widgetOptions) { var options = Drupal.media.popups.mediaBrowser.getDefaults(); options.global = $.extend({}, options.global, globalOptions); options.plugins = pluginOptions; options.widget = $.extend({}, options.widget, widgetOptions); // Create it as a modal window. var browserSrc = options.widget.src; if ($.isArray(browserSrc) && browserSrc.length) { browserSrc = browserSrc[browserSrc.length - 1]; } // Params to send along to the iframe. WIP. var params = {}; $.extend(params, options.global); params.plugins = options.plugins; browserSrc += '&' + $.param(params); var mediaIframe = Drupal.media.popups.getPopupIframe(browserSrc, 'mediaBrowser'); // Attach the onLoad event mediaIframe.bind('load', options, options.widget.onLoad); /** * Setting up the modal dialog */ var ok = 'OK'; var notSelected = 'You have not selected anything!'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = options.dialog; dialogOptions.buttons[ok] = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("close"); }; var dialog = mediaIframe.dialog(dialogOptions); Drupal.media.popups.sizeDialog(dialog); Drupal.media.popups.resizeDialog(dialog); Drupal.media.popups.scrollDialog(dialog); Drupal.media.popups.overlayDisplace(dialog.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad = function (e) { var options = e.data; if (this.contentWindow.Drupal.media == undefined) return; if (this.contentWindow.Drupal.media.browser.selectedMedia.length > 0) { var ok = (Drupal && Drupal.t) ? Drupal.t('OK') : 'OK'; var ok_func = $(this).dialog('option', 'buttons')[ok]; ok_func.call(this); return; } }; Drupal.media.popups.mediaBrowser.getDefaults = function () { return { global: { types: [], // Types to allow, defaults to all. activePlugins: [] // If provided, a list of plugins which should be enabled. }, widget: { // Settings for the actual iFrame which is launched. src: Drupal.settings.media.browserUrl, // Src of the media browser (if you want to totally override it) onLoad: Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad // Onload function when iFrame loads. }, dialog: Drupal.media.popups.getDialogOptions() }; }; Drupal.media.popups.mediaBrowser.finalizeSelection = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("close"); } /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaStyleSelector = function (mediaFile, onSelect, options) { var defaults = Drupal.media.popups.mediaStyleSelector.getDefaults(); // @todo: remove this awful hack :( if (typeof defaults.src === 'string' ) { defaults.src = defaults.src.replace('-media_id-', mediaFile.fid) + '&fields=' + encodeURIComponent(JSON.stringify(mediaFile.fields)); } else { var src = defaults.src.shift(); defaults.src.unshift(src); defaults.src = src.replace('-media_id-', mediaFile.fid) + '&fields=' + encodeURIComponent(JSON.stringify(mediaFile.fields)); } options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaStyleSelector'); // Attach the onLoad event mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("close"); }; var dialog = mediaIframe.dialog(dialogOptions); Drupal.media.popups.sizeDialog(dialog); Drupal.media.popups.resizeDialog(dialog); Drupal.media.popups.scrollDialog(dialog); Drupal.media.popups.overlayDisplace(dialog.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaStyleSelector.getDefaults = function () { return { src: Drupal.settings.media.styleSelectorUrl, onLoad: Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad }; }; /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaFieldEditor = function (fid, onSelect, options) { var defaults = Drupal.media.popups.mediaFieldEditor.getDefaults(); // @todo: remove this awful hack :( defaults.src = defaults.src.replace('-media_id-', fid); options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaFieldEditor'); // Attach the onLoad event // @TODO - This event is firing too early in IE on Windows 7, // - so the height being calculated is too short for the content. mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("close"); }; var dialog = mediaIframe.dialog(dialogOptions); Drupal.media.popups.sizeDialog(dialog); Drupal.media.popups.resizeDialog(dialog); Drupal.media.popups.scrollDialog(dialog); Drupal.media.popups.overlayDisplace(dialog); return mediaIframe; }; Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaFieldEditor.getDefaults = function () { return { // @todo: do this for real src: '/media/-media_id-/edit?render=media-popup', onLoad: Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad }; }; /** * Generic functions to both the media-browser and style selector */ /** * Returns the commonly used options for the dialog. */ Drupal.media.popups.getDialogOptions = function () { return { buttons: {}, dialogClass: Drupal.settings.media.dialogOptions.dialogclass, modal: Drupal.settings.media.dialogOptions.modal, draggable: Drupal.settings.media.dialogOptions.draggable, resizable: Drupal.settings.media.dialogOptions.resizable, minWidth: Drupal.settings.media.dialogOptions.minwidth, width: Drupal.settings.media.dialogOptions.width, height: Drupal.settings.media.dialogOptions.height, position: Drupal.settings.media.dialogOptions.position, overlay: { backgroundColor: Drupal.settings.media.dialogOptions.overlay.backgroundcolor, opacity: Drupal.settings.media.dialogOptions.overlay.opacity }, zIndex: Drupal.settings.media.dialogOptions.zindex, close: function (event, ui) { $(event.target).remove(); } }; }; /** * Get an iframe to serve as the dialog's contents. Common to both plugins. */ Drupal.media.popups.getPopupIframe = function (src, id, options) { var defaults = {width: '100%', scrolling: 'auto'}; var options = $.extend({}, defaults, options); return $('<iframe class="media-modal-frame"/>') .attr('src', src) .attr('width', options.width) .attr('id', id) .attr('scrolling', options.scrolling); }; Drupal.media.popups.overlayDisplace = function (dialog) { if (parent.window.Drupal.overlay && jQuery.isFunction(parent.window.Drupal.overlay.getDisplacement)) { var overlayDisplace = parent.window.Drupal.overlay.getDisplacement('top'); if (dialog.offset().top < overlayDisplace) { dialog.css('top', overlayDisplace); } } } /** * Size the dialog when it is first loaded and keep it centered when scrolling. * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.sizeDialog = function (dialogElement) { if (!dialogElement.is(':visible')) { return; } var windowWidth = $(window).width(); var dialogWidth = windowWidth * 0.8; var windowHeight = $(window).height(); var dialogHeight = windowHeight * 0.8; dialogElement.dialog("option", "width", dialogWidth); dialogElement.dialog("option", "height", dialogHeight); dialogElement.dialog("option", "position", 'center'); $('.media-modal-frame').width('100%'); } /** * Resize the dialog when the window changes. * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.resizeDialog = function (dialogElement) { $(window).resize(function() { Drupal.media.popups.sizeDialog(dialogElement); }); } /** * Keeps the dialog centered when the window is scrolled. * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.scrollDialog = function (dialogElement) { // Keep the dialog window centered when scrolling. $(window).scroll(function() { if (!dialogElement.is(':visible')) { return; } dialogElement.dialog("option", "position", 'center'); }); } })(jQuery); ;/**/<|fim▁end|>
$drupalToolbar.show();
<|file_name|>test_tweetMining.py<|end_file_name|><|fim▁begin|>import unittest from tweetMining import TweetMining, TweetProxy, TestProxy, HttpProxy import nltk class TweetMiningTestCase(unittest.TestCase): def setUp(self): self.tweetMining = TweetMining(proxy='test') self.search = self.tweetMining.search(q="twitter") self.userInfoResponse = self.tweetMining.userInfo(username="fakeusername") def tearDown(self): self.tweetMining = None def test_instanceIsNotNone(self): self.assertIsNotNone(self.tweetMining) def test_tweetMiningIsInstanceOf(self): self.assertIsInstance(self.tweetMining, TweetMining) # setProxy def test_setProxy_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "setProxy"))) def test_setProxy_Raises_ExceptionWithWrongInput(self): self.assertRaises(Exception, self.tweetMining.setProxy, 1) self.assertRaises(Exception, self.tweetMining.setProxy, "wrong") def test_setProxy_Returns_TweetProxyInstance(self): actual = self.tweetMining.setProxy('test') self.assertIsInstance(actual, TweetProxy) def test_setProxy_Returns_TestProxyInstance(self): actual = self.tweetMining.setProxy('test') self.assertIsInstance(actual, TestProxy) def test_setProxy_Returns_HttpProxyInstance(self): actual = self.tweetMining.setProxy('http') self.assertIsInstance(actual, HttpProxy) # Trends def test_Trends_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "trends"))) def test_Trends_returnsADict(self): self.assertIsInstance(self.tweetMining.trends(), type({})) def test_Trends_containsTrendsKey(self): result = self.tweetMining.trends() actual = 'trends' in result.keys() self.assertTrue(actual) def test_TrendsKeyIsAnArray(self): result = self.tweetMining.trends() actual = result['trends'] self.assertTrue(isinstance(actual, list)) def test_Trends_containsAs_OfKey(self): result = self.tweetMining.trends() actual = 'as_of' in result.keys() self.assertTrue(actual) def test_As_OfKeyIsAString(self): result = self.tweetMining.trends() actual = str(result['as_of']) self.assertTrue(isinstance(actual, str)) # Search def test_search_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "search"))) def test_search_returnsADict(self): self.assertIsInstance(self.search, type({})) def test_search_containsResultsKey(self): actual = 'results' in self.search.keys() self.assertTrue(actual) def test_ResultsKeyIsAnArray(self): actual = self.search['results'] self.assertTrue(isinstance(actual, list)) def test_search_containsSince_IdKey(self): actual = 'since_id' in self.search.keys() self.assertTrue(actual) def test_ResultsKeyIsAnArray(self): actual = self.search['since_id'] self.assertTrue(isinstance(actual, int)) def test_search_containsQueryKey(self): actual = 'query' in self.search.keys() self.assertTrue(actual) def test_QueryKeyIsAString(self): actual = self.search['query'] self.assertTrue(isinstance(actual, (str, unicode))) def test_search_containsResults_per_pageKey(self): actual = 'results_per_page' in self.search.keys() self.assertTrue(actual) def test_Results_Per_PageKeyIsAnInt(self): actual = self.search['results_per_page'] self.assertTrue(isinstance(actual, int)) def test_search_containsMaxIdKey(self): actual = 'max_id' in self.search.keys() self.assertTrue(actual) def test_Max_IdKeyIsAnInteger(self): actual = self.search['max_id'] self.assertTrue(isinstance(actual, (int, long))) def test_serach_containsPageKey(self): actual = 'page' in self.search.keys() self.assertTrue(actual) def test_PageKeyIsAnInt(self): actual = self.search['page'] self.assertTrue(isinstance(actual, int)) def test_search_containsNextPageKey(self): actual = 'next_page' in self.search.keys() self.assertTrue(actual) def test_NextPageKeyIsAString(self): actual = self.search['next_page'] self.assertTrue(isinstance(actual, (str, unicode))) def test_search_containsCompleted_InKey(self): actual = 'completed_in' in self.search.keys() self.assertTrue(actual) def test_CompletedInKeyIsFloat(self): actual = self.search['completed_in'] self.assertTrue(isinstance(actual, (float))) def test_search_containsRefreshUrlKey(self): actual = 'refresh_url' in self.search.keys() self.assertTrue(actual) def test_RefreshUrlKeyIsAString(self): actual = self.search['refresh_url'] self.assertTrue(isinstance(actual, (str, unicode))) # Words def test_words_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "words"))) def test_words_raisesAnExceptionWithWrongInput(self): self.assertRaises(Exception, self.tweetMining.words, 1) self.assertRaises(Exception, self.tweetMining.words, "1") self.assertRaises(Exception, self.tweetMining.words, (1,)) self.assertRaises(Exception, self.tweetMining.words, {1:1}) def test_words_acceptsAListAsInput(self): self.assertIsInstance(self.tweetMining.words([]), list) def test_words_returnsAnArray(self): actual = self.tweetMining.words(self.search['results']) self.assertIsInstance(actual, list) # FreqDist def test_freqDist_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "freqDist"))) def test_freqDist_raisesAnExceptionWithWrongInput(self): self.assertRaises(Exception, self.tweetMining.freqDist, 1) self.assertRaises(Exception, self.tweetMining.freqDist, "1") self.assertRaises(Exception, self.tweetMining.freqDist, (1,)) self.assertRaises(Exception, self.tweetMining.freqDist, {1:1}) def test_freqDist_acceptsAListAsInput(self): self.assertEquals(type(self.tweetMining.freqDist([])), nltk.probability.FreqDist) def test_freqDist_returnsAnArray(self): words = self.tweetMining.words(self.search['results']) actual = self.tweetMining.freqDist(words) self.assertEquals(type(actual), nltk.probability.FreqDist) # _get_rt_sources def test_getRTSources_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "_getRTSources"))) def test_getRTSources_returnsAList(self): actual = self.tweetMining._getRTSources('RT @user la la la') self.assertIsInstance(actual, list) def test_getRTSources_raisesAnExceptionWithWrongInput(self): self.assertRaises(Exception, self.tweetMining._getRTSources, 1) self.assertRaises(Exception, self.tweetMining._getRTSources, []) self.assertRaises(Exception, self.tweetMining._getRTSources, {}) # buildRetweetGraph def test_buildRetweetGraph_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "buildRetweetGraph"))) def test_buildRetweetGraph_ReturnsADict(self): actual = self.tweetMining.buildRetweetGraph(self.search['results']) self.assertIsInstance(actual, dict) def test_buildRetweetGraph_Dict_containsGraphKey(self): actual = self.tweetMining.buildRetweetGraph(self.search['results']) self.assertTrue('graph' in actual.keys()) self.assertIsNotNone(actual['graph']) def test_buildRetweetGraph_RaisesAnExceptionWithWrongInput(self): self.assertRaises(Exception ,self.tweetMining.buildRetweetGraph, 1) self.assertRaises(Exception ,self.tweetMining.buildRetweetGraph, "1") self.assertRaises(Exception ,self.tweetMining.buildRetweetGraph, {}) # userInfo def test_userInfo_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "userInfo"))) def test_userInfo_ReturnsADict(self): actual = self.userInfoResponse self.assertIsInstance(actual, dict) def test_userInfo_Dict_ContainsAProfile_Background_TileKey(self): key = 'profile_background_tile' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, bool) def test_userInfo_Dict_ContainsAProtectedKey(self): key = 'protected' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, bool) def test_userInfo_Dict_ContainsAShow_All_Inline_MediaKey(self): key = 'show_all_inline_media' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, bool) def test_userInfo_Dict_ContainsAListedCountKey(self): key = 'listed_count' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, int) def test_userInfo_Dict_ContainsAContributorsEnabledKey(self): key = 'contributors_enabled' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, bool) def test_userInfo_Dict_ContainsAProfile_Sidebar_fill_colorKey(self): key = 'profile_sidebar_fill_color' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, unicode) def test_userInfo_Dict_ContainsANameKey(self): key = 'name' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, unicode) def test_userInfo_Dict_Contains_VerifiedKey(self): key = 'verified' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, bool) def test_userInfo_Dict_Contains_LangKey(self): key = 'lang' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, unicode) def test_userInfo_Dict_Contains_DescriptionKey(self): key = 'description' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, unicode)<|fim▁hole|> def test_userInfo_Dict_Contains_StatusesCountKey(self): key = 'statuses_count' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, int) def test_userInfo_Dict_Contains_Profile_Image_Url(self): key = 'profile_image_url' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, unicode) def test_userInfo_Dict_Contains_StatusKey(self): key = 'status' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, dict) def test_userInfo_Dict_Contains_UrlKey(self): key = 'url' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, unicode) def test_userInfo_Dict_Contains_Screen_NameKey(self): key = 'screen_name' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value,unicode) def test_userInfo_Dict_Contains_Friends_CountKey(self): key = 'friends_count' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, int) def test_userInfo_Dict_Contains_Followers_CountKey(self): key = 'followers_count' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, int) def test_userInfo_Dict_Contains_Favourites_CountKey(self): key = 'favourites_count' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, int) def test_userInfo_Dict_Contains_IdKey(self): key = 'id' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, int) def test_userInfo_Dict_Contains_IdStrKey(self): key = 'id_str' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, unicode) # _getFactory def test_userInfo_Dict_Contains_Friends_CountKey(self): key = 'friends_count' value = self.userInfoResponse.get(key) self.assertTrue(key in self.userInfoResponse.keys()) self.assertIsInstance(value, int) def test__getFactoryProxy_exists(self): self.assertTrue(callable(getattr(self.tweetMining, "_getFactoryProxy"))) def test__getFactoryProxy_Raises_ExceptionWithWrongInput(self): self.assertRaises(Exception, self.tweetMining._getFactoryProxy, "wrong") self.assertRaises(Exception, self.tweetMining._getFactoryProxy, 1) def test__getFactoryProxy_Returns_TweetProxyInstance(self): actual = self.tweetMining._getFactoryProxy('test') self.assertIsInstance(actual, TweetProxy)<|fim▁end|>
<|file_name|>ac97_mixer.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::pci::ac97_regs::*; // AC97 Vendor ID const AC97_VENDOR_ID1: u16 = 0x8086; const AC97_VENDOR_ID2: u16 = 0x8086; // Extented Audio ID const AC97_EXTENDED_ID: u16 = MIXER_EI_VRA | MIXER_EI_CDAC | MIXER_EI_SDAC | MIXER_EI_LDAC; // Master volume register is specified in 1.5dB steps. const MASTER_VOLUME_STEP_DB: f64 = 1.5; /// `Ac97Mixer` holds the mixer state for the AC97 bus. /// The mixer is used by calling the `readb`/`readw`/`readl` functions to read register values and /// the `writeb`/`writew`/`writel` functions to set register values. pub struct Ac97Mixer { // Mixer Registers master_volume_l: u8, master_volume_r: u8, master_mute: bool, mic_muted: bool, mic_20db: bool, mic_volume: u8, record_gain_l: u8, record_gain_r: u8, record_gain_mute: bool, pcm_out_vol_l: u16, pcm_out_vol_r: u16, pcm_out_mute: bool, power_down_control: u16, ext_audio_status_ctl: u16, pcm_front_dac_rate: u16, pcm_surr_dac_rate: u16, pcm_lfe_dac_rate: u16, } impl Ac97Mixer { /// Creates an 'Ac97Mixer' with the standard default register values. pub fn new() -> Self { Ac97Mixer { master_volume_l: 0, master_volume_r: 0, master_mute: true, mic_muted: true, mic_20db: false, mic_volume: 0x8, record_gain_l: 0, record_gain_r: 0, record_gain_mute: true, pcm_out_vol_l: 0x8, pcm_out_vol_r: 0x8, pcm_out_mute: true, power_down_control: PD_REG_STATUS_MASK, // Report everything is ready. ext_audio_status_ctl: 0, // Default to 48 kHz. pcm_front_dac_rate: 0xBB80, pcm_surr_dac_rate: 0xBB80, pcm_lfe_dac_rate: 0xBB80, } } pub fn reset(&mut self) { // Upon reset, the audio sample rate registers default to 48 kHz, and VRA=0. self.ext_audio_status_ctl &= !MIXER_EI_VRA; self.pcm_front_dac_rate = 0xBB80; self.pcm_surr_dac_rate = 0xBB80; self.pcm_lfe_dac_rate = 0xBB80; } /// Reads a word from the register at `offset`. pub fn readw(&self, offset: u64) -> u16 { match offset { MIXER_RESET_00 => BC_DEDICATED_MIC, MIXER_MASTER_VOL_MUTE_02 => self.get_master_reg(), MIXER_MIC_VOL_MUTE_0E => self.get_mic_volume(), MIXER_PCM_OUT_VOL_MUTE_18 => self.get_pcm_out_volume(), MIXER_REC_VOL_MUTE_1C => self.get_record_gain_reg(), MIXER_POWER_DOWN_CONTROL_26 => self.power_down_control, MIXER_EXTENDED_AUDIO_ID_28 => AC97_EXTENDED_ID, MIXER_VENDOR_ID1_7C => AC97_VENDOR_ID1, MIXER_VENDOR_ID2_7E => AC97_VENDOR_ID2, MIXER_EXTENDED_AUDIO_STATUS_CONTROL_28 => self.ext_audio_status_ctl, MIXER_PCM_FRONT_DAC_RATE_2C => self.pcm_front_dac_rate, MIXER_PCM_SURR_DAC_RATE_2E => self.pcm_surr_dac_rate, MIXER_PCM_LFE_DAC_RATE_30 => self.pcm_lfe_dac_rate, _ => 0, } } /// Writes a word `val` to the register `offset`. pub fn writew(&mut self, offset: u64, val: u16) { match offset { MIXER_RESET_00 => self.reset(), MIXER_MASTER_VOL_MUTE_02 => self.set_master_reg(val), MIXER_MIC_VOL_MUTE_0E => self.set_mic_volume(val), MIXER_PCM_OUT_VOL_MUTE_18 => self.set_pcm_out_volume(val), MIXER_REC_VOL_MUTE_1C => self.set_record_gain_reg(val), MIXER_POWER_DOWN_CONTROL_26 => self.set_power_down_reg(val), MIXER_EXTENDED_AUDIO_STATUS_CONTROL_28 => self.ext_audio_status_ctl = val, MIXER_PCM_FRONT_DAC_RATE_2C => self.pcm_front_dac_rate = val, MIXER_PCM_SURR_DAC_RATE_2E => self.pcm_surr_dac_rate = val, MIXER_PCM_LFE_DAC_RATE_30 => self.pcm_lfe_dac_rate = val, _ => (), } } /// Returns the mute status and left and right attenuation from the master volume register. pub fn get_master_volume(&self) -> (bool, f64, f64) { ( self.master_mute, f64::from(self.master_volume_l) * MASTER_VOLUME_STEP_DB, f64::from(self.master_volume_r) * MASTER_VOLUME_STEP_DB, ) } /// Returns the front sample rate (reg 0x2c). pub fn get_sample_rate(&self) -> u16 { // MIXER_PCM_FRONT_DAC_RATE_2C, MIXER_PCM_SURR_DAC_RATE_2E, and MIXER_PCM_LFE_DAC_RATE_30 // are updated to the same rate when playback with 2,4 and 6 tubes. self.pcm_front_dac_rate } // Returns the master mute and l/r volumes (reg 0x02). fn get_master_reg(&self) -> u16 { let reg = (u16::from(self.master_volume_l)) << 8 | u16::from(self.master_volume_r); if self.master_mute { reg | MUTE_REG_BIT } else { reg } } // Handles writes to the master register (0x02).<|fim▁hole|> self.master_volume_l = (val >> 8 & VOL_REG_MASK) as u8; } // Returns the value read in the Mic volume register (0x0e). fn get_mic_volume(&self) -> u16 { let mut reg = u16::from(self.mic_volume); if self.mic_muted { reg |= MUTE_REG_BIT; } if self.mic_20db { reg |= MIXER_MIC_20DB; } reg } // Sets the mic input mute, boost, and volume settings (0x0e). fn set_mic_volume(&mut self, val: u16) { self.mic_volume = (val & MIXER_VOL_MASK) as u8; self.mic_muted = val & MUTE_REG_BIT != 0; self.mic_20db = val & MIXER_MIC_20DB != 0; } // Returns the value read in the Mic volume register (0x18). fn get_pcm_out_volume(&self) -> u16 { let reg = (self.pcm_out_vol_l as u16) << 8 | self.pcm_out_vol_r as u16; if self.pcm_out_mute { reg | MUTE_REG_BIT } else { reg } } // Sets the pcm output mute and volume states (0x18). fn set_pcm_out_volume(&mut self, val: u16) { self.pcm_out_vol_r = val & MIXER_VOL_MASK; self.pcm_out_vol_l = (val >> MIXER_VOL_LEFT_SHIFT) & MIXER_VOL_MASK; self.pcm_out_mute = val & MUTE_REG_BIT != 0; } // Returns the record gain register (0x01c). fn get_record_gain_reg(&self) -> u16 { let reg = u16::from(self.record_gain_l) << 8 | u16::from(self.record_gain_r); if self.record_gain_mute { reg | MUTE_REG_BIT } else { reg } } // Handles writes to the record_gain register (0x1c). fn set_record_gain_reg(&mut self, val: u16) { self.record_gain_mute = val & MUTE_REG_BIT != 0; self.record_gain_r = (val & VOL_REG_MASK) as u8; self.record_gain_l = (val >> 8 & VOL_REG_MASK) as u8; } // Handles writes to the powerdown ctrl/status register (0x26). fn set_power_down_reg(&mut self, val: u16) { self.power_down_control = (val & !PD_REG_STATUS_MASK) | (self.power_down_control & PD_REG_STATUS_MASK); } }<|fim▁end|>
fn set_master_reg(&mut self, val: u16) { self.master_mute = val & MUTE_REG_BIT != 0; self.master_volume_r = (val & VOL_REG_MASK) as u8;
<|file_name|>mdbver.java<|end_file_name|><|fim▁begin|>/* * #%L * Fork of MDB Tools (Java port). * %% * Copyright (C) 2008 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /* * Created on Jan 14, 2005 * * TODO To change the template for this generated file go to<|fim▁hole|>/** * @author calvin * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class mdbver { public static void main(String[] args) { } }<|fim▁end|>
* Window - Preferences - Java - Code Style - Code Templates */ package mdbtools.libmdb06util;
<|file_name|>scribe.py<|end_file_name|><|fim▁begin|>import io import sys isPython3 = sys.version_info >= (3, 0) class Scribe: @staticmethod def read(path): with io.open(path, mode="rt", encoding="utf-8") as f: s = f.read() # go to beginning f.seek(0) return s @staticmethod def read_beginning(path, lines): with io.open(path, mode="rt", encoding="utf-8") as f: s = f.read(lines) # go to beginning f.seek(0) return s @staticmethod def read_lines(path): with io.open(path, mode="rt", encoding="utf-8") as f: content = f.readlines() return content @staticmethod def write(contents, path): if isPython3: with open(path, mode="wt", encoding="utf-8") as f: # truncate previous contents f.truncate() f.write(contents) else: <|fim▁hole|> with io.open(path, mode="wt", encoding="utf-8") as f: # truncate previous contents f.truncate() f.write(contents.decode("utf8")) @staticmethod def write_lines(lines, path): if isPython3: with open(path, mode="wt", encoding="utf-8") as f: f.writelines([l + "\n" for l in lines]) else: with io.open(path, mode="wt") as f: for line in lines: f.writelines(line.decode("utf8") + "\n") @staticmethod def add_content(contents, path): if isPython3: with open(path, mode="a", encoding="utf-8") as f: f.writelines(contents) else: with io.open(path, mode="a") as f: f.writelines(contents.decode("utf8"))<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#/usr/bin/env python # -#- coding: utf-8 -#- # # equity_master/tests/__init__.py - equity masger unit test package # # Standard copyright message # # # # Initial version: 2012-04-02 # Author: Amnon Janiv """ .. module:: equity_master/tests :synopsis: equity_master module unit test package This package is designed to demonstrate TDD best practices: - Structured approach to test data creation - Per module unit test (not achievable due to time constraints) - Per public and critical private class method, instance method, and function test cases - Valid and invalid test suites and test cases - Object life cycle including creation, configuration, validation - Structured for expansion as more functionality is to be tested - Implement unit test first, flushing out interfaces and underlying functionality iteratively - Each module is structured to be easily customized on specific functionality being developed. - Include functional, performance, and memory utilization test cases While using the underlying python unit test module, the implementation would be relatively simple to port to other unit test frameworks. Each test module is name x_test, where x is the corresponding module under test. In order to run all the tests, execute 'python run_tests The tests can be executed stand alone as well as when using an IDE such as Eclipse <|fim▁hole|>- common.py - common classes used - equity_master_tests - higher level process tests - process tests - process creation - regexp_tests - regular expression related tests .. moduleauthor:: Amnon Janiv """ __revision__ = '$Id: $' __version__ = '0.0.1'<|fim▁end|>
It is comprised of the following modules:
<|file_name|>Session.ts<|end_file_name|><|fim▁begin|>import { PushRequest } from './../protocol/push/PushRequest'; import { PushRequestNewObject } from './../protocol/push/PushRequestNewObject'; import { PushRequestObject } from './../protocol/push/PushRequestObject'; import { PushResponse } from './../protocol/push/PushResponse'; import { PushResponseNewObject } from './../protocol/push/PushResponseNewObject'; import { ResponseType } from './../protocol/ResponseType'; import { SyncResponse } from './../protocol/sync/SyncResponse'; import { INewSessionObject, ISessionObject, SessionObject } from './SessionObject'; import { IWorkspace } from './Workspace'; import { WorkspaceObject } from './WorkspaceObject'; export interface ISession { hasChanges: boolean; get(id: string): ISessionObject; create(objectTypeName: string): ISessionObject; delete(object: ISessionObject): void; pushRequest(): PushRequest; pushResponse(saveResponse: PushResponse): void; reset(): void; } export class Session implements ISession { private static idCounter = 0; public hasChanges: boolean; private sessionObjectById: { [id: string]: ISessionObject } = {}; private newSessionObjectById: { [id: string]: INewSessionObject } = {}; constructor(private workspace: IWorkspace) { this.hasChanges = false; } public get(id: string): ISessionObject { if (!id) { return undefined; } let sessionObject: ISessionObject = this.sessionObjectById[id]; if (sessionObject === undefined) { sessionObject = this.newSessionObjectById[id]; if (sessionObject === undefined) { const workspaceObject: WorkspaceObject = this.workspace.get(id); const constructor: any = this.workspace.constructorByName[ workspaceObject.objectType.name ]; sessionObject = new constructor(); sessionObject.session = this; sessionObject.workspaceObject = workspaceObject; sessionObject.objectType = workspaceObject.objectType; this.sessionObjectById[sessionObject.id] = sessionObject; } } return sessionObject; } public create(objectTypeName: string): ISessionObject { const constructor: any = this.workspace.constructorByName[objectTypeName]; const newSessionObject: INewSessionObject = new constructor(); newSessionObject.session = this; newSessionObject.objectType = this.workspace.metaPopulation.objectTypeByName[ objectTypeName ]; newSessionObject.newId = (--Session.idCounter).toString(); this.newSessionObjectById[newSessionObject.newId] = newSessionObject; this.hasChanges = true; return newSessionObject; } public delete(object: ISessionObject): void { if (!object.isNew) { throw new Error('Existing objects can not be deleted'); } const newSessionObject = object as SessionObject; const newId = newSessionObject.newId; if (this.newSessionObjectById && this.newSessionObjectById.hasOwnProperty(newId)) { Object.keys(this.newSessionObjectById).forEach((key: string) => (this.newSessionObjectById[key] as SessionObject).onDelete(newSessionObject), ); if (this.sessionObjectById) { Object.keys(this.sessionObjectById).forEach((key: string) => (this.sessionObjectById[key] as SessionObject).onDelete(newSessionObject), ); } newSessionObject.reset(); delete this.newSessionObjectById[newId]; } } public reset(): void { if (this.newSessionObjectById) { Object.keys(this.newSessionObjectById).forEach((key: string) => this.newSessionObjectById[key].reset(), ); } if (this.sessionObjectById) { Object.keys(this.sessionObjectById).forEach((key: string) => this.sessionObjectById[key].reset(), ); } this.hasChanges = false; } public pushRequest(): PushRequest { const data: PushRequest = new PushRequest(); data.newObjects = []; data.objects = []; if (this.newSessionObjectById) { Object.keys(this.newSessionObjectById).forEach((key: string) => { const newSessionObject: INewSessionObject = this.newSessionObjectById[ key ]; const objectData: PushRequestNewObject = newSessionObject.saveNew(); if (objectData !== undefined) { data.newObjects.push(objectData); } }); } if (this.sessionObjectById) { Object.keys(this.sessionObjectById).forEach((key: string) => { const sessionObject: ISessionObject = this.sessionObjectById[key]; const objectData: PushRequestObject = sessionObject.save(); if (objectData !== undefined) { data.objects.push(objectData); } }); } return data; }<|fim▁hole|> if (pushResponse.newObjects) { Object.keys(pushResponse.newObjects).forEach((key: string) => { const pushResponseNewObject: PushResponseNewObject = pushResponse.newObjects[key]; const newId: string = pushResponseNewObject.ni; const id: string = pushResponseNewObject.i; const newSessionObject: INewSessionObject = this.newSessionObjectById[ newId ]; const syncResponse: SyncResponse = { hasErrors: false, objects: [ { i: id, methods: [], roles: [], t: newSessionObject.objectType.name, v: '', }, ], responseType: ResponseType.Sync, userSecurityHash: '#', // This should trigger a load on next check }; delete this.newSessionObjectById[newId]; delete newSessionObject.newId; this.workspace.sync(syncResponse); const workspaceObject: WorkspaceObject = this.workspace.get(id); newSessionObject.workspaceObject = workspaceObject; this.sessionObjectById[id] = newSessionObject; }); } if (Object.getOwnPropertyNames(this.newSessionObjectById).length !== 0) { throw new Error('Not all new objects received ids'); } } }<|fim▁end|>
public pushResponse(pushResponse: PushResponse): void {
<|file_name|>ModelOrBuilder.java<|end_file_name|><|fim▁begin|>// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/ml/v1beta1/model_service.proto package com.google.cloud.ml.api.v1beta1; public interface ModelOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.ml.v1beta1.Model) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. The name specified for the model when it was created. * The model name must be unique within the project it is created in. * </pre> * * <code>optional string name = 1;</code> */ java.lang.String getName(); /** * <pre> * Required. The name specified for the model when it was created. * The model name must be unique within the project it is created in.<|fim▁hole|> * * <code>optional string name = 1;</code> */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> * Optional. The description specified for the model when it was created. * </pre> * * <code>optional string description = 2;</code> */ java.lang.String getDescription(); /** * <pre> * Optional. The description specified for the model when it was created. * </pre> * * <code>optional string description = 2;</code> */ com.google.protobuf.ByteString getDescriptionBytes(); /** * <pre> * Output only. The default version of the model. This version will be used to * handle prediction requests that do not specify a version. * You can change the default version by calling * [projects.methods.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault). * </pre> * * <code>optional .google.cloud.ml.v1beta1.Version default_version = 3;</code> */ boolean hasDefaultVersion(); /** * <pre> * Output only. The default version of the model. This version will be used to * handle prediction requests that do not specify a version. * You can change the default version by calling * [projects.methods.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault). * </pre> * * <code>optional .google.cloud.ml.v1beta1.Version default_version = 3;</code> */ com.google.cloud.ml.api.v1beta1.Version getDefaultVersion(); /** * <pre> * Output only. The default version of the model. This version will be used to * handle prediction requests that do not specify a version. * You can change the default version by calling * [projects.methods.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault). * </pre> * * <code>optional .google.cloud.ml.v1beta1.Version default_version = 3;</code> */ com.google.cloud.ml.api.v1beta1.VersionOrBuilder getDefaultVersionOrBuilder(); }<|fim▁end|>
* </pre>
<|file_name|>encrypting_serializer.go<|end_file_name|><|fim▁begin|>package session import ( "crypto/sha256" "fmt" "github.com/fasthttp/session/v2" "github.com/authelia/authelia/v4/internal/utils" ) // EncryptingSerializer a serializer encrypting the data with AES-GCM with 256-bit keys. type EncryptingSerializer struct { key [32]byte } // NewEncryptingSerializer return new encrypt instance. func NewEncryptingSerializer(secret string) *EncryptingSerializer { key := sha256.Sum256([]byte(secret)) return &EncryptingSerializer{key} } // Encode encode and encrypt session. func (e *EncryptingSerializer) Encode(src session.Dict) ([]byte, error) { if len(src.D) == 0 {<|fim▁hole|> dst, err := src.MarshalMsg(nil) if err != nil { return nil, fmt.Errorf("unable to marshal session: %v", err) } encryptedDst, err := utils.Encrypt(dst, &e.key) if err != nil { return nil, fmt.Errorf("unable to encrypt session: %v", err) } return encryptedDst, nil } // Decode decrypt and decode session. func (e *EncryptingSerializer) Decode(dst *session.Dict, src []byte) error { if len(src) == 0 { return nil } dst.Reset() decryptedSrc, err := utils.Decrypt(src, &e.key) if err != nil { return fmt.Errorf("unable to decrypt session: %s", err) } _, err = dst.UnmarshalMsg(decryptedSrc) return err }<|fim▁end|>
return nil, nil }
<|file_name|>DigestAuthentication.cpp<|end_file_name|><|fim▁begin|>/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved. // A class used for digest authentication. // Implementation #include "DigestAuthentication.hh" #include "ourMD5.hh" #include <strDup.hh> #include <GroupsockHelper.hh> // for gettimeofday() #include <stdio.h> #include <stdlib.h> #include <string.h> Authenticator::Authenticator() { assign(NULL, NULL, NULL, NULL, False); } Authenticator::Authenticator(char const* username, char const* password, Boolean passwordIsMD5) { assign(NULL, NULL, username, password, passwordIsMD5); } Authenticator::Authenticator(const Authenticator& orig) { assign(orig.realm(), orig.nonce(), orig.username(), orig.password(), orig.fPasswordIsMD5); } Authenticator& Authenticator::operator=(const Authenticator& rightSide) { if (&rightSide != this) { reset(); assign(rightSide.realm(), rightSide.nonce(), rightSide.username(), rightSide.password(), rightSide.fPasswordIsMD5); } return *this; } Boolean Authenticator::operator<(const Authenticator* rightSide) { if (rightSide != NULL && rightSide != this && (rightSide->realm() != NULL || rightSide->nonce() != NULL || strcmp(rightSide->username(), username()) != 0 || strcmp(rightSide->password(), password()) != 0)) { return True; } return False; } Authenticator::~Authenticator() { reset(); } void Authenticator::reset() { resetRealmAndNonce(); resetUsernameAndPassword(); } void Authenticator::setRealmAndNonce(char const* realm, char const* nonce) { resetRealmAndNonce(); assignRealmAndNonce(realm, nonce); } void Authenticator::setRealmAndRandomNonce(char const* realm) { resetRealmAndNonce(); // Construct data to seed the random nonce: struct { struct timeval timestamp; unsigned counter; } seedData; gettimeofday(&seedData.timestamp, NULL); static unsigned counter = 0; seedData.counter = ++counter; // Use MD5 to compute a 'random' nonce from this seed data: char nonceBuf[33]; our_MD5Data((unsigned char*)(&seedData), sizeof seedData, nonceBuf); assignRealmAndNonce(realm, nonceBuf); } void Authenticator::setUsernameAndPassword(char const* username, char const* password, Boolean passwordIsMD5) { resetUsernameAndPassword(); assignUsernameAndPassword(username, password, passwordIsMD5); } char const* Authenticator::computeDigestResponse(char const* cmd, char const* url) const { // The "response" field is computed as: // md5(md5(<username>:<realm>:<password>):<nonce>:md5(<cmd>:<url>)) // or, if "fPasswordIsMD5" is True: // md5(<password>:<nonce>:md5(<cmd>:<url>)) char ha1Buf[33]; if (fPasswordIsMD5) { strncpy(ha1Buf, password(), 32); ha1Buf[32] = '\0'; // just in case } else { unsigned const ha1DataLen = strlen(username()) + 1 + strlen(realm()) + 1 + strlen(password()); unsigned char* ha1Data = new unsigned char[ha1DataLen+1]; sprintf((char*)ha1Data, "%s:%s:%s", username(), realm(), password()); our_MD5Data(ha1Data, ha1DataLen, ha1Buf); delete[] ha1Data; } unsigned const ha2DataLen = strlen(cmd) + 1 + strlen(url); unsigned char* ha2Data = new unsigned char[ha2DataLen+1]; sprintf((char*)ha2Data, "%s:%s", cmd, url); char ha2Buf[33]; our_MD5Data(ha2Data, ha2DataLen, ha2Buf); delete[] ha2Data; unsigned const digestDataLen = 32 + 1 + strlen(nonce()) + 1 + 32; unsigned char* digestData = new unsigned char[digestDataLen+1]; sprintf((char*)digestData, "%s:%s:%s", ha1Buf, nonce(), ha2Buf); char const* result = our_MD5Data(digestData, digestDataLen, NULL); delete[] digestData; return result; } void Authenticator::reclaimDigestResponse(char const* responseStr) const { delete[](char*)responseStr; } void Authenticator::resetRealmAndNonce() { delete[] fRealm; fRealm = NULL; delete[] fNonce; fNonce = NULL; } void Authenticator::resetUsernameAndPassword() { delete[] fUsername; fUsername = NULL; delete[] fPassword; fPassword = NULL; fPasswordIsMD5 = False; } void Authenticator::assignRealmAndNonce(char const* realm, char const* nonce) {<|fim▁hole|> fRealm = strDup(realm); fNonce = strDup(nonce); } void Authenticator::assignUsernameAndPassword(char const* username, char const* password, Boolean passwordIsMD5) { if (username == NULL) username = ""; if (password == NULL) password = ""; fUsername = strDup(username); fPassword = strDup(password); fPasswordIsMD5 = passwordIsMD5; } void Authenticator::assign(char const* realm, char const* nonce, char const* username, char const* password, Boolean passwordIsMD5) { assignRealmAndNonce(realm, nonce); assignUsernameAndPassword(username, password, passwordIsMD5); }<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import http from "http"; import express from "express"; import cors from "cors"; import morgan from "morgan"; import bodyParser from "body-parser"; import initializeDb from "./db"; import middleware from "./middleware"; import api from "./api"; import config from "config"; //we load the db location from the JSON files let app = express(); app.server = http.createServer(app); //don't show the log when it is test if (process.env.NODE_ENV !== "test") { // logger app.use(morgan("dev")); } // 3rd party middleware app.use( cors({ exposedHeaders: config.corsHeaders }) ); app.use( bodyParser.json({ limit: config.bodyLimit }) ); const dbOptions = { useMongoClient: true }; // connect to db initializeDb(config.dbURI, dbOptions, () => {<|fim▁hole|> app.use("/api", api({ config })); app.server.listen(process.env.PORT || config.port, () => { console.log(`Started on port ${app.server.address().port}`); }); }); export default app;<|fim▁end|>
// internal middleware app.use(middleware({ config })); // api router
<|file_name|>test_cargo_compile_git_deps.rs<|end_file_name|><|fim▁begin|>use std::fs::{self, File}; use std::io::prelude::*; use std::path::Path; use std::thread; use git2; use support::{git, project, execs, main_file, path2url}; use support::{COMPILING, UPDATING, RUNNING}; use support::paths::{self, CargoPathExt}; use hamcrest::{assert_that,existing_file}; use cargo::util::process; fn setup() { } test!(cargo_compile_simple_git_dep { let project = project("foo"); let git_project = git::new("dep1", |project| { project .file("Cargo.toml", r#" [project] name = "dep1" version = "0.5.0" authors = ["[email protected]"] [lib] name = "dep1" "#) .file("src/dep1.rs", r#" pub fn hello() -> &'static str { "hello world" } "#) }).unwrap(); let project = project .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] git = '{}' [[bin]] name = "foo" "#, git_project.url())) .file("src/foo.rs", &main_file(r#""{}", dep1::hello()"#, &["dep1"])); let root = project.root(); let git_root = git_project.root(); assert_that(project.cargo_process("build"), execs() .with_stdout(&format!("{} git repository `{}`\n\ {} dep1 v0.5.0 ({}#[..])\n\ {} foo v0.5.0 ({})\n", UPDATING, path2url(git_root.clone()), COMPILING, path2url(git_root), COMPILING, path2url(root))) .with_stderr("")); assert_that(&project.bin("foo"), existing_file()); assert_that( process(&project.bin("foo")), execs().with_stdout("hello world\n")); }); test!(cargo_compile_git_dep_branch { let project = project("foo"); let git_project = git::new("dep1", |project| { project .file("Cargo.toml", r#" [project] name = "dep1" version = "0.5.0" authors = ["[email protected]"] [lib] name = "dep1" "#) .file("src/dep1.rs", r#" pub fn hello() -> &'static str { "hello world" } "#) }).unwrap(); // Make a new branch based on the current HEAD commit let repo = git2::Repository::open(&git_project.root()).unwrap(); let head = repo.head().unwrap().target().unwrap(); let head = repo.find_commit(head).unwrap(); repo.branch("branchy", &head, true).unwrap(); let project = project .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] git = '{}' branch = "branchy" [[bin]] name = "foo" "#, git_project.url())) .file("src/foo.rs", &main_file(r#""{}", dep1::hello()"#, &["dep1"])); let root = project.root(); let git_root = git_project.root(); assert_that(project.cargo_process("build"), execs() .with_stdout(&format!("{} git repository `{}`\n\ {} dep1 v0.5.0 ({}?branch=branchy#[..])\n\ {} foo v0.5.0 ({})\n", UPDATING, path2url(git_root.clone()), COMPILING, path2url(git_root), COMPILING, path2url(root))) .with_stderr("")); assert_that(&project.bin("foo"), existing_file()); assert_that( process(&project.bin("foo")), execs().with_stdout("hello world\n")); }); test!(cargo_compile_git_dep_tag { let project = project("foo"); let git_project = git::new("dep1", |project| { project .file("Cargo.toml", r#" [project] name = "dep1" version = "0.5.0" authors = ["[email protected]"] [lib] name = "dep1" "#) .file("src/dep1.rs", r#" pub fn hello() -> &'static str { "hello world" } "#) }).unwrap(); // Make a tag corresponding to the current HEAD let repo = git2::Repository::open(&git_project.root()).unwrap(); let head = repo.head().unwrap().target().unwrap(); repo.tag("v0.1.0", &repo.find_object(head, None).unwrap(), &repo.signature().unwrap(), "make a new tag", false).unwrap(); let project = project .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] git = '{}' tag = "v0.1.0" [[bin]] name = "foo" "#, git_project.url())) .file("src/foo.rs", &main_file(r#""{}", dep1::hello()"#, &["dep1"])); let root = project.root(); let git_root = git_project.root(); assert_that(project.cargo_process("build"), execs() .with_stdout(&format!("{} git repository `{}`\n\ {} dep1 v0.5.0 ({}?tag=v0.1.0#[..])\n\ {} foo v0.5.0 ({})\n", UPDATING, path2url(git_root.clone()), COMPILING, path2url(git_root), COMPILING, path2url(root)))); assert_that(&project.bin("foo"), existing_file()); assert_that(process(&project.bin("foo")), execs().with_stdout("hello world\n")); assert_that(project.cargo("build"), execs().with_status(0)); }); test!(cargo_compile_with_nested_paths { let git_project = git::new("dep1", |project| { project .file("Cargo.toml", r#" [project] name = "dep1" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep2] version = "0.5.0" path = "vendor/dep2" [lib] name = "dep1" "#) .file("src/dep1.rs", r#" extern crate dep2; pub fn hello() -> &'static str { dep2::hello() } "#) .file("vendor/dep2/Cargo.toml", r#" [project] name = "dep2" version = "0.5.0" authors = ["[email protected]"] [lib] name = "dep2" "#) .file("vendor/dep2/src/dep2.rs", r#" pub fn hello() -> &'static str { "hello world" } "#) }).unwrap(); let p = project("parent") .file("Cargo.toml", &format!(r#" [project] name = "parent" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] version = "0.5.0" git = '{}' [[bin]] name = "parent" "#, git_project.url())) .file("src/parent.rs", &main_file(r#""{}", dep1::hello()"#, &["dep1"])); p.cargo_process("build") .exec_with_output() .unwrap(); assert_that(&p.bin("parent"), existing_file()); assert_that(process(&p.bin("parent")), execs().with_stdout("hello world\n")); }); test!(cargo_compile_with_meta_package { let git_project = git::new("meta-dep", |project| { project .file("dep1/Cargo.toml", r#" [project] name = "dep1" version = "0.5.0" authors = ["[email protected]"] [lib] name = "dep1" "#) .file("dep1/src/dep1.rs", r#" pub fn hello() -> &'static str { "this is dep1" } "#) .file("dep2/Cargo.toml", r#" [project] name = "dep2" version = "0.5.0" authors = ["[email protected]"] [lib] name = "dep2" "#) .file("dep2/src/dep2.rs", r#" pub fn hello() -> &'static str { "this is dep2" } "#) }).unwrap(); let p = project("parent") .file("Cargo.toml", &format!(r#" [project] name = "parent" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] version = "0.5.0" git = '{}' [dependencies.dep2] version = "0.5.0" git = '{}' [[bin]] name = "parent" "#, git_project.url(), git_project.url())) .file("src/parent.rs", &main_file(r#""{} {}", dep1::hello(), dep2::hello()"#, &["dep1", "dep2"])); p.cargo_process("build") .exec_with_output() .unwrap(); assert_that(&p.bin("parent"), existing_file()); assert_that(process(&p.bin("parent")), execs().with_stdout("this is dep1 this is dep2\n")); }); test!(cargo_compile_with_short_ssh_git { let url = "[email protected]:a/dep"; let project = project("project") .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep] git = "{}" [[bin]] name = "foo" "#, url)) .file("src/foo.rs", &main_file(r#""{}", dep1::hello()"#, &["dep1"])); assert_that(project.cargo_process("build"), execs() .with_stdout("") .with_stderr(&format!("\ failed to parse manifest at `[..]` Caused by: invalid url `{}`: relative URL without a base ", url))); }); test!(two_revs_same_deps { let bar = git::new("meta-dep", |project| { project.file("Cargo.toml", r#" [package] name = "bar" version = "0.0.0" authors = [] "#) .file("src/lib.rs", "pub fn bar() -> i32 { 1 }") }).unwrap(); let repo = git2::Repository::open(&bar.root()).unwrap(); let rev1 = repo.revparse_single("HEAD").unwrap().id(); // Commit the changes and make sure we trigger a recompile File::create(&bar.root().join("src/lib.rs")).unwrap().write_all(br#" pub fn bar() -> i32 { 2 } "#).unwrap(); git::add(&repo); let rev2 = git::commit(&repo); let foo = project("foo") .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.0.0" authors = [] [dependencies.bar] git = '{}' rev = "{}" [dependencies.baz] path = "../baz" "#, bar.url(), rev1)) .file("src/main.rs", r#" extern crate bar; extern crate baz; fn main() { assert_eq!(bar::bar(), 1); assert_eq!(baz::baz(), 2); } "#); let baz = project("baz") .file("Cargo.toml", &format!(r#" [package] name = "baz" version = "0.0.0" authors = [] [dependencies.bar] git = '{}' rev = "{}" "#, bar.url(), rev2)) .file("src/lib.rs", r#" extern crate bar; pub fn baz() -> i32 { bar::bar() } "#); baz.build(); assert_that(foo.cargo_process("build").arg("-v"), execs().with_status(0)); assert_that(&foo.bin("foo"), existing_file()); assert_that(foo.process(&foo.bin("foo")), execs().with_status(0)); }); test!(recompilation { let git_project = git::new("bar", |project| { project .file("Cargo.toml", r#" [project] name = "bar" version = "0.5.0" authors = ["[email protected]"] [lib] name = "bar" "#) .file("src/bar.rs", r#" pub fn bar() {} "#) }).unwrap(); let p = project("foo") .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.bar] version = "0.5.0" git = '{}' [[bin]] name = "foo" "#, git_project.url())) .file("src/foo.rs", &main_file(r#""{:?}", bar::bar()"#, &["bar"])); // First time around we should compile both foo and bar assert_that(p.cargo_process("build"), execs().with_stdout(&format!("{} git repository `{}`\n\ {} bar v0.5.0 ({}#[..])\n\ {} foo v0.5.0 ({})\n", UPDATING, git_project.url(), COMPILING, git_project.url(), COMPILING, p.url()))); // Don't recompile the second time assert_that(p.cargo("build"), execs().with_stdout("")); // Modify a file manually, shouldn't trigger a recompile File::create(&git_project.root().join("src/bar.rs")).unwrap().write_all(br#" pub fn bar() { println!("hello!"); } "#).unwrap(); assert_that(p.cargo("build"), execs().with_stdout("")); assert_that(p.cargo("update"), execs().with_stdout(&format!("{} git repository `{}`", UPDATING, git_project.url()))); assert_that(p.cargo("build"), execs().with_stdout("")); // Commit the changes and make sure we don't trigger a recompile because the // lockfile says not to change let repo = git2::Repository::open(&git_project.root()).unwrap(); git::add(&repo); git::commit(&repo); println!("compile after commit"); assert_that(p.cargo("build"), execs().with_stdout("")); p.root().move_into_the_past().unwrap(); // Update the dependency and carry on! assert_that(p.cargo("update"), execs().with_stdout(&format!("{} git repository `{}`\n\ {} bar v0.5.0 ([..]) -> #[..]\n\ ", UPDATING, git_project.url(), UPDATING))); println!("going for the last compile"); assert_that(p.cargo("build"), execs().with_stdout(&format!("{} bar v0.5.0 ({}#[..])\n\ {} foo v0.5.0 ({})\n", COMPILING, git_project.url(), COMPILING, p.url()))); // Make sure clean only cleans one dep assert_that(p.cargo("clean") .arg("-p").arg("foo"), execs().with_stdout("")); assert_that(p.cargo("build"), execs().with_stdout(&format!("{} foo v0.5.0 ({})\n", COMPILING, p.url()))); }); test!(update_with_shared_deps { let git_project = git::new("bar", |project| { project .file("Cargo.toml", r#" [project] name = "bar" version = "0.5.0" authors = ["[email protected]"] [lib] name = "bar" "#) .file("src/bar.rs", r#" pub fn bar() {} "#) }).unwrap(); let p = project("foo") .file("Cargo.toml", r#" [package] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] path = "dep1" [dependencies.dep2] path = "dep2" "#) .file("src/main.rs", r#" extern crate dep1; extern crate dep2; fn main() {} "#) .file("dep1/Cargo.toml", &format!(r#" [package] name = "dep1" version = "0.5.0" authors = ["[email protected]"] [dependencies.bar] version = "0.5.0" git = '{}' "#, git_project.url())) .file("dep1/src/lib.rs", "") .file("dep2/Cargo.toml", &format!(r#" [package] name = "dep2" version = "0.5.0" authors = ["[email protected]"] [dependencies.bar] version = "0.5.0" git = '{}' "#, git_project.url())) .file("dep2/src/lib.rs", ""); // First time around we should compile both foo and bar assert_that(p.cargo_process("build"), execs().with_stdout(&format!("\ {updating} git repository `{git}` {compiling} bar v0.5.0 ({git}#[..]) {compiling} [..] v0.5.0 ({dir}) {compiling} [..] v0.5.0 ({dir}) {compiling} foo v0.5.0 ({dir})\n", updating = UPDATING, git = git_project.url(), compiling = COMPILING, dir = p.url()))); // Modify a file manually, and commit it File::create(&git_project.root().join("src/bar.rs")).unwrap().write_all(br#" pub fn bar() { println!("hello!"); } "#).unwrap(); let repo = git2::Repository::open(&git_project.root()).unwrap(); let old_head = repo.head().unwrap().target().unwrap(); git::add(&repo); git::commit(&repo); thread::sleep_ms(1000); // By default, not transitive updates println!("dep1 update"); assert_that(p.cargo("update") .arg("-p").arg("dep1"), execs().with_stdout("")); // Don't do anything bad on a weird --precise argument println!("bar bad precise update"); assert_that(p.cargo("update") .arg("-p").arg("bar") .arg("--precise").arg("0.1.2"), execs().with_status(101).with_stderr("\ Unable to update [..] To learn more, run the command again with --verbose. ")); // Specifying a precise rev to the old rev shouldn't actually update // anything because we already have the rev in the db. println!("bar precise update"); assert_that(p.cargo("update") .arg("-p").arg("bar") .arg("--precise").arg(&old_head.to_string()), execs().with_stdout("")); // Updating aggressively should, however, update the repo. println!("dep1 aggressive update"); assert_that(p.cargo("update") .arg("-p").arg("dep1") .arg("--aggressive"), execs().with_stdout(&format!("{} git repository `{}`\n\ {} bar v0.5.0 ([..]) -> #[..]\n\ ", UPDATING, git_project.url(), UPDATING))); // Make sure we still only compile one version of the git repo println!("build"); assert_that(p.cargo("build"), execs().with_stdout(&format!("\ {compiling} bar v0.5.0 ({git}#[..]) {compiling} [..] v0.5.0 ({dir}) {compiling} [..] v0.5.0 ({dir}) {compiling} foo v0.5.0 ({dir})\n", git = git_project.url(), compiling = COMPILING, dir = p.url()))); // We should be able to update transitive deps assert_that(p.cargo("update").arg("-p").arg("bar"), execs().with_stdout(&format!("{} git repository `{}`", UPDATING, git_project.url()))); }); test!(dep_with_submodule { let project = project("foo"); let git_project = git::new("dep1", |project| { project .file("Cargo.toml", r#" [package] name = "dep1" version = "0.5.0" authors = ["[email protected]"] "#) }).unwrap(); let git_project2 = git::new("dep2", |project| { project.file("lib.rs", "pub fn dep() {}") }).unwrap(); let repo = git2::Repository::open(&git_project.root()).unwrap(); let url = path2url(git_project2.root()).to_string(); git::add_submodule(&repo, &url, Path::new("src")); git::commit(&repo); let project = project .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] git = '{}' "#, git_project.url())) .file("src/lib.rs", " extern crate dep1; pub fn foo() { dep1::dep() } "); assert_that(project.cargo_process("build"), execs().with_stderr("").with_status(0)); }); test!(two_deps_only_update_one { let project = project("foo"); let git1 = git::new("dep1", |project| { project .file("Cargo.toml", r#" [package] name = "dep1" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "") }).unwrap(); let git2 = git::new("dep2", |project| { project .file("Cargo.toml", r#" [package] name = "dep2" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "") }).unwrap(); let project = project .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] git = '{}' [dependencies.dep2] git = '{}' "#, git1.url(), git2.url())) .file("src/main.rs", "fn main() {}"); assert_that(project.cargo_process("build"), execs() .with_stdout(&format!("{} git repository `[..]`\n\ {} git repository `[..]`\n\ {} [..] v0.5.0 ([..])\n\ {} [..] v0.5.0 ([..])\n\ {} foo v0.5.0 ({})\n", UPDATING, UPDATING, COMPILING, COMPILING, COMPILING, project.url())) .with_stderr("")); File::create(&git1.root().join("src/lib.rs")).unwrap().write_all(br#" pub fn foo() {} "#).unwrap(); let repo = git2::Repository::open(&git1.root()).unwrap(); git::add(&repo); git::commit(&repo); assert_that(project.cargo("update") .arg("-p").arg("dep1"), execs() .with_stdout(&format!("{} git repository `{}`\n\ {} dep1 v0.5.0 ([..]) -> #[..]\n\ ", UPDATING, git1.url(), UPDATING)) .with_stderr("")); }); test!(stale_cached_version { let bar = git::new("meta-dep", |project| { project.file("Cargo.toml", r#" [package] name = "bar" version = "0.0.0" authors = [] "#) .file("src/lib.rs", "pub fn bar() -> i32 { 1 }") }).unwrap(); // Update the git database in the cache with the current state of the git // repo let foo = project("foo") .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.0.0" authors = [] [dependencies.bar] git = '{}' "#, bar.url())) .file("src/main.rs", r#" extern crate bar; fn main() { assert_eq!(bar::bar(), 1) } "#); assert_that(foo.cargo_process("build"), execs().with_status(0)); assert_that(foo.process(&foo.bin("foo")), execs().with_status(0)); // Update the repo, and simulate someone else updating the lockfile and then // us pulling it down. File::create(&bar.root().join("src/lib.rs")).unwrap().write_all(br#" pub fn bar() -> i32 { 1 + 0 } "#).unwrap(); let repo = git2::Repository::open(&bar.root()).unwrap(); git::add(&repo); git::commit(&repo); thread::sleep_ms(1000); let rev = repo.revparse_single("HEAD").unwrap().id(); File::create(&foo.root().join("Cargo.lock")).unwrap().write_all(format!(r#" [root] name = "foo" version = "0.0.0" dependencies = [ 'bar 0.0.0 (git+{url}#{hash})' ] [[package]] name = "bar" version = "0.0.0" source = 'git+{url}#{hash}' "#, url = bar.url(), hash = rev).as_bytes()).unwrap(); // Now build! assert_that(foo.cargo("build"), execs().with_status(0) .with_stdout(&format!("\ {updating} git repository `{bar}` {compiling} bar v0.0.0 ({bar}#[..]) {compiling} foo v0.0.0 ({foo}) ", updating = UPDATING, compiling = COMPILING, bar = bar.url(), foo = foo.url()))); assert_that(foo.process(&foo.bin("foo")), execs().with_status(0)); });<|fim▁hole|> let git_project = git::new("dep1", |project| { project .file("Cargo.toml", r#" [package] name = "dep1" version = "0.5.0" authors = ["[email protected]"] "#) }).unwrap(); let git_project2 = git::new("dep2", |project| { project .file("lib.rs", "pub fn dep() -> &'static str { \"project2\" }") }).unwrap(); let git_project3 = git::new("dep3", |project| { project .file("lib.rs", "pub fn dep() -> &'static str { \"project3\" }") }).unwrap(); let repo = git2::Repository::open(&git_project.root()).unwrap(); let mut sub = git::add_submodule(&repo, &git_project2.url().to_string(), &Path::new("src")); git::commit(&repo); let project = project .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.dep1] git = '{}' "#, git_project.url())) .file("src/main.rs", " extern crate dep1; pub fn main() { println!(\"{}\", dep1::dep()) } "); println!("first run"); assert_that(project.cargo_process("run"), execs() .with_stdout(&format!("{} git repository `[..]`\n\ {} dep1 v0.5.0 ([..])\n\ {} foo v0.5.0 ([..])\n\ {} `target[..]foo[..]`\n\ project2\ ", UPDATING, COMPILING, COMPILING, RUNNING)) .with_stderr("") .with_status(0)); File::create(&git_project.root().join(".gitmodules")).unwrap() .write_all(format!("[submodule \"src\"]\n\tpath = src\n\turl={}", git_project3.url()).as_bytes()).unwrap(); // Sync the submodule and reset it to the new remote. sub.sync().unwrap(); { let subrepo = sub.open().unwrap(); subrepo.remote_add_fetch("origin", "refs/heads/*:refs/heads/*").unwrap(); subrepo.remote_set_url("origin", &git_project3.url().to_string()).unwrap(); let mut origin = subrepo.find_remote("origin").unwrap(); origin.fetch(&[], None, None).unwrap(); let id = subrepo.refname_to_id("refs/remotes/origin/master").unwrap(); let obj = subrepo.find_object(id, None).unwrap(); subrepo.reset(&obj, git2::ResetType::Hard, None).unwrap(); } sub.add_to_index(true).unwrap(); git::add(&repo); git::commit(&repo); thread::sleep_ms(1000); // Update the dependency and carry on! println!("update"); assert_that(project.cargo("update").arg("-v"), execs() .with_stderr("") .with_stdout(&format!("{} git repository `{}`\n\ {} dep1 v0.5.0 ([..]) -> #[..]\n\ ", UPDATING, git_project.url(), UPDATING))); println!("last run"); assert_that(project.cargo("run"), execs() .with_stdout(&format!("{compiling} dep1 v0.5.0 ([..])\n\ {compiling} foo v0.5.0 ([..])\n\ {running} `target[..]foo[..]`\n\ project3\ ", compiling = COMPILING, running = RUNNING)) .with_stderr("") .with_status(0)); }); test!(dev_deps_with_testing { let p2 = git::new("bar", |project| { project.file("Cargo.toml", r#" [package] name = "bar" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", r#" pub fn gimme() -> &'static str { "zoidberg" } "#) }).unwrap(); let p = project("foo") .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dev-dependencies.bar] version = "0.5.0" git = '{}' "#, p2.url())) .file("src/main.rs", r#" fn main() {} #[cfg(test)] mod tests { extern crate bar; #[test] fn foo() { bar::gimme(); } } "#); // Generate a lockfile which did not use `bar` to compile, but had to update // `bar` to generate the lockfile assert_that(p.cargo_process("build"), execs().with_stdout(&format!("\ {updating} git repository `{bar}` {compiling} foo v0.5.0 ({url}) ", updating = UPDATING, compiling = COMPILING, url = p.url(), bar = p2.url()))); // Make sure we use the previous resolution of `bar` instead of updating it // a second time. assert_that(p.cargo("test"), execs().with_stdout(&format!("\ {compiling} [..] v0.5.0 ([..]) {compiling} [..] v0.5.0 ([..] {running} target[..]foo-[..] running 1 test test tests::foo ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured ", compiling = COMPILING, running = RUNNING))); }); test!(git_build_cmd_freshness { let foo = git::new("foo", |project| { project.file("Cargo.toml", r#" [package] name = "foo" version = "0.0.0" authors = [] build = "build.rs" "#) .file("build.rs", "fn main() {}") .file("src/lib.rs", "pub fn bar() -> i32 { 1 }") .file(".gitignore", " src/bar.rs ") }).unwrap(); foo.root().move_into_the_past().unwrap(); thread::sleep_ms(1000); assert_that(foo.cargo("build"), execs().with_status(0) .with_stdout(&format!("\ {compiling} foo v0.0.0 ({url}) ", compiling = COMPILING, url = foo.url()))); // Smoke test to make sure it doesn't compile again println!("first pass"); assert_that(foo.cargo("build"), execs().with_status(0) .with_stdout("")); // Modify an ignored file and make sure we don't rebuild println!("second pass"); File::create(&foo.root().join("src/bar.rs")).unwrap(); assert_that(foo.cargo("build"), execs().with_status(0) .with_stdout("")); }); test!(git_name_not_always_needed { let p2 = git::new("bar", |project| { project.file("Cargo.toml", r#" [package] name = "bar" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", r#" pub fn gimme() -> &'static str { "zoidberg" } "#) }).unwrap(); let repo = git2::Repository::open(&p2.root()).unwrap(); let mut cfg = repo.config().unwrap(); let _ = cfg.remove("user.name"); let _ = cfg.remove("user.email"); let p = project("foo") .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = [] [dev-dependencies.bar] git = '{}' "#, p2.url())) .file("src/main.rs", "fn main() {}"); // Generate a lockfile which did not use `bar` to compile, but had to update // `bar` to generate the lockfile assert_that(p.cargo_process("build"), execs().with_stdout(&format!("\ {updating} git repository `{bar}` {compiling} foo v0.5.0 ({url}) ", updating = UPDATING, compiling = COMPILING, url = p.url(), bar = p2.url()))); }); test!(git_repo_changing_no_rebuild { let bar = git::new("bar", |project| { project.file("Cargo.toml", r#" [package] name = "bar" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "pub fn bar() -> i32 { 1 }") }).unwrap(); // Lock p1 to the first rev in the git repo let p1 = project("p1") .file("Cargo.toml", &format!(r#" [project] name = "p1" version = "0.5.0" authors = [] build = 'build.rs' [dependencies.bar] git = '{}' "#, bar.url())) .file("src/main.rs", "fn main() {}") .file("build.rs", "fn main() {}"); p1.build(); p1.root().move_into_the_past().unwrap(); assert_that(p1.cargo("build"), execs().with_stdout(&format!("\ {updating} git repository `{bar}` {compiling} [..] {compiling} [..] ", updating = UPDATING, compiling = COMPILING, bar = bar.url()))); // Make a commit to lock p2 to a different rev File::create(&bar.root().join("src/lib.rs")).unwrap().write_all(br#" pub fn bar() -> i32 { 2 } "#).unwrap(); let repo = git2::Repository::open(&bar.root()).unwrap(); git::add(&repo); git::commit(&repo); // Lock p2 to the second rev let p2 = project("p2") .file("Cargo.toml", &format!(r#" [project] name = "p2" version = "0.5.0" authors = [] [dependencies.bar] git = '{}' "#, bar.url())) .file("src/main.rs", "fn main() {}"); assert_that(p2.cargo_process("build"), execs().with_stdout(&format!("\ {updating} git repository `{bar}` {compiling} [..] {compiling} [..] ", updating = UPDATING, compiling = COMPILING, bar = bar.url()))); // And now for the real test! Make sure that p1 doesn't get rebuilt // even though the git repo has changed. assert_that(p1.cargo("build"), execs().with_stdout("")); }); test!(git_dep_build_cmd { let p = git::new("foo", |project| { project.file("Cargo.toml", r#" [project] name = "foo" version = "0.5.0" authors = ["[email protected]"] [dependencies.bar] version = "0.5.0" path = "bar" [[bin]] name = "foo" "#) .file("src/foo.rs", &main_file(r#""{}", bar::gimme()"#, &["bar"])) .file("bar/Cargo.toml", r#" [project] name = "bar" version = "0.5.0" authors = ["[email protected]"] build = "build.rs" [lib] name = "bar" "#) .file("bar/src/bar.rs.in", r#" pub fn gimme() -> i32 { 0 } "#) .file("bar/build.rs", r#" use std::fs; fn main() { fs::copy("src/bar.rs.in", "src/bar.rs").unwrap(); } "#) }).unwrap(); p.root().join("bar").move_into_the_past().unwrap(); assert_that(p.cargo("build"), execs().with_status(0)); assert_that(process(&p.bin("foo")), execs().with_stdout("0\n")); // Touching bar.rs.in should cause the `build` command to run again. fs::File::create(&p.root().join("bar/src/bar.rs.in")).unwrap() .write_all(b"pub fn gimme() -> i32 { 1 }").unwrap(); assert_that(p.cargo("build"), execs().with_status(0)); assert_that(process(&p.bin("foo")), execs().with_stdout("1\n")); }); test!(fetch_downloads { let bar = git::new("bar", |project| { project.file("Cargo.toml", r#" [package] name = "bar" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "pub fn bar() -> i32 { 1 }") }).unwrap(); let p = project("p1") .file("Cargo.toml", &format!(r#" [project] name = "p1" version = "0.5.0" authors = [] [dependencies.bar] git = '{}' "#, bar.url())) .file("src/main.rs", "fn main() {}"); assert_that(p.cargo_process("fetch"), execs().with_status(0).with_stdout(&format!("\ {updating} git repository `{url}` ", updating = UPDATING, url = bar.url()))); assert_that(p.cargo("fetch"), execs().with_status(0).with_stdout("")); }); test!(warnings_in_git_dep { let bar = git::new("bar", |project| { project.file("Cargo.toml", r#" [package] name = "bar" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "fn unused() {}") }).unwrap(); let p = project("foo") .file("Cargo.toml", &format!(r#" [project] name = "foo" version = "0.5.0" authors = [] [dependencies.bar] git = '{}' "#, bar.url())) .file("src/main.rs", "fn main() {}"); assert_that(p.cargo_process("build"), execs() .with_stdout(&format!("{} git repository `{}`\n\ {} bar v0.5.0 ({}#[..])\n\ {} foo v0.5.0 ({})\n", UPDATING, bar.url(), COMPILING, bar.url(), COMPILING, p.url())) .with_stderr("")); }); test!(update_ambiguous { let foo1 = git::new("foo1", |project| { project.file("Cargo.toml", r#" [package] name = "foo" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "") }).unwrap(); let foo2 = git::new("foo2", |project| { project.file("Cargo.toml", r#" [package] name = "foo" version = "0.6.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "") }).unwrap(); let bar = git::new("bar", |project| { project.file("Cargo.toml", &format!(r#" [package] name = "bar" version = "0.5.0" authors = ["[email protected]"] [dependencies.foo] git = '{}' "#, foo2.url())) .file("src/lib.rs", "") }).unwrap(); let p = project("project") .file("Cargo.toml", &format!(r#" [project] name = "project" version = "0.5.0" authors = [] [dependencies.foo] git = '{}' [dependencies.bar] git = '{}' "#, foo1.url(), bar.url())) .file("src/main.rs", "fn main() {}"); assert_that(p.cargo_process("generate-lockfile"), execs().with_status(0)); assert_that(p.cargo("update") .arg("-p").arg("foo"), execs().with_status(101) .with_stderr("\ There are multiple `foo` packages in your project, and the specification `foo` \ is ambiguous. Please re-run this command with `-p <spec>` where `<spec>` is one of the \ following: foo:0.[..].0 foo:0.[..].0 ")); }); test!(update_one_dep_in_repo_with_many_deps { let foo = git::new("foo", |project| { project.file("Cargo.toml", r#" [package] name = "foo" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "") .file("a/Cargo.toml", r#" [package] name = "a" version = "0.5.0" authors = ["[email protected]"] "#) .file("a/src/lib.rs", "") }).unwrap(); let p = project("project") .file("Cargo.toml", &format!(r#" [project] name = "project" version = "0.5.0" authors = [] [dependencies.foo] git = '{}' [dependencies.a] git = '{}' "#, foo.url(), foo.url())) .file("src/main.rs", "fn main() {}"); assert_that(p.cargo_process("generate-lockfile"), execs().with_status(0)); assert_that(p.cargo("update") .arg("-p").arg("foo"), execs().with_status(0) .with_stdout(&format!("\ Updating git repository `{}` ", foo.url()))); }); test!(switch_deps_does_not_update_transitive { let transitive = git::new("transitive", |project| { project.file("Cargo.toml", r#" [package] name = "transitive" version = "0.5.0" authors = ["[email protected]"] "#) .file("src/lib.rs", "") }).unwrap(); let dep1 = git::new("dep1", |project| { project.file("Cargo.toml", &format!(r#" [package] name = "dep" version = "0.5.0" authors = ["[email protected]"] [dependencies.transitive] git = '{}' "#, transitive.url())) .file("src/lib.rs", "") }).unwrap(); let dep2 = git::new("dep2", |project| { project.file("Cargo.toml", &format!(r#" [package] name = "dep" version = "0.5.0" authors = ["[email protected]"] [dependencies.transitive] git = '{}' "#, transitive.url())) .file("src/lib.rs", "") }).unwrap(); let p = project("project") .file("Cargo.toml", &format!(r#" [project] name = "project" version = "0.5.0" authors = [] [dependencies.dep] git = '{}' "#, dep1.url())) .file("src/main.rs", "fn main() {}"); p.build(); assert_that(p.cargo("build"), execs().with_status(0) .with_stdout(&format!("\ Updating git repository `{}` Updating git repository `{}` {compiling} transitive [..] {compiling} dep [..] {compiling} project [..] ", dep1.url(), transitive.url(), compiling = COMPILING))); // Update the dependency to point to the second repository, but this // shouldn't update the transitive dependency which is the same. File::create(&p.root().join("Cargo.toml")).unwrap().write_all(format!(r#" [project] name = "project" version = "0.5.0" authors = [] [dependencies.dep] git = '{}' "#, dep2.url()).as_bytes()).unwrap(); assert_that(p.cargo("build"), execs().with_status(0) .with_stdout(&format!("\ Updating git repository `{}` {compiling} dep [..] {compiling} project [..] ", dep2.url(), compiling = COMPILING))); }); test!(update_one_source_updates_all_packages_in_that_git_source { let dep = git::new("dep", |project| { project.file("Cargo.toml", r#" [package] name = "dep" version = "0.5.0" authors = [] [dependencies.a] path = "a" "#) .file("src/lib.rs", "") .file("a/Cargo.toml", r#" [package] name = "a" version = "0.5.0" authors = [] "#) .file("a/src/lib.rs", "") }).unwrap(); let p = project("project") .file("Cargo.toml", &format!(r#" [project] name = "project" version = "0.5.0" authors = [] [dependencies.dep] git = '{}' "#, dep.url())) .file("src/main.rs", "fn main() {}"); p.build(); assert_that(p.cargo("build"), execs().with_status(0)); let repo = git2::Repository::open(&dep.root()).unwrap(); let rev1 = repo.revparse_single("HEAD").unwrap().id(); // Just be sure to change a file File::create(&dep.root().join("src/lib.rs")).unwrap().write_all(br#" pub fn bar() -> i32 { 2 } "#).unwrap(); git::add(&repo); git::commit(&repo); assert_that(p.cargo("update").arg("-p").arg("dep"), execs().with_status(0)); let mut lockfile = String::new(); File::open(&p.root().join("Cargo.lock")).unwrap() .read_to_string(&mut lockfile).unwrap(); assert!(!lockfile.contains(&rev1.to_string()), "{} in {}", rev1, lockfile); }); test!(switch_sources { let a1 = git::new("a1", |project| { project.file("Cargo.toml", r#" [package] name = "a" version = "0.5.0" authors = [] "#) .file("src/lib.rs", "") }).unwrap(); let a2 = git::new("a2", |project| { project.file("Cargo.toml", r#" [package] name = "a" version = "0.5.1" authors = [] "#) .file("src/lib.rs", "") }).unwrap(); let p = project("project") .file("Cargo.toml", r#" [project] name = "project" version = "0.5.0" authors = [] [dependencies.b] path = "b" "#) .file("src/main.rs", "fn main() {}") .file("b/Cargo.toml", &format!(r#" [project] name = "b" version = "0.5.0" authors = [] [dependencies.a] git = '{}' "#, a1.url())) .file("b/src/lib.rs", "fn main() {}"); p.build(); assert_that(p.cargo("build"), execs().with_status(0) .with_stdout(&format!("\ {updating} git repository `file://[..]a1` {compiling} a v0.5.0 ([..]a1#[..] {compiling} b v0.5.0 ([..]) {compiling} project v0.5.0 ([..]) ", updating = UPDATING, compiling = COMPILING))); File::create(&p.root().join("b/Cargo.toml")).unwrap().write_all(format!(r#" [project] name = "b" version = "0.5.0" authors = [] [dependencies.a] git = '{}' "#, a2.url()).as_bytes()).unwrap(); assert_that(p.cargo("build"), execs().with_status(0) .with_stdout(&format!("\ {updating} git repository `file://[..]a2` {compiling} a v0.5.1 ([..]a2#[..] {compiling} b v0.5.0 ([..]) {compiling} project v0.5.0 ([..]) ", updating = UPDATING, compiling = COMPILING))); }); test!(dont_require_submodules_are_checked_out { let project = project("foo"); let git1 = git::new("dep1", |p| { p.file("Cargo.toml", r#" [project] name = "foo" version = "0.5.0" authors = [] build = "build.rs" "#) .file("build.rs", "fn main() {}") .file("src/lib.rs", "") .file("a/foo", "") }).unwrap(); let git2 = git::new("dep2", |p| p).unwrap(); let repo = git2::Repository::open(&git1.root()).unwrap(); let url = path2url(git2.root()).to_string(); git::add_submodule(&repo, &url, &Path::new("a/submodule")); git::commit(&repo); git2::Repository::init(&project.root()).unwrap(); let url = path2url(git1.root()).to_string(); let dst = paths::home().join("foo"); git2::Repository::clone(&url, &dst).unwrap(); assert_that(git1.cargo("build").arg("-v").cwd(&dst), execs().with_status(0)); }); test!(doctest_same_name { let a2 = git::new("a2", |p| { p.file("Cargo.toml", r#" [project] name = "a" version = "0.5.0" authors = [] "#) .file("src/lib.rs", "pub fn a2() {}") }).unwrap(); let a1 = git::new("a1", |p| { p.file("Cargo.toml", &format!(r#" [project] name = "a" version = "0.5.0" authors = [] [dependencies] a = {{ git = '{}' }} "#, a2.url())) .file("src/lib.rs", "extern crate a; pub fn a1() {}") }).unwrap(); let p = project("foo") .file("Cargo.toml", &format!(r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] a = {{ git = '{}' }} "#, a1.url())) .file("src/lib.rs", r#" #[macro_use] extern crate a; "#); assert_that(p.cargo_process("test").arg("-v"), execs().with_status(0)); }); test!(lints_are_suppressed { let a = git::new("a", |p| { p.file("Cargo.toml", r#" [project] name = "a" version = "0.5.0" authors = [] "#) .file("src/lib.rs", " use std::option; ") }).unwrap(); let p = project("foo") .file("Cargo.toml", &format!(r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] a = {{ git = '{}' }} "#, a.url())) .file("src/lib.rs", ""); assert_that(p.cargo_process("build"), execs().with_status(0).with_stdout(&format!("\ {updating} git repository `[..]` {compiling} a v0.5.0 ([..]) {compiling} foo v0.0.1 ([..]) ", compiling = COMPILING, updating = UPDATING))); }); test!(denied_lints_are_allowed { let enabled = super::RUSTC.with(|r| r.cap_lints); if !enabled { return } let a = git::new("a", |p| { p.file("Cargo.toml", r#" [project] name = "a" version = "0.5.0" authors = [] "#) .file("src/lib.rs", " #![deny(warnings)] use std::option; ") }).unwrap(); let p = project("foo") .file("Cargo.toml", &format!(r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] a = {{ git = '{}' }} "#, a.url())) .file("src/lib.rs", ""); assert_that(p.cargo_process("build"), execs().with_status(0).with_stdout(&format!("\ {updating} git repository `[..]` {compiling} a v0.5.0 ([..]) {compiling} foo v0.0.1 ([..]) ", compiling = COMPILING, updating = UPDATING))); });<|fim▁end|>
test!(dep_with_changed_submodule { let project = project("foo");
<|file_name|>share_instances.py<|end_file_name|><|fim▁begin|># Copyright 2015 Mirantis 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<|fim▁hole|> from manilaclient import api_versions from manilaclient import base from manilaclient.openstack.common.apiclient import base as common_base class ShareInstance(common_base.Resource): """A share is an extra block level storage to the OpenStack instances.""" def __repr__(self): return "<Share: %s>" % self.id def force_delete(self): """Delete the specified share ignoring its current state.""" self.manager.force_delete(self) def reset_state(self, state): """Update the share with the provided state.""" self.manager.reset_state(self, state) class ShareInstanceManager(base.ManagerWithFind): """Manage :class:`ShareInstances` resources.""" resource_class = ShareInstance @api_versions.wraps("2.3") def get(self, instance): """Get a share instance. :param instance: either share object or text with its ID. :rtype: :class:`ShareInstance` """ share_id = common_base.getid(instance) return self._get("/share_instances/%s" % share_id, "share_instance") @api_versions.wraps("2.3") def list(self): """List all share instances.""" return self._list('/share_instances', 'share_instances') def _action(self, action, instance, info=None, **kwargs): """Perform a share instnace 'action'. :param action: text with action name. :param instance: either share object or text with its ID. :param info: dict with data for specified 'action'. :param kwargs: dict with data to be provided for action hooks. """ body = {action: info} self.run_hooks('modify_body_for_action', body, **kwargs) url = '/share_instances/%s/action' % common_base.getid(instance) return self.api.client.post(url, body=body) def _do_force_delete(self, instance, action_name="force_delete"): """Delete a share instance forcibly - share status will be avoided. :param instance: either share instance object or text with its ID. """ return self._action(action_name, common_base.getid(instance)) @api_versions.wraps("2.3", "2.6") def force_delete(self, instance): return self._do_force_delete(instance, "os-force_delete") @api_versions.wraps("2.7") # noqa def force_delete(self, instance): return self._do_force_delete(instance, "force_delete") def _do_reset_state(self, instance, state, action_name): """Update the provided share instance with the provided state. :param instance: either share object or text with its ID. :param state: text with new state to set for share. """ return self._action(action_name, instance, {"status": state}) @api_versions.wraps("2.3", "2.6") def reset_state(self, instance, state): return self._do_reset_state(instance, state, "os-reset_status") @api_versions.wraps("2.7") # noqa def reset_state(self, instance, state): return self._do_reset_state(instance, state, "reset_status")<|fim▁end|>
# 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.
<|file_name|>940_more_supplier_details.py<|end_file_name|><|fim▁begin|>""" Extend suppliers table with new fields (to be initially populated from declaration data) Revision ID: 940 Revises: 930 Create Date: 2017-08-16 16:39:00.000000 """ # revision identifiers, used by Alembic. revision = '940' down_revision = '930' from alembic import op import sqlalchemy as sa <|fim▁hole|>def upgrade(): op.add_column(u'suppliers', sa.Column('registered_name', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('registration_country', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('other_company_registration_number', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('registration_date', sa.DateTime(), nullable=True)) op.add_column(u'suppliers', sa.Column('vat_number', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('organisation_size', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('trading_status', sa.String(), nullable=True)) def downgrade(): op.drop_column(u'suppliers', 'registered_name') op.drop_column(u'suppliers', 'registration_country') op.drop_column(u'suppliers', 'other_company_registration_number') op.drop_column(u'suppliers', 'registration_date') op.drop_column(u'suppliers', 'vat_number') op.drop_column(u'suppliers', 'organisation_size') op.drop_column(u'suppliers', 'trading_status')<|fim▁end|>
<|file_name|>example.py<|end_file_name|><|fim▁begin|>import numpy try: import matplotlib.pyplot as pypl plotting = True except: plotting = False import os, shutil this_dir = os.path.dirname(os.path.realpath(__file__)) import condor import logging logger = logging.getLogger('condor') logger.setLevel("INFO") #logger.setLevel("DEBUG") out_dir = this_dir + "/pngs" if os.path.exists(out_dir): shutil.rmtree(out_dir) os.mkdir(out_dir) # Source src = condor.Source(wavelength=0.1E-9, pulse_energy=1E-3, focus_diameter=1E-6) # Detector det = condor.Detector(distance=0.5, pixel_size=750E-6, nx=100, ny=100)#, cx=55, cy=55) #angles_d = numpy.array([0., 22.5, 45.]) angles_d = numpy.array([72.5]) for angle_d in angles_d: angle = angle_d/360.*2*numpy.pi rotation_axis = numpy.array([1.,1.,0.])/numpy.sqrt(2.) quaternion = condor.utils.rotation.quat(angle,rotation_axis[0],rotation_axis[1], rotation_axis[2]) rotation_values = numpy.array([quaternion]) rotation_formalism = "quaternion" rotation_mode = "extrinsic" #rotation_values = None #rotation_formalism = "random" #rotation_mode = "extrinsic" #rotation_values = None #rotation_formalism = None #rotation_mode = "extrinsic" #print("Angle = %.2f degrees" % angle_d) short_diameter = 25E-9*12/100. long_diameter = 2*short_diameter spheroid_diameter = condor.utils.spheroid_diffraction.to_spheroid_diameter(short_diameter/2.,long_diameter/2.) spheroid_flattening = condor.utils.spheroid_diffraction.to_spheroid_flattening(short_diameter/2.,long_diameter/2.) N_long = 20 N_short = int(round(short_diameter/long_diameter * N_long)) # Spheroid if True: # Ideal spheroid #print("Simulating spheroid") par = condor.ParticleSpheroid(diameter=spheroid_diameter, material_type="water", flattening=spheroid_flattening, rotation_values=rotation_values, rotation_formalism=rotation_formalism, rotation_mode=rotation_mode) s = "particle_spheroid" E = condor.Experiment(src, {s : par}, det) res = E.propagate() real_space = numpy.fft.fftshift(numpy.fft.ifftn(res["entry_1"]["data_1"]["data_fourier"])) vmin = numpy.log10(res["entry_1"]["data_1"]["data"].max()/10000.) if plotting: pypl.imsave(out_dir + "/%s_%2.2fdeg.png" % (s,angle_d), numpy.log10(res["entry_1"]["data_1"]["data"]), vmin=vmin) pypl.imsave(out_dir + "/%s_rs_%2.2fdeg.png" % (s,angle_d), abs(real_space)) if True: # Map (spheroid) #print("Simulating map (spheroid)") par = condor.ParticleMap(diameter=spheroid_diameter, material_type="water", flattening=spheroid_flattening, geometry="spheroid", rotation_values=rotation_values, rotation_formalism=rotation_formalism, rotation_mode=rotation_mode) s = "particle_map_spheroid" E = condor.Experiment(src, {s : par}, det) res = E.propagate() real_space = numpy.fft.fftshift(numpy.fft.ifftn(res["entry_1"]["data_1"]["data_fourier"])) vmin = numpy.log10(res["entry_1"]["data_1"]["data"].max()/10000.) if plotting: pypl.imsave(out_dir + "/%s_%2.2f.png" % (s,angle_d), numpy.log10(res["entry_1"]["data_1"]["data"]), vmin=vmin) pypl.imsave(out_dir + "/%s_rs_%2.2f.png" % (s,angle_d), abs(real_space)) # Box if True: # Map (box) dx = long_diameter/(N_long-1) map3d = numpy.zeros(shape=(N_long,N_long,N_long)) map3d[:N_short,:,:N_short] = 1. map3d[N_short:N_short+N_short,:N_short,:N_short] = 1. # Map #print("Simulating map (custom)") par = condor.ParticleMap(diameter=long_diameter, material_type="water", geometry="custom", map3d=map3d, dx=dx, rotation_values=rotation_values, rotation_formalism=rotation_formalism, rotation_mode=rotation_mode)<|fim▁hole|> res = E.propagate() if plotting: data_fourier = res["entry_1"]["data_1"]["data_fourier"] #data_fourier = abs(data_fourier)*numpy.exp(-1.j*numpy.angle(data_fourier)) real_space = numpy.fft.fftshift(numpy.fft.ifftn(numpy.fft.fftshift(data_fourier))) vmin = numpy.log10(res["entry_1"]["data_1"]["data"].max()/10000.) pypl.imsave(out_dir + "/%s_map.png" % (s),map3d.sum(0)) pypl.imsave(out_dir + "/%s_%2.2f.png" % (s,angle_d), numpy.log10(res["entry_1"]["data_1"]["data"]), vmin=vmin) pypl.imsave(out_dir + "/%s_%2.2f_phases.png" % (s,angle_d), numpy.angle(res["entry_1"]["data_1"]["data_fourier"])%(2*numpy.pi)) pypl.imsave(out_dir + "/%s_rs_%2.2f.png" % (s,angle_d), abs(real_space)) if True: # Atoms (box) #print("Simulating atoms") Z1,Y1,X1 = numpy.meshgrid(numpy.linspace(0, short_diameter, N_short), numpy.linspace(0, long_diameter, N_long), numpy.linspace(0, short_diameter, N_short), indexing="ij") Z2,Y2,X2 = numpy.meshgrid(numpy.linspace(0, short_diameter, N_short) + long_diameter/2., numpy.linspace(0, short_diameter, N_short), numpy.linspace(0, short_diameter, N_short), indexing="ij") Z = numpy.concatenate((Z1.ravel(),Z2.ravel())) Y = numpy.concatenate((Y1.ravel(),Y2.ravel())) X = numpy.concatenate((X1.ravel(),X2.ravel())) proj = numpy.zeros(shape=(N_long,N_long)) dx = long_diameter/(N_long-1) for (x,y,z) in zip(X.ravel(),Y.ravel(),Z.ravel()): proj[int(round(y/dx)),int(round(x/dx))] += 1 if plotting: pypl.imsave(out_dir + "/%s_proj.png" % (s),proj) atomic_positions = numpy.array([[x,y,z] for x,y,z in zip(X.ravel(),Y.ravel(),Z.ravel())]) atomic_numbers = numpy.ones(int(atomic_positions.size/3), dtype=numpy.int16) par = condor.ParticleAtoms(atomic_positions=atomic_positions, atomic_numbers=atomic_numbers, rotation_values=rotation_values, rotation_formalism=rotation_formalism, rotation_mode=rotation_mode) s = "particle_atoms" E = condor.Experiment(src, {s : par}, det) res = E.propagate() if plotting: real_space = numpy.fft.fftshift(numpy.fft.ifftn(numpy.fft.fftshift(res["entry_1"]["data_1"]["data_fourier"]))) fourier_space = res["entry_1"]["data_1"]["data_fourier"] vmin = numpy.log10(res["entry_1"]["data_1"]["data"].max()/10000.) pypl.imsave(out_dir + "/%s_%2.2f.png" % (s,angle_d), numpy.log10(res["entry_1"]["data_1"]["data"]), vmin=vmin) pypl.imsave(out_dir + "/%s_%2.2f_phases.png" % (s,angle_d), numpy.angle(fourier_space)%(2*numpy.pi)) pypl.imsave(out_dir + "/%s_rs_%2.2f.png" % (s,angle_d), abs(real_space))<|fim▁end|>
s = "particle_map_custom" E = condor.Experiment(src, {s : par}, det)
<|file_name|>explicit-self.rs<|end_file_name|><|fim▁begin|>// 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. static tau: f64 = 2.0*3.14159265358979323; struct Point {x: f64, y: f64} struct Size {w: f64, h: f64} enum shape { circle(Point, f64), rectangle(Point, Size) } fn compute_area(shape: &shape) -> f64 {<|fim▁hole|> rectangle(_, ref size) => size.w * size.h } } impl shape { // self is in the implicit self region pub fn select<'r, T>(&self, threshold: f64, a: &'r T, b: &'r T) -> &'r T { if compute_area(self) > threshold {a} else {b} } } fn select_based_on_unit_circle<'r, T>( threshold: f64, a: &'r T, b: &'r T) -> &'r T { let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0); shape.select(threshold, a, b) } #[deriving(Clone)] struct thing { x: A } #[deriving(Clone)] struct A { a: int } fn thing(x: A) -> thing { thing { x: x } } impl thing { pub fn bar(~self) -> int { self.x.a } pub fn quux(&self) -> int { self.x.a } pub fn baz<'a>(&'a self) -> &'a A { &self.x } pub fn spam(self) -> int { self.x.a } } trait Nus { fn f(&self); } impl Nus for thing { fn f(&self) {} } pub fn main() { let y = box thing(A {a: 10}); assert_eq!(y.clone().bar(), 10); assert_eq!(y.quux(), 10); let z = thing(A {a: 11}); assert_eq!(z.spam(), 11); }<|fim▁end|>
match *shape { circle(_, radius) => 0.5 * tau * radius * radius,
<|file_name|>MyApplication.java<|end_file_name|><|fim▁begin|>package com.a7av.news24h; import android.app.Application; import android.content.Context; import android.support.multidex.MultiDex; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; /** * MultiDex configuration */ public class MyApplication extends Application {<|fim▁hole|> protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }<|fim▁end|>
@Override
<|file_name|>snip.py<|end_file_name|><|fim▁begin|>import json import logging from flask import abort, redirect, render_template, request, send_file import ctrl.snip from . import handlers @handlers.route('/snip/<slug>.png') def snip_view(slug): filename = ctrl.snip.getSnipPath(slug) if filename == None: logging.warning("invalid slug: " + slug) abort(400)<|fim▁hole|>def snip_page(slug): snip = ctrl.snip.getSnip(slug) return render_template('snip.html', snip=snip) @handlers.route('/snip/upload', methods=['POST']) def snip_upload(): if 'file' not in request.files: abort(400) file = request.files['file'] snip = ctrl.snip.saveSnip(file) if request.args.get('redirect') == '0': return json.dumps({'slug': snip.slug}) else: return redirect('/snip/' + snip.slug) @handlers.route('/snip/new') def snip_new(): return render_template('snip-new.html')<|fim▁end|>
return send_file(filename, attachment_filename=slug + '.png', mimetype='image/png') @handlers.route('/snip/<slug>')
<|file_name|>ftp_rmdir.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import ftplib import os.path import sys p_debug = False def ftp_rmdir(ftp, folder, remove_toplevel, dontremove): for filename, attr in ftp.mlsd(folder): if attr['type'] == 'file' and filename not in dontremove: if p_debug: print( 'removing file [{0}] from folder [{1}]'.format(filename, folder))<|fim▁hole|> ftp_rmdir(ftp, filename, True, dontremove) if remove_toplevel: if p_debug: print('removing folder [{0}]'.format(folder)) ftp.rmd(folder) def main(): p_host = sys.argv[1] p_user = sys.argv[2] p_pass = sys.argv[3] p_dir = sys.argv[4] if p_debug: print(p_host) print(p_user) print(p_pass) print(p_dir) ftp = ftplib.FTP(p_host) ftp.login(user=p_user, passwd=p_pass) # ftp_rmdir(ftp, p_dir, False, set(['.ftpquota'])) ftp_rmdir(ftp, p_dir, False, set()) ftp.quit() if __name__ == '__main__': main()<|fim▁end|>
ftp.delete(os.path.join(folder, filename)) if attr['type'] == 'dir':
<|file_name|>cabi_powerpc.rs<|end_file_name|><|fim▁begin|>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty);<|fim▁hole|> n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, &coerce_to_int(ccx, size), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }<|fim▁end|>
<|file_name|>env.go<|end_file_name|><|fim▁begin|>package mock import ( "github.com/fkmhrk/OpenInvoice/v1/model/env"<|fim▁hole|>type EnvDAO struct { CreateResult env.Env GetResult env.Env GetListResult []*env.Env SaveResult error UpdateResult env.Env DeleteResult env.Env } func (d *EnvDAO) Create(key, value string) (env.Env, error) { return d.CreateResult, nil } func (d *EnvDAO) Get(key string) (env.Env, error) { return d.GetResult, nil } func (d *EnvDAO) GetList() ([]*env.Env, error) { return d.GetListResult, nil } func (d *EnvDAO) Save(list []*env.Env) error { return d.SaveResult } func (d *EnvDAO) Update(key, value string) (env.Env, error) { return d.UpdateResult, nil } func (d *EnvDAO) Delete(key string) (env.Env, error) { return d.DeleteResult, nil }<|fim▁end|>
)
<|file_name|>workers.go<|end_file_name|><|fim▁begin|>// Copyright 2016 Mark Clarkson // // 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<|fim▁hole|>// All api calls have the username and GUID to be sent as part of the request import ( "fmt" "github.com/mclarkson/obdi/external/ant0ine/go-json-rest/rest" "strconv" ) func (api *Api) GetAllWorkers(w rest.ResponseWriter, r *rest.Request) { // Check credentials login := r.PathParam("login") guid := r.PathParam("GUID") // Anyone can view envs //session := Session{} var errl error = nil //if session,errl = api.CheckLogin( login, guid ); errl != nil { if _, errl = api.CheckLogin(login, guid); errl != nil { rest.Error(w, errl.Error(), 401) return } defer api.TouchSession(guid) qs := r.URL.Query() // Query string - map[string][]string workers := []Worker{} if len(qs["env_id"]) > 0 && len(qs["env_cap_id"]) > 0 { mutex.Lock() err := api.db.Order("env_id,env_cap_id").Find(&workers, "env_id = ? and env_cap_id = ?", qs["env_id"][0], qs["env_cap_id"][0]) mutex.Unlock() if err.Error != nil { if !err.RecordNotFound() { rest.Error(w, err.Error.Error(), 500) return } } } else { mutex.Lock() err := api.db.Order("env_id,env_cap_id").Find(&workers) mutex.Unlock() if err.Error != nil { if !err.RecordNotFound() { rest.Error(w, err.Error.Error(), 500) return } } } // Create a slice of maps from users struct // to selectively copy database fields for display u := make([]map[string]interface{}, len(workers)) for i := range workers { u[i] = make(map[string]interface{}) u[i]["Id"] = workers[i].Id u[i]["EnvId"] = workers[i].EnvId u[i]["EnvCapId"] = workers[i].EnvCapId u[i]["WorkerUrl"] = workers[i].WorkerUrl if login == "admin" { u[i]["WorkerKey"] = workers[i].WorkerKey } else { u[i]["WorkerKey"] = "*****" } env_caps := EnvCap{} mutex.Lock() api.db.Model(&workers[i]).Related(&env_caps) mutex.Unlock() u[i]["EnvCapCode"] = env_caps.Code u[i]["EnvCapDesc"] = env_caps.Desc u[i]["EnvCapId"] = env_caps.Id } // Too much noise //api.LogActivity( session.Id, "Sent list of users" ) w.WriteJson(&u) } func (api *Api) AddWorker(w rest.ResponseWriter, r *rest.Request) { // Check credentials login := r.PathParam("login") guid := r.PathParam("GUID") // Only admin is allowed if login != "admin" { rest.Error(w, "Not allowed", 400) return } session := Session{} var errl error if session, errl = api.CheckLogin(login, guid); errl != nil { rest.Error(w, errl.Error(), 401) return } defer api.TouchSession(guid) // Can't add if it exists already worker := Worker{} if err := r.DecodeJsonPayload(&worker); err != nil { rest.Error(w, "Invalid data format received.", 400) return } else if len(worker.WorkerUrl) == 0 { rest.Error(w, "Incorrect data format received."+ " WorkerUrl is unset.", 400) return } { tmpworker := Worker{} mutex.Lock() if !api.db.Find(&tmpworker, "env_id = ? and env_cap_id = ?", worker.EnvId, worker.EnvCapId).RecordNotFound() { mutex.Unlock() rest.Error(w, "Record exists.", 400) return } mutex.Unlock() } // Add worker mutex.Lock() if err := api.db.Save(&worker).Error; err != nil { mutex.Unlock() rest.Error(w, err.Error(), 400) return } mutex.Unlock() env_cap := EnvCap{} mutex.Lock() api.db.First(&env_cap, worker.EnvCapId) mutex.Unlock() text := fmt.Sprintf("Added new worker '%s->%s'.", env_cap.Desc, worker.WorkerUrl) api.LogActivity(session.Id, text) w.WriteJson(worker) } func (api *Api) UpdateWorker(w rest.ResponseWriter, r *rest.Request) { // Check credentials login := r.PathParam("login") guid := r.PathParam("GUID") // Only admin is allowed if login != "admin" { rest.Error(w, "Not allowed", 400) return } session := Session{} var errl error if session, errl = api.CheckLogin(login, guid); errl != nil { rest.Error(w, errl.Error(), 401) return } defer api.TouchSession(guid) // Ensure user exists id := r.PathParam("id") // Check that the id string is a number if _, err := strconv.Atoi(id); err != nil { rest.Error(w, "Invalid id.", 400) return } // Load data from db, then ... worker := Worker{} mutex.Lock() if api.db.Find(&worker, id).RecordNotFound() { mutex.Unlock() rest.Error(w, "Record not found.", 400) return } mutex.Unlock() // ... overwrite any sent fields if err := r.DecodeJsonPayload(&worker); err != nil { //rest.Error(w, err.Error(), 400) rest.Error(w, "Invalid data format received.", 400) return } // Force the use of the path id over an id in the payload Id, _ := strconv.Atoi(id) worker.Id = int64(Id) mutex.Lock() if err := api.db.Save(&worker).Error; err != nil { mutex.Unlock() rest.Error(w, err.Error(), 400) return } mutex.Unlock() env_cap := EnvCap{} mutex.Lock() api.db.First(&env_cap, worker.EnvCapId) mutex.Unlock() text := fmt.Sprintf("Updated worker '%s->%s'.", env_cap.Desc, worker.WorkerUrl) api.LogActivity(session.Id, text) w.WriteJson("Success") } func (api *Api) DeleteWorker(w rest.ResponseWriter, r *rest.Request) { // Check credentials login := r.PathParam("login") guid := r.PathParam("GUID") // Only admin is allowed if login != "admin" { rest.Error(w, "Not allowed", 400) return } session := Session{} var errl error if session, errl = api.CheckLogin(login, guid); errl != nil { rest.Error(w, errl.Error(), 401) return } defer api.TouchSession(guid) // Delete id := 0 if id, errl = strconv.Atoi(r.PathParam("id")); errl != nil { rest.Error(w, "Invalid id.", 400) return } worker := Worker{} mutex.Lock() if api.db.First(&worker, id).RecordNotFound() { mutex.Unlock() rest.Error(w, "Record not found.", 400) return } mutex.Unlock() mutex.Lock() if err := api.db.Delete(&worker).Error; err != nil { mutex.Unlock() rest.Error(w, err.Error(), 400) return } mutex.Unlock() env_cap := EnvCap{} mutex.Lock() api.db.First(&env_cap, worker.EnvCapId) mutex.Unlock() text := fmt.Sprintf("Deleted worker '%s->%s'.", env_cap.Desc, worker.WorkerUrl) api.LogActivity(session.Id, text) w.WriteJson("Success") }<|fim▁end|>
<|file_name|>test_remote_access_controller.py<|end_file_name|><|fim▁begin|># coding: utf-8 from __future__ import absolute_import import unittest from flask import json from six import BytesIO from openapi_server.models.computer_set import ComputerSet # noqa: E501 from openapi_server.models.free_style_build import FreeStyleBuild # noqa: E501 from openapi_server.models.free_style_project import FreeStyleProject # noqa: E501 from openapi_server.models.hudson import Hudson # noqa: E501 from openapi_server.models.list_view import ListView # noqa: E501 from openapi_server.models.queue import Queue # noqa: E501 from openapi_server.test import BaseTestCase class TestRemoteAccessController(BaseTestCase): """RemoteAccessController integration test stubs""" def test_get_computer(self): """Test case for get_computer """<|fim▁hole|> 'Accept': 'application/json', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/computer/api/json', method='GET', headers=headers, query_string=query_string) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_jenkins(self): """Test case for get_jenkins """ headers = { 'Accept': 'application/json', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/api/json', method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_job(self): """Test case for get_job """ headers = { 'Accept': 'application/json', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/api/json'.format(name='name_example'), method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_job_config(self): """Test case for get_job_config """ headers = { 'Accept': 'text/xml', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/config.xml'.format(name='name_example'), method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_job_last_build(self): """Test case for get_job_last_build """ headers = { 'Accept': 'application/json', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/lastBuild/api/json'.format(name='name_example'), method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_job_progressive_text(self): """Test case for get_job_progressive_text """ query_string = [('start', 'start_example')] headers = { 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/{number}/logText/progressiveText'.format(name='name_example', number='number_example'), method='GET', headers=headers, query_string=query_string) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_queue(self): """Test case for get_queue """ headers = { 'Accept': 'application/json', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/queue/api/json', method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_queue_item(self): """Test case for get_queue_item """ headers = { 'Accept': 'application/json', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/queue/item/{number}/api/json'.format(number='number_example'), method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_view(self): """Test case for get_view """ headers = { 'Accept': 'application/json', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/view/{name}/api/json'.format(name='name_example'), method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_get_view_config(self): """Test case for get_view_config """ headers = { 'Accept': 'text/xml', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/view/{name}/config.xml'.format(name='name_example'), method='GET', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_head_jenkins(self): """Test case for head_jenkins """ headers = { 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/api/json', method='HEAD', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_create_item(self): """Test case for post_create_item """ body = 'body_example' query_string = [('name', 'name_example'), ('from', '_from_example'), ('mode', 'mode_example')] headers = { 'Accept': '*/*', 'Content-Type': 'application/json', 'jenkins_crumb': 'jenkins_crumb_example', 'content_type': 'content_type_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/createItem', method='POST', headers=headers, data=json.dumps(body), content_type='application/json', query_string=query_string) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_create_view(self): """Test case for post_create_view """ body = 'body_example' query_string = [('name', 'name_example')] headers = { 'Accept': '*/*', 'Content-Type': 'application/json', 'jenkins_crumb': 'jenkins_crumb_example', 'content_type': 'content_type_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/createView', method='POST', headers=headers, data=json.dumps(body), content_type='application/json', query_string=query_string) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_job_build(self): """Test case for post_job_build """ query_string = [('json', 'json_example'), ('token', 'token_example')] headers = { 'jenkins_crumb': 'jenkins_crumb_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/build'.format(name='name_example'), method='POST', headers=headers, query_string=query_string) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_job_config(self): """Test case for post_job_config """ body = 'body_example' headers = { 'Accept': '*/*', 'Content-Type': 'application/json', 'jenkins_crumb': 'jenkins_crumb_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/config.xml'.format(name='name_example'), method='POST', headers=headers, data=json.dumps(body), content_type='application/json') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_job_delete(self): """Test case for post_job_delete """ headers = { 'jenkins_crumb': 'jenkins_crumb_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/doDelete'.format(name='name_example'), method='POST', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_job_disable(self): """Test case for post_job_disable """ headers = { 'jenkins_crumb': 'jenkins_crumb_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/disable'.format(name='name_example'), method='POST', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_job_enable(self): """Test case for post_job_enable """ headers = { 'jenkins_crumb': 'jenkins_crumb_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/enable'.format(name='name_example'), method='POST', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_job_last_build_stop(self): """Test case for post_job_last_build_stop """ headers = { 'jenkins_crumb': 'jenkins_crumb_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/job/{name}/lastBuild/stop'.format(name='name_example'), method='POST', headers=headers) self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_post_view_config(self): """Test case for post_view_config """ body = 'body_example' headers = { 'Accept': '*/*', 'Content-Type': 'application/json', 'jenkins_crumb': 'jenkins_crumb_example', 'Authorization': 'Basic Zm9vOmJhcg==', } response = self.client.open( '/view/{name}/config.xml'.format(name='name_example'), method='POST', headers=headers, data=json.dumps(body), content_type='application/json') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) if __name__ == '__main__': unittest.main()<|fim▁end|>
query_string = [('depth', 56)] headers = {
<|file_name|>gather_op_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 The TensorFlow 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. # ============================================================================== """Tests for tensorflow.ops.tf.gather.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.platform import test _TEST_TYPES = (dtypes.int64, dtypes.float32, dtypes.complex64, dtypes.complex128) class GatherTest(test.TestCase): def _buildParams(self, data, dtype): data = data.astype(dtype.as_numpy_dtype) # For complex types, add an index-dependent imaginary component so we can # tell we got the right value. if dtype.is_complex: return data + 10j * data return data def testScalar1D(self): with self.cached_session(use_gpu=True): data = np.array([0, 1, 2, 3, 7, 5]) for dtype in _TEST_TYPES: for indices in 4, [1, 2, 2, 4, 5]: params_np = self._buildParams(data, dtype) params = constant_op.constant(params_np) indices_tf = constant_op.constant(indices) gather_t = array_ops.gather(params, indices_tf) gather_val = gather_t.eval() np_val = params_np[indices] self.assertAllEqual(np_val, gather_val) self.assertEqual(np_val.shape, gather_t.get_shape()) def testScalar2D(self): with self.session(use_gpu=True): data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]) for dtype in _TEST_TYPES: for axis in range(data.ndim): params_np = self._buildParams(data, dtype) params = constant_op.constant(params_np) indices = constant_op.constant(2) gather_t = array_ops.gather(params, indices, axis=axis) gather_val = gather_t.eval() self.assertAllEqual(np.take(params_np, 2, axis=axis), gather_val) expected_shape = data.shape[:axis] + data.shape[axis + 1:] self.assertEqual(expected_shape, gather_t.get_shape()) def testSimpleTwoD32(self): with self.session(use_gpu=True): data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]) for dtype in _TEST_TYPES: for axis in range(data.ndim): params_np = self._buildParams(data, dtype) params = constant_op.constant(params_np) # The indices must be in bounds for any axis. indices = constant_op.constant([0, 1, 0, 2]) gather_t = array_ops.gather(params, indices, axis=axis) gather_val = gather_t.eval() self.assertAllEqual(np.take(params_np, [0, 1, 0, 2], axis=axis), gather_val) expected_shape = data.shape[:axis] + (4,) + data.shape[axis + 1:] self.assertEqual(expected_shape, gather_t.get_shape()) def testHigherRank(self): # We check that scalar and empty indices shapes work as well shape = (2, 1, 3, 2) for indices_shape in (), (0,), (2, 0), (2, 3): for dtype in _TEST_TYPES: for axis in range(len(shape)):<|fim▁hole|> params = self._buildParams(np.random.randn(*shape), dtype) indices = np.random.randint(shape[axis], size=indices_shape) with self.cached_session(use_gpu=True) as sess: tf_params = constant_op.constant(params) tf_indices = constant_op.constant(indices) # Check that both positive and negative indices for axis work. tf_axis = constant_op.constant(axis) tf_negative_axis = constant_op.constant(-len(shape) + axis) gather = array_ops.gather(tf_params, tf_indices, axis=tf_axis) gather_negative_axis = array_ops.gather( tf_params, tf_indices, axis=tf_negative_axis) gather_value, gather_negative_axis_value = sess.run( [gather, gather_negative_axis]) gather_np = np.take(params, indices, axis) self.assertAllEqual(gather_np, gather_value) self.assertAllEqual(gather_np, gather_negative_axis_value) expected_shape = (params.shape[:axis] + indices.shape + params.shape[axis + 1:]) self.assertEqual(expected_shape, gather.shape) self.assertEqual(expected_shape, gather_negative_axis.shape) # Test gradients gather_grad = np.random.randn( *gather.get_shape().as_list()).astype(dtype.as_numpy_dtype) if dtype.is_complex: gather_grad -= 1j * gather_grad params_grad, indices_grad, axis_grad = gradients_impl.gradients( gather, [tf_params, tf_indices, tf_axis], gather_grad) self.assertEqual(indices_grad, None) self.assertEqual(axis_grad, None) if dtype.is_integer: self.assertEqual(params_grad, None) continue # For axis 0, we are able to create an efficient IndexedSlices for # the gradient. if axis == 0: self.assertEqual(type(params_grad), ops.IndexedSlices) params_grad = ops.convert_to_tensor(params_grad) correct_params_grad = np.zeros(shape).astype(dtype.as_numpy_dtype) outer_dims = axis inner_dims = len(shape) - axis - 1 gather_grad = gather_grad.reshape( shape[:axis] + (indices.size,) + shape[axis + 1:]) for source_index, dest_index in enumerate(indices.flat): dest_slice = ((slice(None),) * outer_dims + (dest_index,) + (slice(None),) * inner_dims) source_slice = ((slice(None),) * outer_dims + (source_index,) + (slice(None),) * inner_dims) correct_params_grad[dest_slice] += gather_grad[source_slice] self.assertAllClose(correct_params_grad, params_grad.eval(), atol=2e-6, rtol=2e-6) def testString(self): params = np.array([[b"asdf", b"zxcv"], [b"qwer", b"uiop"]]) with self.cached_session(): self.assertAllEqual([b"qwer", b"uiop"], array_ops.gather(params, 1, axis=0).eval()) self.assertAllEqual([b"asdf", b"qwer"], array_ops.gather(params, 0, axis=1).eval()) def testUInt32AndUInt64(self): for unsigned_type in (dtypes.uint32, dtypes.uint64): params = self._buildParams( np.array([[1, 2, 3], [7, 8, 9]]), unsigned_type) with self.cached_session(): self.assertAllEqual([7, 8, 9], array_ops.gather(params, 1, axis=0).eval()) self.assertAllEqual([1, 7], array_ops.gather(params, 0, axis=1).eval()) def testUnknownIndices(self): params = constant_op.constant([[0, 1, 2]]) indices = array_ops.placeholder(dtypes.int32) gather_t = array_ops.gather(params, indices) self.assertEqual(None, gather_t.get_shape()) def testUnknownAxis(self): params = constant_op.constant([[0, 1, 2]]) indices = constant_op.constant([[0, 0], [0, 0]]) axis = array_ops.placeholder(dtypes.int32) gather_t = array_ops.gather(params, indices, axis=axis) # Rank 2 params with rank 2 indices results in a rank 3 shape. self.assertEqual([None, None, None], gather_t.shape.as_list()) # If indices is also unknown the result rank is unknown. indices = array_ops.placeholder(dtypes.int32) gather_t = array_ops.gather(params, indices, axis=axis) self.assertEqual(None, gather_t.shape) def testBadIndicesCPU(self): with self.session(use_gpu=False): params = [[0, 1, 2], [3, 4, 5]] with self.assertRaisesOpError(r"indices\[0,0\] = 7 is not in \[0, 2\)"): array_ops.gather(params, [[7]], axis=0).eval() with self.assertRaisesOpError(r"indices\[0,0\] = 7 is not in \[0, 3\)"): array_ops.gather(params, [[7]], axis=1).eval() def _disabledTestBadIndicesGPU(self): # TODO disabled due to different behavior on GPU and CPU # On GPU the bad indices do not raise error but fetch 0 values if not test.is_gpu_available(): return with self.session(use_gpu=True): params = [[0, 1, 2], [3, 4, 5]] with self.assertRaisesOpError(r"indices\[0,0\] = 7 is not in \[0, 2\)"): array_ops.gather(params, [[7]], axis=0).eval() with self.assertRaisesOpError(r"indices\[0,0\] = 7 is not in \[0, 3\)"): array_ops.gather(params, [[7]], axis=1).eval() def testBadAxis(self): with self.session(use_gpu=True): params = [0, 1, 2] params_ph = array_ops.placeholder(dtypes.int32) indices = 0 for bad_axis in (1, 2, -2): # Shape inference can validate axis for known params rank. with self.assertRaisesWithPredicateMatch( ValueError, "Shape must be at least rank . but is rank 1"): array_ops.gather(params, indices, axis=bad_axis) # If params rank is unknown, an op error occurs. with self.assertRaisesOpError( r"Expected axis in the range \[-1, 1\), but got %s" % bad_axis): array_ops.gather(params_ph, indices, axis=bad_axis).eval( feed_dict={params_ph: params}) def testEmptySlices(self): with self.session(use_gpu=True): for dtype in _TEST_TYPES: for itype in np.int32, np.int64: # Leading axis gather. params = np.zeros((7, 0, 0), dtype=dtype.as_numpy_dtype) indices = np.array([3, 4], dtype=itype) gather = array_ops.gather(params, indices, axis=0) self.assertAllEqual(gather.eval(), np.zeros((2, 0, 0))) # Middle axis gather. params = np.zeros((0, 7, 0), dtype=dtype.as_numpy_dtype) gather = array_ops.gather(params, indices, axis=1) self.assertAllEqual(gather.eval(), np.zeros((0, 2, 0))) # Trailing axis gather. params = np.zeros((0, 0, 7), dtype=dtype.as_numpy_dtype) gather = array_ops.gather(params, indices, axis=2) self.assertAllEqual(gather.eval(), np.zeros((0, 0, 2))) if __name__ == "__main__": test.main()<|fim▁end|>
<|file_name|>body.rs<|end_file_name|><|fim▁begin|>use url::form_urlencoded; use hyper::Chunk; use mime; use controller::context::BodyContent; pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent> { if body_data.is_empty() {<|fim▁hole|> } else { let is_multipart_form_data = if let Some(ref content_mime) = content_type { content_mime.type_() == mime::MULTIPART && content_mime.subtype() == mime::FORM_DATA } else { false }; let body_parsed = if is_multipart_form_data { parse_multipart_form_data(content_type, body_data) } else { parse_form_urlencoded(body_data) }; Some(body_parsed) } } fn parse_form_urlencoded(body_data: Chunk) -> BodyContent { let vec: Vec<u8> = body_data.iter().cloned().collect(); form_urlencoded::parse(vec.as_ref()) .map(|(key, value)| (key.to_string(), value.to_string())) .collect() } // TODO: realize this function // https://github.com/abonander/multipart-async // https://ru.wikipedia.org/wiki/HTTP#Множественное_содержимое fn parse_multipart_form_data(content_type: Option<&mime::Mime>, body_data: Chunk) -> BodyContent { if let Some(boundary) = get_boundary(content_type) { println!("multipart request received, boundary: {}", boundary); } parse_form_urlencoded(body_data) // TODO: this is stub } fn get_boundary(content_type: Option<&mime::Mime>) -> Option<String> { content_type .and_then(|content_mime| { content_mime.get_param(mime::BOUNDARY).map(|boundary|boundary.as_ref().into()) }) }<|fim▁end|>
None
<|file_name|>DownloadView.cpp<|end_file_name|><|fim▁begin|>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file DownloadView.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "DownloadView.h" #include <QtWidgets> #include <QtCore> #include <libethereum/DownloadMan.h> #include "Grapher.h" using namespace std; using namespace dev; using namespace dev::eth; DownloadView::DownloadView(QWidget* _p): QWidget(_p) { } void DownloadView::paintEvent(QPaintEvent*) { QPainter p(this); p.fillRect(rect(), Qt::white); if (!m_man || m_man->chain().empty() || !m_man->subCount()) return; double ratio = (double)rect().width() / rect().height(); if (ratio < 1) ratio = 1 / ratio; double n = min(rect().width(), rect().height()) / ceil(sqrt(m_man->chain().size() / ratio)); // QSizeF area(rect().width() / floor(rect().width() / n), rect().height() / floor(rect().height() / n)); QSizeF area(n, n); QPointF pos(0, 0); auto const& bg = m_man->blocksGot(); for (unsigned i = bg.all().first, ei = bg.all().second; i < ei; ++i) { int s = -2; if (bg.contains(i)) s = -1; else { unsigned h = 0; m_man->foreachSub([&](DownloadSub const& sub) { if (sub.asked().contains(i)) s = h; h++; }); } unsigned dh = 360 / m_man->subCount(); if (s == -2) p.fillRect(QRectF(QPointF(pos) + QPointF(3 * area.width() / 8, 3 * area.height() / 8), area / 4), Qt::black); else if (s == -1) p.fillRect(QRectF(QPointF(pos) + QPointF(1 * area.width() / 8, 1 * area.height() / 8), area * 3 / 4), Qt::black); else p.fillRect(QRectF(QPointF(pos) + QPointF(1 * area.width() / 8, 1 * area.height() / 8), area * 3 / 4), QColor::fromHsv(s * dh, 64, 128)); pos.setX(pos.x() + n); if (pos.x() >= rect().width() - n) pos = QPoint(0, pos.y() + n); }<|fim▁hole|><|fim▁end|>
}
<|file_name|>poll_opt.rs<|end_file_name|><|fim▁begin|>use std::{fmt, ops}; /// Options supplied when registering an `Evented` handle with `Poll` /// /// `PollOpt` values can be combined together using the various bitwise /// operators. /// /// For high level documentation on polling and poll options, see [`Poll`]. /// /// [`Poll`]: struct.Poll.html #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord)] pub(crate) struct PollOpt(usize); impl PollOpt { /// Return a `PollOpt` representing no set options. /// /// See [`Poll`] for more documentation on polling. /// /// [`Poll`]: struct.Poll.html #[inline] pub fn empty() -> PollOpt { PollOpt(0) } /// Return a `PollOpt` representing edge-triggered notifications. /// /// See [`Poll`] for more documentation on polling. /// /// [`Poll`]: struct.Poll.html #[inline] pub fn edge() -> PollOpt { PollOpt(0b0001) } /// Return a `PollOpt` representing level-triggered notifications. /// /// See [`Poll`] for more documentation on polling. /// /// [`Poll`]: struct.Poll.html #[inline] pub fn level() -> PollOpt { PollOpt(0b0010) } /// Return a `PollOpt` representing oneshot notifications. /// /// See [`Poll`] for more documentation on polling. /// /// [`Poll`]: struct.Poll.html #[inline] pub fn oneshot() -> PollOpt { PollOpt(0b0100) } /// Returns true if the options include edge-triggered notifications. /// /// See [`Poll`] for more documentation on polling. /// /// [`Poll`]: struct.Poll.html #[inline] pub fn is_edge(&self) -> bool {<|fim▁hole|> /// Returns true if the options includes oneshot. /// /// See [`Poll`] for more documentation on polling. /// /// [`Poll`]: struct.Poll.html #[inline] pub fn is_oneshot(&self) -> bool { self.contains(PollOpt::oneshot()) } /// Returns true if `self` is a superset of `other`. /// /// `other` may represent more than one option, in which case the function /// only returns true if `self` contains all of the options specified in /// `other`. /// /// See [`Poll`] for more documentation on polling. /// /// [`Poll`]: struct.Poll.html #[inline] pub fn contains(&self, other: PollOpt) -> bool { (*self & other) == other } } impl ops::BitOr for PollOpt { type Output = PollOpt; #[inline] fn bitor(self, other: PollOpt) -> PollOpt { PollOpt(self.0 | other.0) } } impl ops::BitXor for PollOpt { type Output = PollOpt; #[inline] fn bitxor(self, other: PollOpt) -> PollOpt { PollOpt(self.0 ^ other.0) } } impl ops::BitAnd for PollOpt { type Output = PollOpt; #[inline] fn bitand(self, other: PollOpt) -> PollOpt { PollOpt(self.0 & other.0) } } impl ops::Sub for PollOpt { type Output = PollOpt; #[inline] fn sub(self, other: PollOpt) -> PollOpt { PollOpt(self.0 & !other.0) } } impl fmt::Debug for PollOpt { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut one = false; let flags = [ (PollOpt::edge(), "Edge-Triggered"), (PollOpt::level(), "Level-Triggered"), (PollOpt::oneshot(), "OneShot"), ]; for &(flag, msg) in &flags { if self.contains(flag) { if one { write!(fmt, " | ")? } write!(fmt, "{}", msg)?; one = true } } if !one { fmt.write_str("(empty)")?; } Ok(()) } } impl From<PollOpt> for usize { fn from(src: PollOpt) -> usize { src.0 } } impl From<usize> for PollOpt { fn from(src: usize) -> PollOpt { PollOpt(src) } } #[test] fn test_debug_pollopt() { assert_eq!("(empty)", format!("{:?}", PollOpt::empty())); assert_eq!("Edge-Triggered", format!("{:?}", PollOpt::edge())); assert_eq!("Level-Triggered", format!("{:?}", PollOpt::level())); assert_eq!("OneShot", format!("{:?}", PollOpt::oneshot())); }<|fim▁end|>
self.contains(PollOpt::edge()) }
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import importlib from django.conf import settings from django.views import View class BaseView(View): """后台管理基类""" def __init__(self): self.context = {} self.context["path"] = {} def dispatch(self,request,*args,**kwargs): _path = request.path_info.split("/")[1:] self.context["path"]["app"] = _path[0] self.context["path"]["module"] = _path[1]<|fim▁hole|> imp_module_path = self.context["path"]["app"]+".views."+self.context["path"]["module"] imp_module = importlib.import_module(imp_module_path) imp_cls = getattr(imp_module,self.context["path"]["module"].capitalize()) return getattr(imp_cls,self.context["path"]["action"])(self,request)<|fim▁end|>
self.context["path"]["action"] = _path[-1]
<|file_name|>service_handler.go<|end_file_name|><|fim▁begin|>package scimoxy <|fim▁hole|><|fim▁end|>
type ServiceHandler interface { Users() }