code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
# Copyright (c) 2013, Ruslan Baratov
# All rights reserved.
# !!! DO NOT PLACE HEADER GUARDS HERE !!!
include(hunter_add_version)
include(hunter_cacheable)
include(hunter_download)
include(hunter_pick_scheme)
include(hunter_cmake_args)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter.tar.gz"
SHA1
1ed1c26d11fb592056c1cb912bd3c784afa96eaa
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-1"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-1.tar.gz"
SHA1
0cb1dcf75e144ad052d3f1e4923a7773bf9b494f
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-2"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-2.tar.gz"
SHA1
e62b2ef70308f63c32c560f7b6e252442eed4d57
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-3"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-3.tar.gz"
SHA1
fea7d3020e20f059255484c69755753ccadf6362
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-4"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-4.tar.gz"
SHA1
9b439c0c25437a083957b197ac6905662a5d901b
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-5"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-5.tar.gz"
SHA1
796804df3facb074087a4d8ba6f652e5ac69ad7f
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-6"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-6.tar.gz"
SHA1
64b93147abe287da8fe4e18cfd54ba9297dafb82
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-7"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-7.tar.gz"
SHA1
19b5c98747768bcd0622714f2ed40f17aee406b2
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-8"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-8.tar.gz"
SHA1
ac4d2215aa1b1d745a096e5e3b2dbe0c0f229ea5
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-9"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-9.tar.gz"
SHA1
8a47fe9c4e550f4ed0e2c05388dd291a059223d9
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-10"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-10.tar.gz"
SHA1
374e6dbe8619ab467c6b1a0b470a598407b172e9
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
"1.7.0-hunter-11"
URL
"https://github.com/hunter-packages/gtest/archive/v1.7.0-hunter-11.tar.gz"
SHA1
c6ae948ca2bea1d734af01b1069491b00933ed31
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
1.8.0-hunter-p2
URL
"https://github.com/hunter-packages/googletest/archive/1.8.0-hunter-p2.tar.gz"
SHA1
93148cb8850abe78b76ed87158fdb6b9c48e38c4
)
hunter_add_version(
PACKAGE_NAME
GTest
VERSION
1.8.0-hunter-p5
URL https://github.com/hunter-packages/googletest/archive/1.8.0-hunter-p5.tar.gz
SHA1 3325aa4fc8b30e665c9f73a60f19387b7db36f85
)
if(HUNTER_GTest_VERSION VERSION_LESS 1.8.0)
set(_gtest_license "LICENSE")
else()
set(_gtest_license "googletest/LICENSE")
endif()
hunter_cmake_args(
GTest
CMAKE_ARGS
HUNTER_INSTALL_LICENSE_FILES=${_gtest_license}
)
hunter_pick_scheme(DEFAULT url_sha1_cmake)
hunter_cacheable(GTest)
hunter_download(PACKAGE_NAME GTest PACKAGE_INTERNAL_DEPS_ID 1)
| x10mind/hunter | cmake/projects/GTest/hunter.cmake | CMake | bsd-2-clause | 3,722 |
class Cpm < Formula
desc "Fast CPAN module installer"
homepage "https://metacpan.org/pod/cpm"
url "https://cpan.metacpan.org/authors/id/S/SK/SKAJI/App-cpm-0.997002.tar.gz"
sha256 "19de1224b5c86d566eb0b85767775efb5bbab82ce98ee8c44f8843f26aabbbab"
license any_of: ["Artistic-1.0-Perl", "GPL-1.0-or-later"]
head "https://github.com/skaji/cpm.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "ec077e8877216d394c00f4bae315edc76d0dd293d1d24b691526ee596766dcc9"
sha256 cellar: :any_skip_relocation, big_sur: "c80c08f2faf3be4f3ffe1577c1002b2a9d44efbe66c8eae8068c2b68b537134f"
sha256 cellar: :any_skip_relocation, catalina: "5ee136ba90a46455007f9e8f5f3de12d55dc8bb888f366c03838cdbc52ab6f63"
sha256 cellar: :any_skip_relocation, mojave: "570d8a40888cc518229910ab30d0ee8c89a0b72a86d8cc12cea8222df885d5cb"
end
depends_on "perl"
resource "Module::Build::Tiny" do
url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/Module-Build-Tiny-0.039.tar.gz"
sha256 "7d580ff6ace0cbe555bf36b86dc8ea232581530cbeaaea09bccb57b55797f11c"
end
resource "CPAN::Common::Index" do
url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/CPAN-Common-Index-0.010.tar.gz"
sha256 "c43ddbb22fd42b06118fe6357f53700fbd77f531ba3c427faafbf303cbf4eaf0"
end
resource "CPAN::DistnameInfo" do
url "https://cpan.metacpan.org/authors/id/G/GB/GBARR/CPAN-DistnameInfo-0.12.tar.gz"
sha256 "2f24fbe9f7eeacbc269d35fc61618322fc17be499ee0cd9018f370934a9f2435"
end
resource "CPAN::Meta::Check" do
url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/CPAN-Meta-Check-0.014.tar.gz"
sha256 "28a0572bfc1c0678d9ce7da48cf521097ada230f96eb3d063fcbae1cfe6a351f"
end
resource "Capture::Tiny" do
url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Capture-Tiny-0.48.tar.gz"
sha256 "6c23113e87bad393308c90a207013e505f659274736638d8c79bac9c67cc3e19"
end
resource "Class::Tiny" do
url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Class-Tiny-1.008.tar.gz"
sha256 "ee058a63912fa1fcb9a72498f56ca421a2056dc7f9f4b67837446d6421815615"
end
resource "Command::Runner" do
url "https://cpan.metacpan.org/authors/id/S/SK/SKAJI/Command-Runner-0.103.tar.gz"
sha256 "0f180b5c3b3fc9db7b83d4a5fdd959db34f7d6d2472f817dbf8b4b795a9dc82a"
end
resource "ExtUtils::Config" do
url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-Config-0.008.tar.gz"
sha256 "ae5104f634650dce8a79b7ed13fb59d67a39c213a6776cfdaa3ee749e62f1a8c"
end
resource "ExtUtils::Helpers" do
url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-Helpers-0.026.tar.gz"
sha256 "de901b6790a4557cf4ec908149e035783b125bf115eb9640feb1bc1c24c33416"
end
resource "ExtUtils::InstallPaths" do
url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-InstallPaths-0.012.tar.gz"
sha256 "84735e3037bab1fdffa3c2508567ad412a785c91599db3c12593a50a1dd434ed"
end
resource "ExtUtils::MakeMaker::CPANfile" do
url "https://cpan.metacpan.org/authors/id/I/IS/ISHIGAKI/ExtUtils-MakeMaker-CPANfile-0.09.tar.gz"
sha256 "2c077607d4b0a108569074dff76e8168659062ada3a6af78b30cca0d40f8e275"
end
resource "File::Copy::Recursive" do
url "https://cpan.metacpan.org/authors/id/D/DM/DMUEY/File-Copy-Recursive-0.45.tar.gz"
sha256 "d3971cf78a8345e38042b208bb7b39cb695080386af629f4a04ffd6549df1157"
end
resource "File::Which" do
url "https://cpan.metacpan.org/authors/id/P/PL/PLICEASE/File-Which-1.23.tar.gz"
sha256 "b79dc2244b2d97b6f27167fc3b7799ef61a179040f3abd76ce1e0a3b0bc4e078"
end
resource "File::pushd" do
url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/File-pushd-1.016.tar.gz"
sha256 "d73a7f09442983b098260df3df7a832a5f660773a313ca273fa8b56665f97cdc"
end
resource "HTTP::Tinyish" do
url "https://cpan.metacpan.org/authors/id/M/MI/MIYAGAWA/HTTP-Tinyish-0.17.tar.gz"
sha256 "47bd111e474566d733c41870e2374c81689db5e0b5a43adc48adb665d89fb067"
end
resource "IPC::Run3" do
url "https://cpan.metacpan.org/authors/id/R/RJ/RJBS/IPC-Run3-0.048.tar.gz"
sha256 "3d81c3cc1b5cff69cca9361e2c6e38df0352251ae7b41e2ff3febc850e463565"
end
resource "Menlo" do
url "https://cpan.metacpan.org/authors/id/M/MI/MIYAGAWA/Menlo-1.9019.tar.gz"
sha256 "3b573f68e7b3a36a87c860be258599330fac248b518854dfb5657ac483dca565"
end
resource "Menlo::Legacy" do
url "https://cpan.metacpan.org/authors/id/M/MI/MIYAGAWA/Menlo-Legacy-1.9022.tar.gz"
sha256 "a6acac3fee318a804b439de54acbc7c27f0b44cfdad8551bbc9cd45986abc201"
end
resource "Module::CPANfile" do
url "https://cpan.metacpan.org/authors/id/M/MI/MIYAGAWA/Module-CPANfile-1.1004.tar.gz"
sha256 "88efbe2e9a642dceaa186430fedfcf999aaf0e06f6cced28a714b8e56b514921"
end
resource "Parallel::Pipes" do
url "https://cpan.metacpan.org/authors/id/S/SK/SKAJI/Parallel-Pipes-0.005.tar.gz"
sha256 "44bd9e2be33d7b314f81c9b886a95d53514689090635f9fad53181f2d3051fd5"
end
resource "Parse::PMFile" do
url "https://cpan.metacpan.org/authors/id/I/IS/ISHIGAKI/Parse-PMFile-0.43.tar.gz"
sha256 "be61e807204738cf0c52ed321551992fdc7fa8faa43ed43ff489d0c269900623"
end
resource "String::ShellQuote" do
url "https://cpan.metacpan.org/authors/id/R/RO/ROSCH/String-ShellQuote-1.04.tar.gz"
sha256 "e606365038ce20d646d255c805effdd32f86475f18d43ca75455b00e4d86dd35"
end
resource "Tie::Handle::Offset" do
url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Tie-Handle-Offset-0.004.tar.gz"
sha256 "ee9f39055dc695aa244a252f56ffd37f8be07209b337ad387824721206d2a89e"
end
resource "URI" do
url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/URI-5.07.tar.gz"
sha256 "eeb6ed2ae212434e2021e29f7556f4024169421a5d8b001a89e65982944131ea"
end
resource "Win32::ShellQuote" do
url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/Win32-ShellQuote-0.003001.tar.gz"
sha256 "aa74b0e3dc2d41cd63f62f853e521ffd76b8d823479a2619e22edb4049b4c0dc"
end
resource "YAML::PP" do
url "https://cpan.metacpan.org/authors/id/T/TI/TINITA/YAML-PP-0.026.tar.gz"
sha256 "4b858e671cf3e966ecc54408e8031740c2f28f87c294ee9679fb02e02d5a45eb"
end
resource "local::lib" do
url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/local-lib-2.000024.tar.gz"
sha256 "2e9b917bd48a0615e42633b2a327494e04610d8f710765b9493d306cead98a05"
end
def install
ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5"
build_pl = [
"Module::Build::Tiny",
"Command::Runner",
"Parallel::Pipes",
]
resources.each do |r|
r.stage do
next if build_pl.include? r.name
system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}"
system "make", "install"
end
end
build_pl.each do |name|
resource(name).stage do
system "perl", "Build.PL", "--install_base", libexec
system "./Build"
system "./Build", "install"
end
end
system "perl", "Build.PL", "--install_base", libexec
system "./Build"
system "./Build", "install"
(bin/"cpm").write_env_script("#{libexec}/bin/cpm", PERL5LIB: ENV["PERL5LIB"])
man1.install_symlink libexec/"man/man1/cpm.1"
man3.install_symlink Dir[libexec/"man/man3/App::cpm*"].reject { |f| File.empty?(f) }
end
test do
system bin/"cpm", "install", "Perl::Tutorial"
expected = <<~EOS
NAME
Perl::Tutorial::HelloWorld - Hello World for Perl
SYNOPSIS
#!/usr/bin/perl
#
# The traditional first program.
# Strict and warnings are recommended.
use strict;
use warnings;
# Print a message.
print "Hello, World!\\n";
EOS
assert_match expected,
shell_output("PERL5LIB=local/lib/perl5 perldoc Perl::Tutorial::HelloWorld")
end
end
| spaam/homebrew-core | Formula/cpm.rb | Ruby | bsd-2-clause | 7,874 |
package tcp
import (
"expvar"
"fmt"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/packetbeat/flows"
"github.com/elastic/beats/packetbeat/protos"
"github.com/tsg/gopacket/layers"
)
const TCP_MAX_DATA_IN_STREAM = 10 * (1 << 20)
const (
TcpDirectionReverse = 0
TcpDirectionOriginal = 1
)
type Tcp struct {
id uint32
streams *common.Cache
portMap map[uint16]protos.Protocol
protocols protos.Protocols
}
type Processor interface {
Process(flow *flows.FlowID, hdr *layers.TCP, pkt *protos.Packet)
}
var (
droppedBecauseOfGaps = expvar.NewInt("tcp.dropped_because_of_gaps")
)
type seqCompare int
const (
seqLT seqCompare = -1
seqEq seqCompare = 0
seqGT seqCompare = 1
)
var (
debugf = logp.MakeDebug("tcp")
isDebug = false
)
func (tcp *Tcp) getId() uint32 {
tcp.id += 1
return tcp.id
}
func (tcp *Tcp) decideProtocol(tuple *common.IpPortTuple) protos.Protocol {
protocol, exists := tcp.portMap[tuple.Src_port]
if exists {
return protocol
}
protocol, exists = tcp.portMap[tuple.Dst_port]
if exists {
return protocol
}
return protos.UnknownProtocol
}
func (tcp *Tcp) findStream(k common.HashableIpPortTuple) *TcpConnection {
v := tcp.streams.Get(k)
if v != nil {
return v.(*TcpConnection)
}
return nil
}
type TcpConnection struct {
id uint32
tuple *common.IpPortTuple
protocol protos.Protocol
tcptuple common.TcpTuple
tcp *Tcp
lastSeq [2]uint32
// protocols private data
data protos.ProtocolData
}
type TcpStream struct {
conn *TcpConnection
dir uint8
}
func (conn *TcpConnection) String() string {
return fmt.Sprintf("TcpStream id[%d] tuple[%s] protocol[%s] lastSeq[%d %d]",
conn.id, conn.tuple, conn.protocol, conn.lastSeq[0], conn.lastSeq[1])
}
func (stream *TcpStream) addPacket(pkt *protos.Packet, tcphdr *layers.TCP) {
conn := stream.conn
mod := conn.tcp.protocols.GetTcp(conn.protocol)
if mod == nil {
if isDebug {
protocol := conn.protocol
debugf("Ignoring protocol for which we have no module loaded: %s",
protocol)
}
return
}
if len(pkt.Payload) > 0 {
conn.data = mod.Parse(pkt, &conn.tcptuple, stream.dir, conn.data)
}
if tcphdr.FIN {
conn.data = mod.ReceivedFin(&conn.tcptuple, stream.dir, conn.data)
}
}
func (stream *TcpStream) gapInStream(nbytes int) (drop bool) {
conn := stream.conn
mod := conn.tcp.protocols.GetTcp(conn.protocol)
conn.data, drop = mod.GapInStream(&conn.tcptuple, stream.dir, nbytes, conn.data)
return drop
}
func (tcp *Tcp) Process(id *flows.FlowID, tcphdr *layers.TCP, pkt *protos.Packet) {
// This Recover should catch all exceptions in
// protocol modules.
defer logp.Recover("Process tcp exception")
stream, created := tcp.getStream(pkt)
if stream.conn == nil {
return
}
conn := stream.conn
if id != nil {
id.AddConnectionID(uint64(conn.id))
}
if isDebug {
debugf("tcp flow id: %p", id)
}
if len(pkt.Payload) == 0 && !tcphdr.FIN {
// return early if packet is not interesting. Still need to find/create
// stream first in order to update the TCP stream timer
return
}
tcpStartSeq := tcphdr.Seq
tcpSeq := tcpStartSeq + uint32(len(pkt.Payload))
lastSeq := conn.lastSeq[stream.dir]
if isDebug {
debugf("pkt.start_seq=%v pkt.last_seq=%v stream.last_seq=%v (len=%d)",
tcpStartSeq, tcpSeq, lastSeq, len(pkt.Payload))
}
if len(pkt.Payload) > 0 && lastSeq != 0 {
if tcpSeqBeforeEq(tcpSeq, lastSeq) {
if isDebug {
debugf("Ignoring retransmitted segment. pkt.seq=%v len=%v stream.seq=%v",
tcphdr.Seq, len(pkt.Payload), lastSeq)
}
return
}
switch tcpSeqCompare(lastSeq, tcpStartSeq) {
case seqLT: // lastSeq < tcpStartSeq => Gap in tcp stream detected
if created {
break
}
gap := int(tcpStartSeq - lastSeq)
debugf("Gap in tcp stream. last_seq: %d, seq: %d, gap: %d", lastSeq, tcpStartSeq, gap)
drop := stream.gapInStream(gap)
if drop {
if isDebug {
debugf("Dropping connection state because of gap")
}
droppedBecauseOfGaps.Add(1)
// drop application layer connection state and
// update stream_id for app layer analysers using stream_id for lookups
conn.id = tcp.getId()
conn.data = nil
}
case seqGT:
// lastSeq > tcpStartSeq => overlapping TCP segment detected. shrink packet
delta := lastSeq - tcpStartSeq
if isDebug {
debugf("Overlapping tcp segment. last_seq %d, seq: %d, delta: %d",
lastSeq, tcpStartSeq, delta)
}
pkt.Payload = pkt.Payload[delta:]
tcphdr.Seq += delta
}
}
conn.lastSeq[stream.dir] = tcpSeq
stream.addPacket(pkt, tcphdr)
}
func (tcp *Tcp) getStream(pkt *protos.Packet) (stream TcpStream, created bool) {
if conn := tcp.findStream(pkt.Tuple.Hashable()); conn != nil {
return TcpStream{conn: conn, dir: TcpDirectionOriginal}, false
}
if conn := tcp.findStream(pkt.Tuple.RevHashable()); conn != nil {
return TcpStream{conn: conn, dir: TcpDirectionReverse}, false
}
protocol := tcp.decideProtocol(&pkt.Tuple)
if protocol == protos.UnknownProtocol {
// don't follow
return TcpStream{}, false
}
var timeout time.Duration
mod := tcp.protocols.GetTcp(protocol)
if mod != nil {
timeout = mod.ConnectionTimeout()
}
if isDebug {
t := pkt.Tuple
debugf("Connection src[%s:%d] dst[%s:%d] doesn't exist, creating new",
t.Src_ip.String(), t.Src_port,
t.Dst_ip.String(), t.Dst_port)
}
conn := &TcpConnection{
id: tcp.getId(),
tuple: &pkt.Tuple,
protocol: protocol,
tcp: tcp}
conn.tcptuple = common.TcpTupleFromIpPort(conn.tuple, conn.id)
tcp.streams.PutWithTimeout(pkt.Tuple.Hashable(), conn, timeout)
return TcpStream{conn: conn, dir: TcpDirectionOriginal}, true
}
func tcpSeqCompare(seq1, seq2 uint32) seqCompare {
i := int32(seq1 - seq2)
switch {
case i == 0:
return seqEq
case i < 0:
return seqLT
default:
return seqGT
}
}
func tcpSeqBefore(seq1 uint32, seq2 uint32) bool {
return int32(seq1-seq2) < 0
}
func tcpSeqBeforeEq(seq1 uint32, seq2 uint32) bool {
return int32(seq1-seq2) <= 0
}
func buildPortsMap(plugins map[protos.Protocol]protos.TcpPlugin) (map[uint16]protos.Protocol, error) {
var res = map[uint16]protos.Protocol{}
for proto, protoPlugin := range plugins {
for _, port := range protoPlugin.GetPorts() {
old_proto, exists := res[uint16(port)]
if exists {
if old_proto == proto {
continue
}
return nil, fmt.Errorf("Duplicate port (%d) exists in %s and %s protocols",
port, old_proto, proto)
}
res[uint16(port)] = proto
}
}
return res, nil
}
// Creates and returns a new Tcp.
func NewTcp(p protos.Protocols) (*Tcp, error) {
isDebug = logp.IsDebug("tcp")
portMap, err := buildPortsMap(p.GetAllTcp())
if err != nil {
return nil, err
}
tcp := &Tcp{
protocols: p,
portMap: portMap,
streams: common.NewCache(
protos.DefaultTransactionExpiration,
protos.DefaultTransactionHashSize),
}
tcp.streams.StartJanitor(protos.DefaultTransactionExpiration)
if isDebug {
debugf("tcp", "Port map: %v", portMap)
}
return tcp, nil
}
| phenomenes/varnishbeat | vendor/github.com/elastic/beats/packetbeat/protos/tcp/tcp.go | GO | bsd-2-clause | 7,086 |
import batoid
import numpy as np
from test_helpers import timer, do_pickle, all_obj_diff, init_gpu, rays_allclose
@timer
def test_properties():
rng = np.random.default_rng(5)
for i in range(100):
R = rng.normal(0.0, 0.3) # negative allowed
sphere = batoid.Sphere(R)
assert sphere.R == R
do_pickle(sphere)
@timer
def test_sag():
rng = np.random.default_rng(57)
for i in range(100):
R = 1./rng.normal(0.0, 0.3)
sphere = batoid.Sphere(R)
for j in range(10):
x = rng.uniform(-0.7*abs(R), 0.7*abs(R))
y = rng.uniform(-0.7*abs(R), 0.7*abs(R))
result = sphere.sag(x, y)
np.testing.assert_allclose(
result,
R*(1-np.sqrt(1.0-(x*x + y*y)/R/R))
)
# Check that it returned a scalar float and not an array
assert isinstance(result, float)
# Check 0,0
np.testing.assert_allclose(sphere.sag(0, 0), 0.0, rtol=0, atol=1e-17)
# Check vectorization
x = rng.uniform(-0.7*abs(R), 0.7*abs(R), size=(10, 10))
y = rng.uniform(-0.7*abs(R), 0.7*abs(R), size=(10, 10))
np.testing.assert_allclose(
sphere.sag(x, y),
R*(1-np.sqrt(1.0-(x*x + y*y)/R/R))
)
# Make sure non-unit stride arrays also work
np.testing.assert_allclose(
sphere.sag(x[::5,::2], y[::5,::2]),
R*(1-np.sqrt(1.0-(x*x + y*y)/R/R))[::5,::2]
)
do_pickle(sphere)
@timer
def test_normal():
rng = np.random.default_rng(577)
for i in range(100):
R = 1./rng.normal(0.0, 0.3)
sphere = batoid.Sphere(R)
for j in range(10):
x = rng.uniform(-0.7*abs(R), 0.7*abs(R))
y = rng.uniform(-0.7*abs(R), 0.7*abs(R))
result = sphere.normal(x, y)
r = np.hypot(x, y)
rat = r/R
dzdr = rat/np.sqrt(1-rat*rat)
nz = 1/np.sqrt(1+dzdr*dzdr)
normal = np.array([-x/r*dzdr*nz, -y/r*dzdr*nz, nz])
np.testing.assert_allclose(result, normal)
# Check 0,0
np.testing.assert_equal(sphere.normal(0, 0), np.array([0, 0, 1]))
# Check vectorization
x = rng.uniform(-0.7*abs(R), 0.7*abs(R), size=(10, 10))
y = rng.uniform(-0.7*abs(R), 0.7*abs(R), size=(10, 10))
r = np.hypot(x, y)
rat = r/R
dzdr = rat/np.sqrt(1-rat*rat)
nz = 1/np.sqrt(1+dzdr*dzdr)
normal = np.dstack([-x/r*dzdr*nz, -y/r*dzdr*nz, nz])
np.testing.assert_allclose(
sphere.normal(x, y),
normal
)
# Make sure non-unit stride arrays also work
np.testing.assert_allclose(
sphere.normal(x[::5,::2], y[::5,::2]),
normal[::5, ::2]
)
@timer
def test_intersect():
rng = np.random.default_rng(5772)
size = 10_000
for i in range(100):
R = 1./rng.normal(0.0, 0.3)
sphereCoordSys = batoid.CoordSys(origin=[0, 0, -1])
sphere = batoid.Sphere(R)
x = rng.uniform(-0.3*abs(R), 0.3*abs(R), size=size)
y = rng.uniform(-0.3*abs(R), 0.3*abs(R), size=size)
z = np.full_like(x, -2*abs(R))
# If we shoot rays straight up, then it's easy to predict the intersection
vx = np.zeros_like(x)
vy = np.zeros_like(x)
vz = np.ones_like(x)
rv = batoid.RayVector(x, y, z, vx, vy, vz)
np.testing.assert_allclose(rv.z, -2*abs(R))
rv2 = batoid.intersect(sphere, rv.copy(), sphereCoordSys)
assert rv2.coordSys == sphereCoordSys
rv2 = rv2.toCoordSys(batoid.CoordSys())
np.testing.assert_allclose(rv2.x, x)
np.testing.assert_allclose(rv2.y, y)
np.testing.assert_allclose(rv2.z, sphere.sag(x, y)-1, rtol=0, atol=1e-9)
# Check default intersect coordTransform
rv2 = rv.copy().toCoordSys(sphereCoordSys)
batoid.intersect(sphere, rv2)
assert rv2.coordSys == sphereCoordSys
rv2 = rv2.toCoordSys(batoid.CoordSys())
np.testing.assert_allclose(rv2.x, x)
np.testing.assert_allclose(rv2.y, y)
np.testing.assert_allclose(rv2.z, sphere.sag(x, y)-1, rtol=0, atol=1e-9)
@timer
def test_reflect():
rng = np.random.default_rng(57721)
size = 10_000
for i in range(100):
R = 1./rng.normal(0.0, 0.3)
sphere = batoid.Sphere(R)
x = rng.uniform(-0.3*abs(R), 0.3*abs(R), size=size)
y = rng.uniform(-0.3*abs(R), 0.3*abs(R), size=size)
z = np.full_like(x, -2*abs(R))
vx = rng.uniform(-1e-5, 1e-5, size=size)
vy = rng.uniform(-1e-5, 1e-5, size=size)
vz = np.full_like(x, 1)
rv = batoid.RayVector(x, y, z, vx, vy, vz)
rvr = batoid.reflect(sphere, rv.copy())
rvr2 = sphere.reflect(rv.copy())
rays_allclose(rvr, rvr2)
# print(f"{np.sum(rvr.failed)/len(rvr)*100:.2f}% failed")
normal = sphere.normal(rvr.x, rvr.y)
# Test law of reflection
a0 = np.einsum("ad,ad->a", normal, rv.v)[~rvr.failed]
a1 = np.einsum("ad,ad->a", normal, -rvr.v)[~rvr.failed]
np.testing.assert_allclose(
a0, a1,
rtol=0, atol=1e-12
)
# Test that rv.v, rvr.v and normal are all in the same plane
np.testing.assert_allclose(
np.einsum(
"ad,ad->a",
np.cross(normal, rv.v),
rv.v
)[~rvr.failed],
0.0,
rtol=0, atol=1e-12
)
@timer
def test_refract():
rng = np.random.default_rng(577215)
size = 10_000
for i in range(100):
R = 1./rng.normal(0.0, 0.3)
sphere = batoid.Sphere(R)
m0 = batoid.ConstMedium(rng.normal(1.2, 0.01))
m1 = batoid.ConstMedium(rng.normal(1.3, 0.01))
x = rng.uniform(-0.3*abs(R), 0.3*abs(R), size=size)
y = rng.uniform(-0.3*abs(R), 0.3*abs(R), size=size)
z = np.full_like(x, -2*abs(R))
vx = rng.uniform(-1e-5, 1e-5, size=size)
vy = rng.uniform(-1e-5, 1e-5, size=size)
vz = np.sqrt(1-vx*vx-vy*vy)/m0.n
rv = batoid.RayVector(x, y, z, vx, vy, vz)
rvr = batoid.refract(sphere, rv.copy(), m0, m1)
rvr2 = sphere.refract(rv.copy(), m0, m1)
rays_allclose(rvr, rvr2)
# print(f"{np.sum(rvr.failed)/len(rvr)*100:.2f}% failed")
normal = sphere.normal(rvr.x, rvr.y)
# Test Snell's law
s0 = np.sum(np.cross(normal, rv.v*m0.n)[~rvr.failed], axis=-1)
s1 = np.sum(np.cross(normal, rvr.v*m1.n)[~rvr.failed], axis=-1)
np.testing.assert_allclose(
m0.n*s0, m1.n*s1,
rtol=0, atol=1e-9
)
# Test that rv.v, rvr.v and normal are all in the same plane
np.testing.assert_allclose(
np.einsum(
"ad,ad->a",
np.cross(normal, rv.v),
rv.v
)[~rvr.failed],
0.0,
rtol=0, atol=1e-12
)
@timer
def test_ne():
objs = [
batoid.Sphere(1.0),
batoid.Sphere(2.0),
batoid.Plane()
]
all_obj_diff(objs)
@timer
def test_fail():
sphere = batoid.Sphere(1.0)
rv = batoid.RayVector(0, 10, 0, 0, 0, -1) # Too far to side
rv2 = batoid.intersect(sphere, rv.copy())
np.testing.assert_equal(rv2.failed, np.array([True]))
# This one passes
rv = batoid.RayVector(0, 0, 0, 0, 0, -1)
rv2 = batoid.intersect(sphere, rv.copy())
np.testing.assert_equal(rv2.failed, np.array([False]))
if __name__ == '__main__':
test_properties()
test_sag()
test_normal()
test_intersect()
test_reflect()
test_refract()
test_ne()
test_fail()
| jmeyers314/batoid | tests/test_Sphere.py | Python | bsd-2-clause | 7,740 |
/* $Id$ */
#include "platform.h"
#include "di_defs.h"
#include "pc.h"
#include "dqueue.h"
#include "adapter.h"
#include "entity.h"
#include "um_xdi.h"
#include "um_idi.h"
#include "debuglib.h"
#include "divasync.h"
#define DIVAS_MAX_XDI_ADAPTERS 64
/* --------------------------------------------------------------------------
IMPORTS
-------------------------------------------------------------------------- */
extern void diva_os_wakeup_read(void *os_context);
extern void diva_os_wakeup_close(void *os_context);
/* --------------------------------------------------------------------------
LOCALS
-------------------------------------------------------------------------- */
static LIST_HEAD(adapter_q);
static diva_os_spin_lock_t adapter_lock;
static diva_um_idi_adapter_t *diva_um_idi_find_adapter(dword nr);
static void cleanup_adapter(diva_um_idi_adapter_t *a);
static void cleanup_entity(divas_um_idi_entity_t *e);
static int diva_user_mode_idi_adapter_features(diva_um_idi_adapter_t *a,
diva_um_idi_adapter_features_t
*features);
static int process_idi_request(divas_um_idi_entity_t *e,
const diva_um_idi_req_hdr_t *req);
static int process_idi_rc(divas_um_idi_entity_t *e, byte rc);
static int process_idi_ind(divas_um_idi_entity_t *e, byte ind);
static int write_return_code(divas_um_idi_entity_t *e, byte rc);
/* --------------------------------------------------------------------------
MAIN
-------------------------------------------------------------------------- */
int diva_user_mode_idi_init(void)
{
diva_os_initialize_spin_lock(&adapter_lock, "adapter");
return (0);
}
/* --------------------------------------------------------------------------
Copy adapter features to user supplied buffer
-------------------------------------------------------------------------- */
static int
diva_user_mode_idi_adapter_features(diva_um_idi_adapter_t *a,
diva_um_idi_adapter_features_t *
features)
{
IDI_SYNC_REQ sync_req;
if ((a) && (a->d.request)) {
features->type = a->d.type;
features->features = a->d.features;
features->channels = a->d.channels;
memset(features->name, 0, sizeof(features->name));
sync_req.GetName.Req = 0;
sync_req.GetName.Rc = IDI_SYNC_REQ_GET_NAME;
(*(a->d.request)) ((ENTITY *)&sync_req);
strlcpy(features->name, sync_req.GetName.name,
sizeof(features->name));
sync_req.GetSerial.Req = 0;
sync_req.GetSerial.Rc = IDI_SYNC_REQ_GET_SERIAL;
sync_req.GetSerial.serial = 0;
(*(a->d.request))((ENTITY *)&sync_req);
features->serial_number = sync_req.GetSerial.serial;
}
return ((a) ? 0 : -1);
}
/* --------------------------------------------------------------------------
REMOVE ADAPTER
-------------------------------------------------------------------------- */
void diva_user_mode_idi_remove_adapter(int adapter_nr)
{
struct list_head *tmp;
diva_um_idi_adapter_t *a;
list_for_each(tmp, &adapter_q) {
a = list_entry(tmp, diva_um_idi_adapter_t, link);
if (a->adapter_nr == adapter_nr) {
list_del(tmp);
cleanup_adapter(a);
DBG_LOG(("DIDD: del adapter(%d)", a->adapter_nr));
diva_os_free(0, a);
break;
}
}
}
/* --------------------------------------------------------------------------
CALLED ON DRIVER EXIT (UNLOAD)
-------------------------------------------------------------------------- */
void diva_user_mode_idi_finit(void)
{
struct list_head *tmp, *safe;
diva_um_idi_adapter_t *a;
list_for_each_safe(tmp, safe, &adapter_q) {
a = list_entry(tmp, diva_um_idi_adapter_t, link);
list_del(tmp);
cleanup_adapter(a);
DBG_LOG(("DIDD: del adapter(%d)", a->adapter_nr));
diva_os_free(0, a);
}
diva_os_destroy_spin_lock(&adapter_lock, "adapter");
}
/* -------------------------------------------------------------------------
CREATE AND INIT IDI ADAPTER
------------------------------------------------------------------------- */
int diva_user_mode_idi_create_adapter(const DESCRIPTOR *d, int adapter_nr)
{
diva_os_spin_lock_magic_t old_irql;
diva_um_idi_adapter_t *a =
(diva_um_idi_adapter_t *) diva_os_malloc(0,
sizeof
(diva_um_idi_adapter_t));
if (!a) {
return (-1);
}
memset(a, 0x00, sizeof(*a));
INIT_LIST_HEAD(&a->entity_q);
a->d = *d;
a->adapter_nr = adapter_nr;
DBG_LOG(("DIDD_ADD A(%d), type:%02x, features:%04x, channels:%d",
adapter_nr, a->d.type, a->d.features, a->d.channels));
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "create_adapter");
list_add_tail(&a->link, &adapter_q);
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "create_adapter");
return (0);
}
/* ------------------------------------------------------------------------
Find adapter by Adapter number
------------------------------------------------------------------------ */
static diva_um_idi_adapter_t *diva_um_idi_find_adapter(dword nr)
{
diva_um_idi_adapter_t *a = NULL;
struct list_head *tmp;
list_for_each(tmp, &adapter_q) {
a = list_entry(tmp, diva_um_idi_adapter_t, link);
DBG_TRC(("find_adapter: (%d)-(%d)", nr, a->adapter_nr));
if (a->adapter_nr == (int)nr)
break;
a = NULL;
}
return (a);
}
/* ------------------------------------------------------------------------
Cleanup this adapter and cleanup/delete all entities assigned
to this adapter
------------------------------------------------------------------------ */
static void cleanup_adapter(diva_um_idi_adapter_t *a)
{
struct list_head *tmp, *safe;
divas_um_idi_entity_t *e;
list_for_each_safe(tmp, safe, &a->entity_q) {
e = list_entry(tmp, divas_um_idi_entity_t, link);
list_del(tmp);
cleanup_entity(e);
if (e->os_context) {
diva_os_wakeup_read(e->os_context);
diva_os_wakeup_close(e->os_context);
}
}
memset(&a->d, 0x00, sizeof(DESCRIPTOR));
}
/* ------------------------------------------------------------------------
Cleanup, but NOT delete this entity
------------------------------------------------------------------------ */
static void cleanup_entity(divas_um_idi_entity_t *e)
{
e->os_ref = NULL;
e->status = 0;
e->adapter = NULL;
e->e.Id = 0;
e->rc_count = 0;
e->status |= DIVA_UM_IDI_REMOVED;
e->status |= DIVA_UM_IDI_REMOVE_PENDING;
diva_data_q_finit(&e->data);
diva_data_q_finit(&e->rc);
}
/* ------------------------------------------------------------------------
Create ENTITY, link it to the adapter and remove pointer to entity
------------------------------------------------------------------------ */
void *divas_um_idi_create_entity(dword adapter_nr, void *file)
{
divas_um_idi_entity_t *e;
diva_um_idi_adapter_t *a;
diva_os_spin_lock_magic_t old_irql;
if ((e = (divas_um_idi_entity_t *) diva_os_malloc(0, sizeof(*e)))) {
memset(e, 0x00, sizeof(*e));
if (!
(e->os_context =
diva_os_malloc(0, diva_os_get_context_size()))) {
DBG_LOG(("E(%08x) no memory for os context", e));
diva_os_free(0, e);
return NULL;
}
memset(e->os_context, 0x00, diva_os_get_context_size());
if ((diva_data_q_init(&e->data, 2048 + 512, 16))) {
diva_os_free(0, e->os_context);
diva_os_free(0, e);
return NULL;
}
if ((diva_data_q_init(&e->rc, sizeof(diva_um_idi_ind_hdr_t), 2))) {
diva_data_q_finit(&e->data);
diva_os_free(0, e->os_context);
diva_os_free(0, e);
return NULL;
}
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "create_entity");
/*
Look for Adapter requested
*/
if (!(a = diva_um_idi_find_adapter(adapter_nr))) {
/*
No adapter was found, or this adapter was removed
*/
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "create_entity");
DBG_LOG(("A: no adapter(%ld)", adapter_nr));
cleanup_entity(e);
diva_os_free(0, e->os_context);
diva_os_free(0, e);
return NULL;
}
e->os_ref = file; /* link to os handle */
e->adapter = a; /* link to adapter */
list_add_tail(&e->link, &a->entity_q); /* link from adapter */
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "create_entity");
DBG_LOG(("A(%ld), create E(%08x)", adapter_nr, e));
}
return (e);
}
/* ------------------------------------------------------------------------
Unlink entity and free memory
------------------------------------------------------------------------ */
int divas_um_idi_delete_entity(int adapter_nr, void *entity)
{
divas_um_idi_entity_t *e;
diva_um_idi_adapter_t *a;
diva_os_spin_lock_magic_t old_irql;
if (!(e = (divas_um_idi_entity_t *) entity))
return (-1);
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "delete_entity");
if ((a = e->adapter)) {
list_del(&e->link);
}
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "delete_entity");
diva_um_idi_stop_wdog(entity);
cleanup_entity(e);
diva_os_free(0, e->os_context);
memset(e, 0x00, sizeof(*e));
diva_os_free(0, e);
DBG_LOG(("A(%d) remove E:%08x", adapter_nr, e));
return (0);
}
/* --------------------------------------------------------------------------
Called by application to read data from IDI
-------------------------------------------------------------------------- */
int diva_um_idi_read(void *entity,
void *os_handle,
void *dst,
int max_length, divas_um_idi_copy_to_user_fn_t cp_fn)
{
divas_um_idi_entity_t *e;
diva_um_idi_adapter_t *a;
const void *data;
int length, ret = 0;
diva_um_idi_data_queue_t *q;
diva_os_spin_lock_magic_t old_irql;
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "read");
e = (divas_um_idi_entity_t *) entity;
if (!e || (!(a = e->adapter)) ||
(e->status & DIVA_UM_IDI_REMOVE_PENDING) ||
(e->status & DIVA_UM_IDI_REMOVED) ||
(a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) {
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "read");
DBG_ERR(("E(%08x) read failed - adapter removed", e))
return (-1);
}
DBG_TRC(("A(%d) E(%08x) read(%d)", a->adapter_nr, e, max_length));
/*
Try to read return code first
*/
data = diva_data_q_get_segment4read(&e->rc);
q = &e->rc;
/*
No return codes available, read indications now
*/
if (!data) {
if (!(e->status & DIVA_UM_IDI_RC_PENDING)) {
DBG_TRC(("A(%d) E(%08x) read data", a->adapter_nr, e));
data = diva_data_q_get_segment4read(&e->data);
q = &e->data;
}
} else {
e->status &= ~DIVA_UM_IDI_RC_PENDING;
DBG_TRC(("A(%d) E(%08x) read rc", a->adapter_nr, e));
}
if (data) {
if ((length = diva_data_q_get_segment_length(q)) >
max_length) {
/*
Not enough space to read message
*/
DBG_ERR(("A: A(%d) E(%08x) read small buffer",
a->adapter_nr, e, ret));
diva_os_leave_spin_lock(&adapter_lock, &old_irql,
"read");
return (-2);
}
/*
Copy it to user, this function does access ONLY locked an verified
memory, also we can access it witch spin lock held
*/
if ((ret = (*cp_fn) (os_handle, dst, data, length)) >= 0) {
/*
Acknowledge only if read was successful
*/
diva_data_q_ack_segment4read(q);
}
}
DBG_TRC(("A(%d) E(%08x) read=%d", a->adapter_nr, e, ret));
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "read");
return (ret);
}
int diva_um_idi_write(void *entity,
void *os_handle,
const void *src,
int length, divas_um_idi_copy_from_user_fn_t cp_fn)
{
divas_um_idi_entity_t *e;
diva_um_idi_adapter_t *a;
diva_um_idi_req_hdr_t *req;
void *data;
int ret = 0;
diva_os_spin_lock_magic_t old_irql;
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "write");
e = (divas_um_idi_entity_t *) entity;
if (!e || (!(a = e->adapter)) ||
(e->status & DIVA_UM_IDI_REMOVE_PENDING) ||
(e->status & DIVA_UM_IDI_REMOVED) ||
(a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) {
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
DBG_ERR(("E(%08x) write failed - adapter removed", e))
return (-1);
}
DBG_TRC(("A(%d) E(%08x) write(%d)", a->adapter_nr, e, length));
if ((length < sizeof(*req)) || (length > sizeof(e->buffer))) {
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
return (-2);
}
if (e->status & DIVA_UM_IDI_RC_PENDING) {
DBG_ERR(("A: A(%d) E(%08x) rc pending", a->adapter_nr, e));
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
return (-1); /* should wait for RC code first */
}
/*
Copy function does access only locked verified memory,
also it can be called with spin lock held
*/
if ((ret = (*cp_fn) (os_handle, e->buffer, src, length)) < 0) {
DBG_TRC(("A: A(%d) E(%08x) write error=%d", a->adapter_nr,
e, ret));
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
return (ret);
}
req = (diva_um_idi_req_hdr_t *)&e->buffer[0];
switch (req->type) {
case DIVA_UM_IDI_GET_FEATURES:{
DBG_LOG(("A(%d) get_features", a->adapter_nr));
if (!(data =
diva_data_q_get_segment4write(&e->data))) {
DBG_ERR(("A(%d) get_features, no free buffer",
a->adapter_nr));
diva_os_leave_spin_lock(&adapter_lock,
&old_irql,
"write");
return (0);
}
diva_user_mode_idi_adapter_features(a, &(((diva_um_idi_ind_hdr_t
*) data)->hdr.features));
((diva_um_idi_ind_hdr_t *) data)->type =
DIVA_UM_IDI_IND_FEATURES;
((diva_um_idi_ind_hdr_t *) data)->data_length = 0;
diva_data_q_ack_segment4write(&e->data,
sizeof(diva_um_idi_ind_hdr_t));
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
diva_os_wakeup_read(e->os_context);
}
break;
case DIVA_UM_IDI_REQ:
case DIVA_UM_IDI_REQ_MAN:
case DIVA_UM_IDI_REQ_SIG:
case DIVA_UM_IDI_REQ_NET:
DBG_TRC(("A(%d) REQ(%02d)-(%02d)-(%08x)", a->adapter_nr,
req->Req, req->ReqCh,
req->type & DIVA_UM_IDI_REQ_TYPE_MASK));
switch (process_idi_request(e, req)) {
case -1:
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
return (-1);
case -2:
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
diva_os_wakeup_read(e->os_context);
break;
default:
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
break;
}
break;
default:
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write");
return (-1);
}
DBG_TRC(("A(%d) E(%08x) write=%d", a->adapter_nr, e, ret));
return (ret);
}
/* --------------------------------------------------------------------------
CALLBACK FROM XDI
-------------------------------------------------------------------------- */
static void diva_um_idi_xdi_callback(ENTITY *entity)
{
divas_um_idi_entity_t *e = DIVAS_CONTAINING_RECORD(entity,
divas_um_idi_entity_t,
e);
diva_os_spin_lock_magic_t old_irql;
int call_wakeup = 0;
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "xdi_callback");
if (e->e.complete == 255) {
if (!(e->status & DIVA_UM_IDI_REMOVE_PENDING)) {
diva_um_idi_stop_wdog(e);
}
if ((call_wakeup = process_idi_rc(e, e->e.Rc))) {
if (e->rc_count) {
e->rc_count--;
}
}
e->e.Rc = 0;
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "xdi_callback");
if (call_wakeup) {
diva_os_wakeup_read(e->os_context);
diva_os_wakeup_close(e->os_context);
}
} else {
if (e->status & DIVA_UM_IDI_REMOVE_PENDING) {
e->e.RNum = 0;
e->e.RNR = 2;
} else {
call_wakeup = process_idi_ind(e, e->e.Ind);
}
e->e.Ind = 0;
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "xdi_callback");
if (call_wakeup) {
diva_os_wakeup_read(e->os_context);
}
}
}
static int process_idi_request(divas_um_idi_entity_t *e,
const diva_um_idi_req_hdr_t *req)
{
int assign = 0;
byte Req = (byte) req->Req;
dword type = req->type & DIVA_UM_IDI_REQ_TYPE_MASK;
if (!e->e.Id || !e->e.callback) { /* not assigned */
if (Req != ASSIGN) {
DBG_ERR(("A: A(%d) E(%08x) not assigned",
e->adapter->adapter_nr, e));
return (-1); /* NOT ASSIGNED */
} else {
switch (type) {
case DIVA_UM_IDI_REQ_TYPE_MAN:
e->e.Id = MAN_ID;
DBG_TRC(("A(%d) E(%08x) assign MAN",
e->adapter->adapter_nr, e));
break;
case DIVA_UM_IDI_REQ_TYPE_SIG:
e->e.Id = DSIG_ID;
DBG_TRC(("A(%d) E(%08x) assign SIG",
e->adapter->adapter_nr, e));
break;
case DIVA_UM_IDI_REQ_TYPE_NET:
e->e.Id = NL_ID;
DBG_TRC(("A(%d) E(%08x) assign NET",
e->adapter->adapter_nr, e));
break;
default:
DBG_ERR(("A: A(%d) E(%08x) unknown type=%08x",
e->adapter->adapter_nr, e,
type));
return (-1);
}
}
e->e.XNum = 1;
e->e.RNum = 1;
e->e.callback = diva_um_idi_xdi_callback;
e->e.X = &e->XData;
e->e.R = &e->RData;
assign = 1;
}
e->status |= DIVA_UM_IDI_RC_PENDING;
e->e.Req = Req;
e->e.ReqCh = (byte) req->ReqCh;
e->e.X->PLength = (word) req->data_length;
e->e.X->P = (byte *)&req[1]; /* Our buffer is safe */
DBG_TRC(("A(%d) E(%08x) request(%02x-%02x-%02x (%d))",
e->adapter->adapter_nr, e, e->e.Id, e->e.Req,
e->e.ReqCh, e->e.X->PLength));
e->rc_count++;
if (e->adapter && e->adapter->d.request) {
diva_um_idi_start_wdog(e);
(*(e->adapter->d.request)) (&e->e);
}
if (assign) {
if (e->e.Rc == OUT_OF_RESOURCES) {
/*
XDI has no entities more, call was not forwarded to the card,
no callback will be scheduled
*/
DBG_ERR(("A: A(%d) E(%08x) XDI out of entities",
e->adapter->adapter_nr, e));
e->e.Id = 0;
e->e.ReqCh = 0;
e->e.RcCh = 0;
e->e.Ind = 0;
e->e.IndCh = 0;
e->e.XNum = 0;
e->e.RNum = 0;
e->e.callback = NULL;
e->e.X = NULL;
e->e.R = NULL;
write_return_code(e, ASSIGN_RC | OUT_OF_RESOURCES);
return (-2);
} else {
e->status |= DIVA_UM_IDI_ASSIGN_PENDING;
}
}
return (0);
}
static int process_idi_rc(divas_um_idi_entity_t *e, byte rc)
{
DBG_TRC(("A(%d) E(%08x) rc(%02x-%02x-%02x)",
e->adapter->adapter_nr, e, e->e.Id, rc, e->e.RcCh));
if (e->status & DIVA_UM_IDI_ASSIGN_PENDING) {
e->status &= ~DIVA_UM_IDI_ASSIGN_PENDING;
if (rc != ASSIGN_OK) {
DBG_ERR(("A: A(%d) E(%08x) ASSIGN failed",
e->adapter->adapter_nr, e));
e->e.callback = NULL;
e->e.Id = 0;
e->e.Req = 0;
e->e.ReqCh = 0;
e->e.Rc = 0;
e->e.RcCh = 0;
e->e.Ind = 0;
e->e.IndCh = 0;
e->e.X = NULL;
e->e.R = NULL;
e->e.XNum = 0;
e->e.RNum = 0;
}
}
if ((e->e.Req == REMOVE) && e->e.Id && (rc == 0xff)) {
DBG_ERR(("A: A(%d) E(%08x) discard OK in REMOVE",
e->adapter->adapter_nr, e));
return (0); /* let us do it in the driver */
}
if ((e->e.Req == REMOVE) && (!e->e.Id)) { /* REMOVE COMPLETE */
e->e.callback = NULL;
e->e.Id = 0;
e->e.Req = 0;
e->e.ReqCh = 0;
e->e.Rc = 0;
e->e.RcCh = 0;
e->e.Ind = 0;
e->e.IndCh = 0;
e->e.X = NULL;
e->e.R = NULL;
e->e.XNum = 0;
e->e.RNum = 0;
e->rc_count = 0;
}
if ((e->e.Req == REMOVE) && (rc != 0xff)) { /* REMOVE FAILED */
DBG_ERR(("A: A(%d) E(%08x) REMOVE FAILED",
e->adapter->adapter_nr, e));
}
write_return_code(e, rc);
return (1);
}
static int process_idi_ind(divas_um_idi_entity_t *e, byte ind)
{
int do_wakeup = 0;
if (e->e.complete != 0x02) {
diva_um_idi_ind_hdr_t *pind =
(diva_um_idi_ind_hdr_t *)
diva_data_q_get_segment4write(&e->data);
if (pind) {
e->e.RNum = 1;
e->e.R->P = (byte *)&pind[1];
e->e.R->PLength =
(word) (diva_data_q_get_max_length(&e->data) -
sizeof(*pind));
DBG_TRC(("A(%d) E(%08x) ind_1(%02x-%02x-%02x)-[%d-%d]",
e->adapter->adapter_nr, e, e->e.Id, ind,
e->e.IndCh, e->e.RLength,
e->e.R->PLength));
} else {
DBG_TRC(("A(%d) E(%08x) ind(%02x-%02x-%02x)-RNR",
e->adapter->adapter_nr, e, e->e.Id, ind,
e->e.IndCh));
e->e.RNum = 0;
e->e.RNR = 1;
do_wakeup = 1;
}
} else {
diva_um_idi_ind_hdr_t *pind =
(diva_um_idi_ind_hdr_t *) (e->e.R->P);
DBG_TRC(("A(%d) E(%08x) ind(%02x-%02x-%02x)-[%d]",
e->adapter->adapter_nr, e, e->e.Id, ind,
e->e.IndCh, e->e.R->PLength));
pind--;
pind->type = DIVA_UM_IDI_IND;
pind->hdr.ind.Ind = ind;
pind->hdr.ind.IndCh = e->e.IndCh;
pind->data_length = e->e.R->PLength;
diva_data_q_ack_segment4write(&e->data,
(int) (sizeof(*pind) +
e->e.R->PLength));
do_wakeup = 1;
}
if ((e->status & DIVA_UM_IDI_RC_PENDING) && !e->rc.count) {
do_wakeup = 0;
}
return (do_wakeup);
}
/* --------------------------------------------------------------------------
Write return code to the return code queue of entity
-------------------------------------------------------------------------- */
static int write_return_code(divas_um_idi_entity_t *e, byte rc)
{
diva_um_idi_ind_hdr_t *prc;
if (!(prc =
(diva_um_idi_ind_hdr_t *) diva_data_q_get_segment4write(&e->rc)))
{
DBG_ERR(("A: A(%d) E(%08x) rc(%02x) lost",
e->adapter->adapter_nr, e, rc));
e->status &= ~DIVA_UM_IDI_RC_PENDING;
return (-1);
}
prc->type = DIVA_UM_IDI_IND_RC;
prc->hdr.rc.Rc = rc;
prc->hdr.rc.RcCh = e->e.RcCh;
prc->data_length = 0;
diva_data_q_ack_segment4write(&e->rc, sizeof(*prc));
return (0);
}
/* --------------------------------------------------------------------------
Return amount of entries that can be bead from this entity or
-1 if adapter was removed
-------------------------------------------------------------------------- */
int diva_user_mode_idi_ind_ready(void *entity, void *os_handle)
{
divas_um_idi_entity_t *e;
diva_um_idi_adapter_t *a;
diva_os_spin_lock_magic_t old_irql;
int ret;
if (!entity)
return (-1);
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "ind_ready");
e = (divas_um_idi_entity_t *) entity;
a = e->adapter;
if ((!a) || (a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) {
/*
Adapter was unloaded
*/
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "ind_ready");
return (-1); /* adapter was removed */
}
if (e->status & DIVA_UM_IDI_REMOVED) {
/*
entity was removed as result of adapter removal
user should assign this entity again
*/
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "ind_ready");
return (-1);
}
ret = e->rc.count + e->data.count;
if ((e->status & DIVA_UM_IDI_RC_PENDING) && !e->rc.count) {
ret = 0;
}
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "ind_ready");
return (ret);
}
void *diva_um_id_get_os_context(void *entity)
{
return (((divas_um_idi_entity_t *) entity)->os_context);
}
int divas_um_idi_entity_assigned(void *entity)
{
divas_um_idi_entity_t *e;
diva_um_idi_adapter_t *a;
int ret;
diva_os_spin_lock_magic_t old_irql;
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "assigned?");
e = (divas_um_idi_entity_t *) entity;
if (!e || (!(a = e->adapter)) ||
(e->status & DIVA_UM_IDI_REMOVED) ||
(a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) {
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "assigned?");
return (0);
}
e->status |= DIVA_UM_IDI_REMOVE_PENDING;
ret = (e->e.Id || e->rc_count
|| (e->status & DIVA_UM_IDI_ASSIGN_PENDING));
DBG_TRC(("Id:%02x, rc_count:%d, status:%08x", e->e.Id, e->rc_count,
e->status))
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "assigned?");
return (ret);
}
int divas_um_idi_entity_start_remove(void *entity)
{
divas_um_idi_entity_t *e;
diva_um_idi_adapter_t *a;
diva_os_spin_lock_magic_t old_irql;
diva_os_enter_spin_lock(&adapter_lock, &old_irql, "start_remove");
e = (divas_um_idi_entity_t *) entity;
if (!e || (!(a = e->adapter)) ||
(e->status & DIVA_UM_IDI_REMOVED) ||
(a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) {
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove");
return (0);
}
if (e->rc_count) {
/*
Entity BUSY
*/
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove");
return (1);
}
if (!e->e.Id) {
/*
Remove request was already pending, and arrived now
*/
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove");
return (0); /* REMOVE was pending */
}
/*
Now send remove request
*/
e->e.Req = REMOVE;
e->e.ReqCh = 0;
e->rc_count++;
DBG_TRC(("A(%d) E(%08x) request(%02x-%02x-%02x (%d))",
e->adapter->adapter_nr, e, e->e.Id, e->e.Req,
e->e.ReqCh, e->e.X->PLength));
if (a->d.request)
(*(a->d.request)) (&e->e);
diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove");
return (0);
}
| andrewjylee/omniplay | linux-lts-quantal-3.5.0/drivers/isdn/hardware/eicon/um_idi.c | C | bsd-2-clause | 24,027 |
cask 'mpv' do
version '0.23.0'
sha256 '9c4f5873fc955920c3d570277a2a74f527a9073c27ee1a5eeb3270a1180961e8'
# laboratory.stolendata.net/~djinn/mpv_osx was verified as official when first introduced to the cask
url "https://laboratory.stolendata.net/~djinn/mpv_osx/mpv-#{version}.tar.gz"
appcast 'https://laboratory.stolendata.net/~djinn/mpv_osx/',
checkpoint: '00223d39362fa2d8764dd0e98997c6b412b21e5ec12d6bec2f90ffe7df7a4608'
name 'mpv'
homepage 'https://mpv.io'
app 'mpv.app'
end
| jiashuw/homebrew-cask | Casks/mpv.rb | Ruby | bsd-2-clause | 507 |
---
title: News
---
{% include header.html %}
<div class="hmargin" style="float: right"><a class="groups_link" style="color: #fff"
href="https://groups.google.com/group/capnproto-announce">Stay Updated</a></div>
<h1>News</h1>
{% for post in site.posts %}
<h2><a href="{{ site.baseurl }}.{{ post.url }}">{{ post.title }}</a></h2>
<p class="author">
<a href="https://github.com/{{ post.author }}">{{ post.author }}</a>
{% if post.author == 'kentonv' %}
<span class="gplus-followbutton"><span class="g-follow" data-annotation="none" data-height="15" data-href="//plus.google.com/118187272963262049674" data-rel="author"></span></span>
<a href="https://www.gittip.com/kentonv/"><img class="gittip" src="{{ site.baseurl }}images/gittip.png" alt="Gittip"></a>
{% endif %}
on <span class="date">{{ post.date | date_to_string }}</span>
</p>
{{ post.content }}
{% endfor %}
<script type="text/javascript">setupSidebar()</script>
{% include footer.html %}
| artillery/capnproto | doc/news/index.html | HTML | bsd-2-clause | 963 |
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Soeren Sonnenburg, Heiko Strathmann, Yuyu Zhang, Viktor Gal,
* Thoralf Klein, Fernando Iglesias, Sergey Lisitsyn
*/
#ifndef __STREAMING_ASCIIFILE_H__
#define __STREAMING_ASCIIFILE_H__
#include <shogun/lib/config.h>
#include <shogun/io/streaming/StreamingFile.h>
#include <shogun/lib/v_array.h>
namespace shogun
{
struct substring;
template <class ST> struct SGSparseVectorEntry;
/** @brief Class StreamingAsciiFile to read vector-by-vector from ASCII files.
*
* The object must be initialized like a CSVFile.
*/
class StreamingAsciiFile: public StreamingFile
{
public:
/**
* Default constructor
*
*/
StreamingAsciiFile();
/**
* Constructor taking file name argument
*
* @param fname file name
* @param rw read/write mode
*/
StreamingAsciiFile(const char* fname, char rw='r');
/**
* Destructor
*/
~StreamingAsciiFile() override;
/** set delimiting character
*
* @param delimiter the character used as delimiter
*/
void set_delimiter(char delimiter);
#ifndef SWIG // SWIG should skip this
/**
* Utility function to convert a string to a boolean value
*
* @param str string to convert
*
* @return boolean value
*/
inline bool str_to_bool(char *str)
{
return (atoi(str)!=0);
}
#define GET_VECTOR_DECL(sg_type) \
void get_vector \
(sg_type*& vector, int32_t& len) override; \
\
void get_vector_and_label \
(sg_type*& vector, int32_t& len, float64_t& label) override; \
\
void get_string \
(sg_type*& vector, int32_t& len) override; \
\
void get_string_and_label \
(sg_type*& vector, int32_t& len, float64_t& label) override; \
\
void get_sparse_vector \
(SGSparseVectorEntry<sg_type>*& vector, int32_t& len) override; \
\
void get_sparse_vector_and_label \
(SGSparseVectorEntry<sg_type>*& vector, int32_t& len, float64_t& label) override;
GET_VECTOR_DECL(bool)
GET_VECTOR_DECL(uint8_t)
GET_VECTOR_DECL(char)
GET_VECTOR_DECL(int32_t)
GET_VECTOR_DECL(float32_t)
GET_VECTOR_DECL(float64_t)
GET_VECTOR_DECL(int16_t)
GET_VECTOR_DECL(uint16_t)
GET_VECTOR_DECL(int8_t)
GET_VECTOR_DECL(uint32_t)
GET_VECTOR_DECL(int64_t)
GET_VECTOR_DECL(uint64_t)
GET_VECTOR_DECL(floatmax_t)
#undef GET_VECTOR_DECL
#endif // #ifndef SWIG // SWIG should skip this
/** @return object name */
const char* get_name() const override
{
return "StreamingAsciiFile";
}
private:
/** helper function to read vectors / matrices
*
* @param items dynamic array of values
* @param ptr_data
* @param ptr_item
*/
template <class T> void append_item(std::vector<T>& items, char* ptr_data, char* ptr_item);
/**
* Split a given substring into an array of substrings
* based on a specified delimiter
*
* @param delim delimiter to use
* @param s substring to tokenize
* @param ret array of substrings, returned
*/
void tokenize(char delim, substring s, v_array<substring> &ret);
private:
/// Helper for parsing
v_array<substring> words;
/** delimiter */
char m_delimiter;
};
}
#endif //__STREAMING_ASCIIFILE_H__
| shogun-toolbox/shogun | src/shogun/io/streaming/StreamingAsciiFile.h | C | bsd-3-clause | 3,187 |
#!/bin/bash
exec newrelic-admin run-program python manage.py celeryd --maxtasksperchild=${CELERY_MAX_TASKS_PER_CHILD:-100}
| MikkCZ/kitsune | bin/run-celery-worker.sh | Shell | bsd-3-clause | 124 |
#!/usr/bin/env python3
import sys
import re
import mpmath as mp
mp.dps=250
mp.mp.dps = 250
if len(sys.argv) != 2:
print("Usage: format_CIAAW.py ciaawfile")
quit(1)
path = sys.argv[1]
atomre = re.compile(r'^(\d+) +(\w\w*) +(\w+) +\[?(\d+)\]?\*? +(.*) *$')
isore = re.compile(r'^(\d+)\*? +(\[?\d.*.*\]?) *$')
brange = re.compile(r'^\[([\d\.]+),([\d\.]+)\].*$')
buncertain = re.compile(r'^([\d\.]+)\((\d+)\)[a-z]*$')
bnum = re.compile(r'^([\d\d]+)$')
atommassline = re.compile(r'^(\d+) +(\w\w*) +(\w+) +(.*) *$')
def NumberStr(n):
# Replace spaces
s = n.replace(' ', '')
# remove "exactly" for the carbon mass
s = s.replace('(exactly)', '')
# if only a number, put it three times
m = bnum.match(s)
if m:
s = "{:<25} {:<25} {:<25}".format(m.group(1), m.group(1), m.group(1))
# if parentheses uncertainty...
m = buncertain.match(s)
if m:
# tricky. duplicate the first part as a string
s2 = m.group(1)
# but replace with all zero
s2 = re.sub(r'\d', '0', s2)
# now replace last characters
l = len(m.group(2))
s2 = s2[:len(s2)-l] + m.group(2)
# convert to a float
serr = mp.mpf(s2)
scenter = mp.mpf(m.group(1))
s = "{:<25} {:<25} {:<25}".format(mp.nstr(scenter, 18), mp.nstr(scenter-serr, 18), mp.nstr(scenter+serr, 18))
# Replace bracketed ranges with parentheses
m = brange.match(s)
if m:
slow = mp.mpf(m.group(1))
shigh = mp.mpf(m.group(2))
smid = (shigh + slow)/mp.mpf("2.0")
s = "{:<25} {:<25} {:<25}".format(mp.nstr(smid, 18), mp.nstr(slow, 18), mp.nstr(shigh, 18))
# just a dash?
if s == "-":
s = "{:<25} {:<25} {:<25}".format(0, 0, 0)
return s
# First 5 lines are comments
filelines = [ x.strip() for x in open(path).readlines() ]
curatom = None
for line in filelines:
matomre = atomre.match(line)
misore = isore.match(line)
matommass = atommassline.match(line)
if matomre:
curatom = "{:<5} {:<5}".format(matomre.group(1), matomre.group(2))
print("{} {:<6} {:<25}".format(curatom, matomre.group(4), NumberStr(matomre.group(5))))
elif misore:
print("{} {:<6} {:<25}".format(curatom, misore.group(1), NumberStr(misore.group(2))))
elif matommass:
curatom = "{:<5} {:<5}".format(matommass.group(1), matommass.group(2))
print("{} {:<25}".format(curatom, NumberStr(matommass.group(4))))
else:
print(line) # comment lines, etc
| pulsar-chem/Pulsar-Core | scripts/data/format_CIAAW.py | Python | bsd-3-clause | 2,449 |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_processing/audio_buffer.h"
#include "webrtc/common_audio/include/audio_util.h"
#include "webrtc/common_audio/resampler/push_sinc_resampler.h"
#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
namespace webrtc {
namespace {
enum {
kSamplesPer8kHzChannel = 80,
kSamplesPer16kHzChannel = 160,
kSamplesPer32kHzChannel = 320
};
bool HasKeyboardChannel(AudioProcessing::ChannelLayout layout) {
switch (layout) {
case AudioProcessing::kMono:
case AudioProcessing::kStereo:
return false;
case AudioProcessing::kMonoAndKeyboard:
case AudioProcessing::kStereoAndKeyboard:
return true;
}
assert(false);
return false;
}
int KeyboardChannelIndex(AudioProcessing::ChannelLayout layout) {
switch (layout) {
case AudioProcessing::kMono:
case AudioProcessing::kStereo:
assert(false);
return -1;
case AudioProcessing::kMonoAndKeyboard:
return 1;
case AudioProcessing::kStereoAndKeyboard:
return 2;
}
assert(false);
return -1;
}
void StereoToMono(const float* left, const float* right, float* out,
int samples_per_channel) {
for (int i = 0; i < samples_per_channel; ++i) {
out[i] = (left[i] + right[i]) / 2;
}
}
void StereoToMono(const int16_t* left, const int16_t* right, int16_t* out,
int samples_per_channel) {
for (int i = 0; i < samples_per_channel; ++i) {
out[i] = (left[i] + right[i]) >> 1;
}
}
} // namespace
// One int16_t and one float ChannelBuffer that are kept in sync. The sync is
// broken when someone requests write access to either ChannelBuffer, and
// reestablished when someone requests the outdated ChannelBuffer. It is
// therefore safe to use the return value of ibuf_const() and fbuf_const()
// until the next call to ibuf() or fbuf(), and the return value of ibuf() and
// fbuf() until the next call to any of the other functions.
class IFChannelBuffer {
public:
IFChannelBuffer(int samples_per_channel, int num_channels)
: ivalid_(true),
ibuf_(samples_per_channel, num_channels),
fvalid_(true),
fbuf_(samples_per_channel, num_channels) {}
ChannelBuffer<int16_t>* ibuf() { return ibuf(false); }
ChannelBuffer<float>* fbuf() { return fbuf(false); }
const ChannelBuffer<int16_t>* ibuf_const() { return ibuf(true); }
const ChannelBuffer<float>* fbuf_const() { return fbuf(true); }
private:
ChannelBuffer<int16_t>* ibuf(bool readonly) {
RefreshI();
fvalid_ = readonly;
return &ibuf_;
}
ChannelBuffer<float>* fbuf(bool readonly) {
RefreshF();
ivalid_ = readonly;
return &fbuf_;
}
void RefreshF() {
if (!fvalid_) {
assert(ivalid_);
const int16_t* const int_data = ibuf_.data();
float* const float_data = fbuf_.data();
const int length = fbuf_.length();
for (int i = 0; i < length; ++i)
float_data[i] = int_data[i];
fvalid_ = true;
}
}
void RefreshI() {
if (!ivalid_) {
assert(fvalid_);
const float* const float_data = fbuf_.data();
int16_t* const int_data = ibuf_.data();
const int length = ibuf_.length();
for (int i = 0; i < length; ++i)
int_data[i] = WEBRTC_SPL_SAT(std::numeric_limits<int16_t>::max(),
float_data[i],
std::numeric_limits<int16_t>::min());
ivalid_ = true;
}
}
bool ivalid_;
ChannelBuffer<int16_t> ibuf_;
bool fvalid_;
ChannelBuffer<float> fbuf_;
};
AudioBuffer::AudioBuffer(int input_samples_per_channel,
int num_input_channels,
int process_samples_per_channel,
int num_process_channels,
int output_samples_per_channel)
: input_samples_per_channel_(input_samples_per_channel),
num_input_channels_(num_input_channels),
proc_samples_per_channel_(process_samples_per_channel),
num_proc_channels_(num_process_channels),
output_samples_per_channel_(output_samples_per_channel),
samples_per_split_channel_(proc_samples_per_channel_),
mixed_low_pass_valid_(false),
reference_copied_(false),
activity_(AudioFrame::kVadUnknown),
keyboard_data_(NULL),
channels_(new IFChannelBuffer(proc_samples_per_channel_,
num_proc_channels_)) {
assert(input_samples_per_channel_ > 0);
assert(proc_samples_per_channel_ > 0);
assert(output_samples_per_channel_ > 0);
assert(num_input_channels_ > 0 && num_input_channels_ <= 2);
assert(num_proc_channels_ <= num_input_channels);
if (num_input_channels_ == 2 && num_proc_channels_ == 1) {
input_buffer_.reset(new ChannelBuffer<float>(input_samples_per_channel_,
num_proc_channels_));
}
if (input_samples_per_channel_ != proc_samples_per_channel_ ||
output_samples_per_channel_ != proc_samples_per_channel_) {
// Create an intermediate buffer for resampling.
process_buffer_.reset(new ChannelBuffer<float>(proc_samples_per_channel_,
num_proc_channels_));
}
if (input_samples_per_channel_ != proc_samples_per_channel_) {
input_resamplers_.reserve(num_proc_channels_);
for (int i = 0; i < num_proc_channels_; ++i) {
input_resamplers_.push_back(
new PushSincResampler(input_samples_per_channel_,
proc_samples_per_channel_));
}
}
if (output_samples_per_channel_ != proc_samples_per_channel_) {
output_resamplers_.reserve(num_proc_channels_);
for (int i = 0; i < num_proc_channels_; ++i) {
output_resamplers_.push_back(
new PushSincResampler(proc_samples_per_channel_,
output_samples_per_channel_));
}
}
if (proc_samples_per_channel_ == kSamplesPer32kHzChannel) {
samples_per_split_channel_ = kSamplesPer16kHzChannel;
split_channels_low_.reset(new IFChannelBuffer(samples_per_split_channel_,
num_proc_channels_));
split_channels_high_.reset(new IFChannelBuffer(samples_per_split_channel_,
num_proc_channels_));
filter_states_.reset(new SplitFilterStates[num_proc_channels_]);
}
}
AudioBuffer::~AudioBuffer() {}
void AudioBuffer::CopyFrom(const float* const* data,
int samples_per_channel,
AudioProcessing::ChannelLayout layout) {
assert(samples_per_channel == input_samples_per_channel_);
assert(ChannelsFromLayout(layout) == num_input_channels_);
InitForNewData();
if (HasKeyboardChannel(layout)) {
keyboard_data_ = data[KeyboardChannelIndex(layout)];
}
// Downmix.
const float* const* data_ptr = data;
if (num_input_channels_ == 2 && num_proc_channels_ == 1) {
StereoToMono(data[0],
data[1],
input_buffer_->channel(0),
input_samples_per_channel_);
data_ptr = input_buffer_->channels();
}
// Resample.
if (input_samples_per_channel_ != proc_samples_per_channel_) {
for (int i = 0; i < num_proc_channels_; ++i) {
input_resamplers_[i]->Resample(data_ptr[i],
input_samples_per_channel_,
process_buffer_->channel(i),
proc_samples_per_channel_);
}
data_ptr = process_buffer_->channels();
}
// Convert to int16.
for (int i = 0; i < num_proc_channels_; ++i) {
ScaleAndRoundToInt16(data_ptr[i], proc_samples_per_channel_,
channels_->ibuf()->channel(i));
}
}
void AudioBuffer::CopyTo(int samples_per_channel,
AudioProcessing::ChannelLayout layout,
float* const* data) {
assert(samples_per_channel == output_samples_per_channel_);
assert(ChannelsFromLayout(layout) == num_proc_channels_);
// Convert to float.
float* const* data_ptr = data;
if (output_samples_per_channel_ != proc_samples_per_channel_) {
// Convert to an intermediate buffer for subsequent resampling.
data_ptr = process_buffer_->channels();
}
for (int i = 0; i < num_proc_channels_; ++i) {
ScaleToFloat(channels_->ibuf()->channel(i),
proc_samples_per_channel_,
data_ptr[i]);
}
// Resample.
if (output_samples_per_channel_ != proc_samples_per_channel_) {
for (int i = 0; i < num_proc_channels_; ++i) {
output_resamplers_[i]->Resample(data_ptr[i],
proc_samples_per_channel_,
data[i],
output_samples_per_channel_);
}
}
}
void AudioBuffer::InitForNewData() {
keyboard_data_ = NULL;
mixed_low_pass_valid_ = false;
reference_copied_ = false;
activity_ = AudioFrame::kVadUnknown;
}
const int16_t* AudioBuffer::data(int channel) const {
return channels_->ibuf_const()->channel(channel);
}
int16_t* AudioBuffer::data(int channel) {
mixed_low_pass_valid_ = false;
return channels_->ibuf()->channel(channel);
}
const float* AudioBuffer::data_f(int channel) const {
return channels_->fbuf_const()->channel(channel);
}
float* AudioBuffer::data_f(int channel) {
mixed_low_pass_valid_ = false;
return channels_->fbuf()->channel(channel);
}
const int16_t* AudioBuffer::low_pass_split_data(int channel) const {
return split_channels_low_.get()
? split_channels_low_->ibuf_const()->channel(channel)
: data(channel);
}
int16_t* AudioBuffer::low_pass_split_data(int channel) {
mixed_low_pass_valid_ = false;
return split_channels_low_.get()
? split_channels_low_->ibuf()->channel(channel)
: data(channel);
}
const float* AudioBuffer::low_pass_split_data_f(int channel) const {
return split_channels_low_.get()
? split_channels_low_->fbuf_const()->channel(channel)
: data_f(channel);
}
float* AudioBuffer::low_pass_split_data_f(int channel) {
mixed_low_pass_valid_ = false;
return split_channels_low_.get()
? split_channels_low_->fbuf()->channel(channel)
: data_f(channel);
}
const int16_t* AudioBuffer::high_pass_split_data(int channel) const {
return split_channels_high_.get()
? split_channels_high_->ibuf_const()->channel(channel)
: NULL;
}
int16_t* AudioBuffer::high_pass_split_data(int channel) {
return split_channels_high_.get()
? split_channels_high_->ibuf()->channel(channel)
: NULL;
}
const float* AudioBuffer::high_pass_split_data_f(int channel) const {
return split_channels_high_.get()
? split_channels_high_->fbuf_const()->channel(channel)
: NULL;
}
float* AudioBuffer::high_pass_split_data_f(int channel) {
return split_channels_high_.get()
? split_channels_high_->fbuf()->channel(channel)
: NULL;
}
const int16_t* AudioBuffer::mixed_low_pass_data() {
// Currently only mixing stereo to mono is supported.
assert(num_proc_channels_ == 1 || num_proc_channels_ == 2);
if (num_proc_channels_ == 1) {
return low_pass_split_data(0);
}
if (!mixed_low_pass_valid_) {
if (!mixed_low_pass_channels_.get()) {
mixed_low_pass_channels_.reset(
new ChannelBuffer<int16_t>(samples_per_split_channel_, 1));
}
StereoToMono(low_pass_split_data(0),
low_pass_split_data(1),
mixed_low_pass_channels_->data(),
samples_per_split_channel_);
mixed_low_pass_valid_ = true;
}
return mixed_low_pass_channels_->data();
}
const int16_t* AudioBuffer::low_pass_reference(int channel) const {
if (!reference_copied_) {
return NULL;
}
return low_pass_reference_channels_->channel(channel);
}
const float* AudioBuffer::keyboard_data() const {
return keyboard_data_;
}
SplitFilterStates* AudioBuffer::filter_states(int channel) {
assert(channel >= 0 && channel < num_proc_channels_);
return &filter_states_[channel];
}
void AudioBuffer::set_activity(AudioFrame::VADActivity activity) {
activity_ = activity;
}
AudioFrame::VADActivity AudioBuffer::activity() const {
return activity_;
}
int AudioBuffer::num_channels() const {
return num_proc_channels_;
}
int AudioBuffer::samples_per_channel() const {
return proc_samples_per_channel_;
}
int AudioBuffer::samples_per_split_channel() const {
return samples_per_split_channel_;
}
int AudioBuffer::samples_per_keyboard_channel() const {
// We don't resample the keyboard channel.
return input_samples_per_channel_;
}
// TODO(andrew): Do deinterleaving and mixing in one step?
void AudioBuffer::DeinterleaveFrom(AudioFrame* frame) {
assert(proc_samples_per_channel_ == input_samples_per_channel_);
assert(num_proc_channels_ == num_input_channels_);
assert(frame->num_channels_ == num_proc_channels_);
assert(frame->samples_per_channel_ == proc_samples_per_channel_);
InitForNewData();
activity_ = frame->vad_activity_;
int16_t* interleaved = frame->data_;
for (int i = 0; i < num_proc_channels_; i++) {
int16_t* deinterleaved = channels_->ibuf()->channel(i);
int interleaved_idx = i;
for (int j = 0; j < proc_samples_per_channel_; j++) {
deinterleaved[j] = interleaved[interleaved_idx];
interleaved_idx += num_proc_channels_;
}
}
}
void AudioBuffer::InterleaveTo(AudioFrame* frame, bool data_changed) const {
assert(proc_samples_per_channel_ == output_samples_per_channel_);
assert(num_proc_channels_ == num_input_channels_);
assert(frame->num_channels_ == num_proc_channels_);
assert(frame->samples_per_channel_ == proc_samples_per_channel_);
frame->vad_activity_ = activity_;
if (!data_changed) {
return;
}
int16_t* interleaved = frame->data_;
for (int i = 0; i < num_proc_channels_; i++) {
int16_t* deinterleaved = channels_->ibuf()->channel(i);
int interleaved_idx = i;
for (int j = 0; j < proc_samples_per_channel_; j++) {
interleaved[interleaved_idx] = deinterleaved[j];
interleaved_idx += num_proc_channels_;
}
}
}
void AudioBuffer::CopyLowPassToReference() {
reference_copied_ = true;
if (!low_pass_reference_channels_.get()) {
low_pass_reference_channels_.reset(
new ChannelBuffer<int16_t>(samples_per_split_channel_,
num_proc_channels_));
}
for (int i = 0; i < num_proc_channels_; i++) {
low_pass_reference_channels_->CopyFrom(low_pass_split_data(i), i);
}
}
} // namespace webrtc
| xin3liang/platform_external_chromium_org_third_party_webrtc | modules/audio_processing/audio_buffer.cc | C++ | bsd-3-clause | 14,986 |
<?php
namespace common\models;
use common\modules\i18n\Module;
/**
* This is the model class for table "magazine_item".
*
* @property integer $id
* @property integer $magazine_id
* @property string $image
* @property integer $sort
*
* @property Magazine $magazine
*/
class MagazineItem extends Bean
{
/**
* Variable for file storing while data saving
* @var mixed
*/
public $file;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'magazine_item';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['magazine_id', 'image'], 'required'],
[['magazine_id', 'sort'], 'integer'],
[['image'], 'string', 'max' => 255],
[['magazine_id'], 'exist', 'skipOnError' => true, 'targetClass' => Magazine::className(), 'targetAttribute' => ['magazine_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Module::t('Id'),
'magazine_id' => Module::t('Magazine'),
'image' => Module::t('Image'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getMagazine()
{
return $this->hasOne(Magazine::className(), ['id' => 'magazine_id']);
}
}
| artemkramov/jenadin-test | common/models/MagazineItem.php | PHP | bsd-3-clause | 1,379 |
import warnings
import unittest
import sys
from nose.tools import assert_raises
from gplearn.skutils.testing import (
_assert_less,
_assert_greater,
assert_less_equal,
assert_greater_equal,
assert_warns,
assert_no_warnings,
assert_equal,
set_random_state,
assert_raise_message)
from sklearn.tree import DecisionTreeClassifier
from sklearn.lda import LDA
try:
from nose.tools import assert_less
def test_assert_less():
# Check that the nose implementation of assert_less gives the
# same thing as the scikit's
assert_less(0, 1)
_assert_less(0, 1)
assert_raises(AssertionError, assert_less, 1, 0)
assert_raises(AssertionError, _assert_less, 1, 0)
except ImportError:
pass
try:
from nose.tools import assert_greater
def test_assert_greater():
# Check that the nose implementation of assert_less gives the
# same thing as the scikit's
assert_greater(1, 0)
_assert_greater(1, 0)
assert_raises(AssertionError, assert_greater, 0, 1)
assert_raises(AssertionError, _assert_greater, 0, 1)
except ImportError:
pass
def test_assert_less_equal():
assert_less_equal(0, 1)
assert_less_equal(1, 1)
assert_raises(AssertionError, assert_less_equal, 1, 0)
def test_assert_greater_equal():
assert_greater_equal(1, 0)
assert_greater_equal(1, 1)
assert_raises(AssertionError, assert_greater_equal, 0, 1)
def test_set_random_state():
lda = LDA()
tree = DecisionTreeClassifier()
# LDA doesn't have random state: smoke test
set_random_state(lda, 3)
set_random_state(tree, 3)
assert_equal(tree.random_state, 3)
def test_assert_raise_message():
def _raise_ValueError(message):
raise ValueError(message)
assert_raise_message(ValueError, "test",
_raise_ValueError, "test")
assert_raises(AssertionError,
assert_raise_message, ValueError, "something else",
_raise_ValueError, "test")
assert_raises(ValueError,
assert_raise_message, TypeError, "something else",
_raise_ValueError, "test")
# This class is inspired from numpy 1.7 with an alteration to check
# the reset warning filters after calls to assert_warns.
# This assert_warns behavior is specific to scikit-learn because
#`clean_warning_registry()` is called internally by assert_warns
# and clears all previous filters.
class TestWarns(unittest.TestCase):
def test_warn(self):
def f():
warnings.warn("yo")
return 3
# Test that assert_warns is not impacted by externally set
# filters and is reset internally.
# This is because `clean_warning_registry()` is called internally by
# assert_warns and clears all previous filters.
warnings.simplefilter("ignore", UserWarning)
assert_equal(assert_warns(UserWarning, f), 3)
# Test that the warning registry is empty after assert_warns
assert_equal(sys.modules['warnings'].filters, [])
assert_raises(AssertionError, assert_no_warnings, f)
assert_equal(assert_no_warnings(lambda x: x, 1), 1)
def test_warn_wrong_warning(self):
def f():
warnings.warn("yo", DeprecationWarning)
failed = False
filters = sys.modules['warnings'].filters[:]
try:
try:
# Should raise an AssertionError
assert_warns(UserWarning, f)
failed = True
except AssertionError:
pass
finally:
sys.modules['warnings'].filters = filters
if failed:
raise AssertionError("wrong warning caught by assert_warn")
| danbob123/gplearn | gplearn/skutils/tests/test_testing.py | Python | bsd-3-clause | 3,785 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/filters/reference_audio_renderer.h"
#include <math.h>
#include "base/bind.h"
#include "base/synchronization/waitable_event.h"
namespace media {
ReferenceAudioRenderer::ReferenceAudioRenderer(AudioManager* audio_manager)
: AudioRendererBase(),
audio_manager_(audio_manager),
bytes_per_second_(0),
has_buffered_data_(true),
buffer_capacity_(0) {
}
ReferenceAudioRenderer::~ReferenceAudioRenderer() {
// Close down the audio device.
if (controller_) {
base::WaitableEvent closed_event(true, false);
controller_->Close(base::Bind(&base::WaitableEvent::Signal,
base::Unretained(&closed_event)));
closed_event.Wait();
}
}
void ReferenceAudioRenderer::SetPlaybackRate(float rate) {
// TODO(fbarchard): limit rate to reasonable values
AudioRendererBase::SetPlaybackRate(rate);
if (controller_ && rate > 0.0f)
controller_->Play();
}
void ReferenceAudioRenderer::SetVolume(float volume) {
if (controller_)
controller_->SetVolume(volume);
}
void ReferenceAudioRenderer::OnCreated(AudioOutputController* controller) {
NOTIMPLEMENTED();
}
void ReferenceAudioRenderer::OnPlaying(AudioOutputController* controller) {
NOTIMPLEMENTED();
}
void ReferenceAudioRenderer::OnPaused(AudioOutputController* controller) {
NOTIMPLEMENTED();
}
void ReferenceAudioRenderer::OnError(AudioOutputController* controller,
int error_code) {
NOTIMPLEMENTED();
}
void ReferenceAudioRenderer::OnMoreData(AudioOutputController* controller,
AudioBuffersState buffers_state) {
// TODO(fbarchard): Waveout_output_win.h should handle zero length buffers
// without clicking.
uint32 pending_bytes = static_cast<uint32>(ceil(buffers_state.total_bytes() *
GetPlaybackRate()));
base::TimeDelta delay = base::TimeDelta::FromMicroseconds(
base::Time::kMicrosecondsPerSecond * pending_bytes /
bytes_per_second_);
has_buffered_data_ = buffers_state.pending_bytes != 0;
uint32 read = FillBuffer(buffer_.get(), buffer_capacity_, delay);
controller->EnqueueData(buffer_.get(), read);
}
void ReferenceAudioRenderer::OnRenderEndOfStream() {
// We cannot signal end of stream as long as we have buffered data.
// In such case eventually host would playback all the data, and OnMoreData()
// would be called with buffers_state.pending_bytes == 0. At that moment
// we'll call SignalEndOfStream();
if (!has_buffered_data_)
SignalEndOfStream();
}
bool ReferenceAudioRenderer::OnInitialize(int bits_per_channel,
ChannelLayout channel_layout,
int sample_rate) {
int samples_per_packet = sample_rate / 10;
int hardware_buffer_size = samples_per_packet *
ChannelLayoutToChannelCount(channel_layout) * bits_per_channel / 8;
// Allocate audio buffer based on hardware buffer size.
buffer_capacity_ = 3 * hardware_buffer_size;
buffer_.reset(new uint8[buffer_capacity_]);
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, channel_layout,
sample_rate, bits_per_channel, samples_per_packet);
bytes_per_second_ = params.GetBytesPerSecond();
controller_ = AudioOutputController::Create(audio_manager_, this, params,
buffer_capacity_);
return controller_ != NULL;
}
void ReferenceAudioRenderer::OnStop() {
if (controller_)
controller_->Pause();
}
} // namespace media
| aYukiSekiguchi/ACCESS-Chromium | media/filters/reference_audio_renderer.cc | C++ | bsd-3-clause | 3,792 |
<?php
namespace ValuSoTest\TestAsset;
use ValuSo\Annotation;
/**
* @Annotation\Exclude
*/
abstract class AbstractExcludedService
{
public function excluded()
{
return true;
}
} | valu-digital/valuso | tests/ValuSoTest/TestAsset/AbstractExcludedService.php | PHP | bsd-3-clause | 200 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="tr">
<context>
<name>BMMDialog</name>
<message>
<location filename="../BMMDialog.ui" line="14"/>
<source>Manage Bookmarks</source>
<translation>Yer İmlerini Yönet</translation>
</message>
<message>
<location filename="../BMMDialog.ui" line="35"/>
<source>Name</source>
<translation>Ad</translation>
</message>
<message>
<location filename="../BMMDialog.ui" line="40"/>
<source>Path</source>
<translation>Yol</translation>
</message>
<message>
<location filename="../BMMDialog.ui" line="52"/>
<source>Remove Bookmark</source>
<translation>Yer İmini Kaldır</translation>
</message>
<message>
<location filename="../BMMDialog.ui" line="65"/>
<source>Rename BookMark</source>
<translation>Yer İmini Yeniden Adlandır</translation>
</message>
<message>
<location filename="../BMMDialog.ui" line="91"/>
<source>Finished</source>
<translation>Bitti</translation>
</message>
<message>
<location filename="../BMMDialog.cpp" line="58"/>
<source>Rename Bookmark</source>
<translation>Yer İmini Yeniden Adlandır</translation>
</message>
<message>
<location filename="../BMMDialog.cpp" line="58"/>
<source>Name:</source>
<translation>Ad:</translation>
</message>
<message>
<location filename="../BMMDialog.cpp" line="64"/>
<source>Invalid Name</source>
<translation>Geçersiz Ad</translation>
</message>
<message>
<location filename="../BMMDialog.cpp" line="64"/>
<source>This bookmark name already exists. Please choose another.</source>
<translation>Bu yer imi adı zaten mevcut. Lütfen başka bir ad seçin.</translation>
</message>
</context>
<context>
<name>BrowserWidget</name>
<message>
<location filename="../BrowserWidget.cpp" line="257"/>
<source>Name</source>
<translation type="unfinished">Ad</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="258"/>
<source>Size</source>
<translation type="unfinished">Boyut</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="259"/>
<source>Type</source>
<translation type="unfinished">Tür</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="260"/>
<source>Date Modified</source>
<translation type="unfinished">Değiştirilme Tarihi</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="261"/>
<source>Date Created</source>
<translation type="unfinished">Oluşturulma Tarihi</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="438"/>
<source>Capacity: %1</source>
<translation type="unfinished">Kapasite: %1</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="463"/>
<source>Files: %1 (%2)</source>
<translation type="unfinished">Dosyalar: %1 (%2)</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="465"/>
<source>Files: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="471"/>
<source>Dirs: %1</source>
<translation type="unfinished">Dizinler: %1</translation>
</message>
<message>
<location filename="../BrowserWidget.cpp" line="427"/>
<source>No Directory Contents</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DirWidget</name>
<message>
<location filename="../widgets/DirWidget2.ui" line="20"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="41"/>
<source> * - FILE MANAGER RUNNING AS ROOT- * </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="182"/>
<source>Increase Icon Sizes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="204"/>
<source>Decrease Icon Sizes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="228"/>
<source>Back</source>
<translation>Geri</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="231"/>
<location filename="../widgets/DirWidget2.ui" line="234"/>
<source>Go back to previous directory</source>
<translation>Önceki dizine geri git</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="242"/>
<source>Up</source>
<translation>Yukarı</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="245"/>
<location filename="../widgets/DirWidget2.ui" line="248"/>
<source>Go to parent directory</source>
<translation>Üst dizine git</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="256"/>
<source>Home</source>
<translation>Ev</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="259"/>
<location filename="../widgets/DirWidget2.ui" line="262"/>
<source>Go to home directory</source>
<translation>Ev dizinine git</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="267"/>
<source>Menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="270"/>
<source>Select Action</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="278"/>
<source>Single Column</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="281"/>
<source>Single column view</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="289"/>
<source>Dual Column</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.ui" line="292"/>
<source>Dual Column View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="691"/>
<source>(Limited Access) </source>
<translation>(Sınırlı Erişim) </translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="713"/>
<location filename="../widgets/DirWidget2.cpp" line="761"/>
<source>New Document</source>
<translation>Yeni Belge</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="713"/>
<location filename="../widgets/DirWidget2.cpp" line="738"/>
<location filename="../widgets/DirWidget2.cpp" line="761"/>
<source>Name:</source>
<translation>Ad:</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="730"/>
<source>Error Creating Document</source>
<translation>Belge Oluşturmada Hata</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="730"/>
<source>The document could not be created. Please ensure that you have the proper permissions.</source>
<translation>Belge oluşturulamadı. Lütfen uygun izinlere sahip olduğunuza emin olun.</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="738"/>
<source>New Directory</source>
<translation>Yeni Dizin</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="721"/>
<location filename="../widgets/DirWidget2.cpp" line="748"/>
<location filename="../widgets/DirWidget2.cpp" line="770"/>
<source>Invalid Name</source>
<translation>Geçersiz Ad</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="289"/>
<source>Open Current Dir in a Terminal</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="570"/>
<source>File Operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="607"/>
<source>Directory Operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="655"/>
<source>Other...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="663"/>
<source>Loading...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="721"/>
<location filename="../widgets/DirWidget2.cpp" line="748"/>
<location filename="../widgets/DirWidget2.cpp" line="770"/>
<source>A file or directory with that name already exists! Please pick a different name.</source>
<translation>Aynı adda bir dosya ya da dizin zaten mevcut! Lütfen farklı bir ad seçin.</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="752"/>
<source>Error Creating Directory</source>
<translation>Dizin Oluşturmada Hata</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="752"/>
<source>The directory could not be created. Please ensure that you have the proper permissions to modify the current directory.</source>
<translation>Dizin oluşturulamadı. Lütfen geçerli dizinde değişiklik yapmak için uygun izinlere sahip olduğunuza emin olun.</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="384"/>
<source>Current</source>
<translation>Geçerli</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="279"/>
<source>Create...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="281"/>
<source>File</source>
<translation type="unfinished">Dosya</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="282"/>
<source>Directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="283"/>
<source>Application Launcher</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="287"/>
<source>Launch...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="290"/>
<source>SlideShow</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="291"/>
<source>Multimedia Player</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="293"/>
<source>Open Current Dir as Root</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="297"/>
<source>Archive Options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="320"/>
<source>Open with...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="326"/>
<source>View Files...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="328"/>
<source>Checksums</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="330"/>
<source>Properties</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="520"/>
<source>File Checksums:</source>
<translation>Dosya Sağlama Toplamları:</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="532"/>
<source>Missing Utility</source>
<translation>Eksik Gereç</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="532"/>
<source>The "lumina-fileinfo" utility could not be found on the system. Please install it first.</source>
<translation>Sistemde "lumina-fileinfo" gereci bulunamadı. Lütfen önce gereci yükleyin.</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="558"/>
<source>Open</source>
<translation>Aç</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="567"/>
<source>Set as Wallpaper</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="575"/>
<source>Rename...</source>
<translation>Yeniden adlandır...</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="576"/>
<source>Cut Selection</source>
<translation>Seçimi Kes</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="577"/>
<source>Copy Selection</source>
<translation>Seçimi Kopyala</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="580"/>
<source>Paste</source>
<translation>Yapıştır</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="584"/>
<source>Delete Selection</source>
<translation>Seçimi Sil</translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="597"/>
<source>Extract Here</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="599"/>
<source>Archive Selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="907"/>
<source>Select Archive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="921"/>
<source>Set Wallpaper on Screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../widgets/DirWidget2.cpp" line="921"/>
<source>Screen</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FODialog</name>
<message>
<location filename="../FODialog.ui" line="14"/>
<source>Performing File Operations</source>
<translation>Dosya İşlemleri Gerçekleştiriliyor</translation>
</message>
<message>
<location filename="../FODialog.ui" line="39"/>
<source>%v/%m</source>
<translation>%v/%m</translation>
</message>
<message>
<location filename="../FODialog.ui" line="74"/>
<source>Stop</source>
<translation>Dur</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="19"/>
<source>Calculating</source>
<translation>Hesaplanıyor</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="131"/>
<source>Overwrite Files?</source>
<translation>Dosyaların üzerine yazılsın mı?</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="131"/>
<source>Do you want to overwrite the existing files?</source>
<translation>Mevcut dosyaların üzerine yazmak istiyor musunuz?</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="131"/>
<source>Note: It will just add a number to the filename otherwise.</source>
<translation>Not: Aksi durumda dosya adına bir sayı eklenecek.</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="133"/>
<source>YesToAll</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../FODialog.cpp" line="134"/>
<source>NoToAll</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../FODialog.cpp" line="135"/>
<source>Cancel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../FODialog.cpp" line="154"/>
<source>Removing: %1</source>
<translation>Kaldırılıyor: %1</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="155"/>
<source>Copying: %1 to %2</source>
<translation>Kopyalanıyor: %1 %2 hedefine</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="156"/>
<source>Restoring: %1 as %2</source>
<translation>Geri yükleniyor: %1 %2 olarak</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="157"/>
<source>Moving: %1 to %2</source>
<translation>Taşınıyor: %1 %2 hedefine</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="170"/>
<source>Could not remove these files:</source>
<translation>Bu dosyalar kaldırılamadı:</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="171"/>
<source>Could not copy these files:</source>
<translation>Bu dosyalar kopyalanamadı:</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="172"/>
<source>Could not restore these files:</source>
<translation>Bu dosyalar geri yüklenemedi:</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="173"/>
<source>Could not move these files:</source>
<translation>Bu dosyalar taşınamadı:</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="175"/>
<source>File Errors</source>
<translation>Dosya Hataları</translation>
</message>
</context>
<context>
<name>FOWorker</name>
<message>
<location filename="../FODialog.cpp" line="326"/>
<source>Invalid Move</source>
<translation>Geçersiz Taşıma</translation>
</message>
<message>
<location filename="../FODialog.cpp" line="326"/>
<source>It is not possible to move a directory into itself. Please make a copy of the directory instead.
Old Location: %1
New Location: %2</source>
<translation>Bir dizini kendi içine taşımak mümkün değil. Bunun yerine lütfen dizinin bir kopyasını alın.
Eski Konum: %1
Yeni Konum: %2</translation>
</message>
</context>
<context>
<name>GitWizard</name>
<message>
<location filename="../gitWizard.ui" line="14"/>
<source>Clone a Git Repository</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="24"/>
<source>Welcome!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="27"/>
<source>This wizard will guide you through the process of downloading a GIT repository from the internet.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="46"/>
<source>GitHub Repository Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="55"/>
<source>Organization/User</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="65"/>
<source>Repository Name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="75"/>
<source>Is Private Repository</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="89"/>
<source>Type of Access</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="95"/>
<source>Use my SSH Key</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="105"/>
<source>Login to server</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="114"/>
<source>Username</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="124"/>
<source>Password</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="133"/>
<source>Anonymous (public repositories only)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="143"/>
<source>Optional SSH Password</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="153"/>
<source>Advanced Options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="159"/>
<source>Custom Depth</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="166"/>
<source>Single Branch</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="175"/>
<source>branch name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.ui" line="232"/>
<source>Click "Next" to start downloading the repository</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.h" line="58"/>
<source>Stop Download?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../gitWizard.h" line="58"/>
<source>Kill the current download?</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainUI</name>
<message>
<location filename="../MainUI.ui" line="14"/>
<source>Insight</source>
<translation>Görü</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="98"/>
<source>Shift+Left</source>
<translation>Shift+Sol</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="99"/>
<source>Shift+Right</source>
<translation>Shift+Sağ</translation>
</message>
<message>
<location filename="../MainUI.ui" line="142"/>
<source>View Mode</source>
<translation>Görünüm Modu</translation>
</message>
<message>
<location filename="../MainUI.ui" line="184"/>
<source>New Tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="187"/>
<source>New Browser</source>
<translation>Yeni Gözatıcı</translation>
</message>
<message>
<location filename="../MainUI.ui" line="258"/>
<source>Show Image Previews</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="263"/>
<source>Search Directory...</source>
<translation>Dizinde Ara...</translation>
</message>
<message>
<location filename="../MainUI.ui" line="296"/>
<source>Increase Icon Size</source>
<translation>Simge Boyutunu Arttır</translation>
</message>
<message>
<location filename="../MainUI.ui" line="301"/>
<source>Decrease Icon Size</source>
<translation>Simge Boyutunu Azalt</translation>
</message>
<message>
<location filename="../MainUI.ui" line="306"/>
<source>Larger Icons</source>
<translation>Daha Büyük Simgeler</translation>
</message>
<message>
<location filename="../MainUI.ui" line="309"/>
<source>Ctrl++</source>
<translation>Ctrl++</translation>
</message>
<message>
<location filename="../MainUI.ui" line="317"/>
<source>Smaller Icons</source>
<translation>Daha Küçük Simgeler</translation>
</message>
<message>
<location filename="../MainUI.ui" line="320"/>
<source>Ctrl+-</source>
<translation>Ctrl+-</translation>
</message>
<message>
<location filename="../MainUI.ui" line="328"/>
<source>New Window</source>
<translation>Yeni Pencere</translation>
</message>
<message>
<location filename="../MainUI.ui" line="331"/>
<source>Ctrl+N</source>
<translation>Ctrl+N</translation>
</message>
<message>
<location filename="../MainUI.ui" line="339"/>
<source>Add Bookmark</source>
<translation>Yer İmi Ekle</translation>
</message>
<message>
<location filename="../MainUI.ui" line="342"/>
<source>Ctrl+D</source>
<translation>Ctrl+D</translation>
</message>
<message>
<location filename="../MainUI.ui" line="394"/>
<source>Delete Selection</source>
<translation>Seçimi Sil</translation>
</message>
<message>
<location filename="../MainUI.ui" line="397"/>
<source>Del</source>
<translation>Sil</translation>
</message>
<message>
<location filename="../MainUI.ui" line="405"/>
<source>Refresh</source>
<translation>Yenile</translation>
</message>
<message>
<location filename="../MainUI.ui" line="416"/>
<source>Close Tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="427"/>
<source>Repo Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="432"/>
<source>Clone Repository</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="440"/>
<source>Show Directory Tree Window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="443"/>
<source>Show Directory Tree Pane</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="446"/>
<source>Ctrl+P</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="451"/>
<source>Open as Root</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="190"/>
<source>Ctrl+T</source>
<translation>Ctrl+T</translation>
</message>
<message>
<location filename="../MainUI.ui" line="124"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="138"/>
<source>&View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="155"/>
<source>&Bookmarks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="163"/>
<source>&External Devices</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="170"/>
<source>&Git</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.ui" line="198"/>
<source>Exit</source>
<translation>Çık</translation>
</message>
<message>
<location filename="../MainUI.ui" line="201"/>
<source>Ctrl+Q</source>
<translation>Ctrl+Q</translation>
</message>
<message>
<location filename="../MainUI.ui" line="209"/>
<source>&Preferences</source>
<translation>&Tercihler</translation>
</message>
<message>
<location filename="../MainUI.ui" line="220"/>
<source>Show Hidden Files</source>
<translation>Gizli Dosyaları Göster</translation>
</message>
<message>
<location filename="../MainUI.ui" line="225"/>
<source>Scan for Devices</source>
<translation>Aygıtlar için Tara</translation>
</message>
<message>
<location filename="../MainUI.ui" line="233"/>
<source>Manage Bookmarks</source>
<translation>Yer İmlerini Yönet</translation>
</message>
<message>
<location filename="../MainUI.ui" line="247"/>
<source>Show Action Buttons</source>
<translation>Eylem Düğmelerini Göster</translation>
</message>
<message>
<location filename="../MainUI.ui" line="266"/>
<source>Ctrl+F</source>
<translation>Ctrl+F</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="69"/>
<source>Detailed List</source>
<translation>Ayrıntılı Liste</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="70"/>
<source>Basic List</source>
<translation>Temel Liste</translation>
</message>
<message>
<location filename="../MainUI.ui" line="419"/>
<source>Ctrl+W</source>
<translation>Ctrl+W</translation>
</message>
<message>
<location filename="../MainUI.ui" line="408"/>
<source>F5</source>
<translation>F5</translation>
</message>
<message>
<location filename="../MainUI.ui" line="375"/>
<source>Ctrl+C</source>
<translation>Ctrl+C</translation>
</message>
<message>
<location filename="../MainUI.ui" line="350"/>
<source>Rename...</source>
<translation>Yeniden adlandır...</translation>
</message>
<message>
<location filename="../MainUI.ui" line="353"/>
<source>F2</source>
<translation>F2</translation>
</message>
<message>
<location filename="../MainUI.ui" line="361"/>
<source>Cut Selection</source>
<translation>Seçimi Kes</translation>
</message>
<message>
<location filename="../MainUI.ui" line="372"/>
<source>Copy Selection</source>
<translation>Seçimi Kopyala</translation>
</message>
<message>
<location filename="../MainUI.ui" line="383"/>
<source>Paste</source>
<translation>Yapıştır</translation>
</message>
<message>
<location filename="../MainUI.ui" line="386"/>
<source>Ctrl+V</source>
<translation>Ctrl+V</translation>
</message>
<message>
<location filename="../MainUI.ui" line="364"/>
<source>Ctrl+X</source>
<translation>Ctrl+X</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="204"/>
<source>Invalid Directories</source>
<translation>Geçersiz Dizinler</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="204"/>
<source>The following directories are invalid and could not be opened:</source>
<translation>İzleyen dizinler geçersiz ve açılamadı:</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="238"/>
<source>CTRL+B</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="247"/>
<source>CTRL+E</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="365"/>
<source>Root</source>
<translation>Kök</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="372"/>
<source>%1 (Type: %2)</source>
<translation>%1 (Tür: %2)</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="376"/>
<source>Filesystem: %1</source>
<translation>Dosya sistemi: %1</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="612"/>
<source>New Bookmark</source>
<translation>Yeni Yer İmi</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="612"/>
<source>Name:</source>
<translation>Ad:</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="617"/>
<source>Invalid Name</source>
<translation>Geçersiz Ad</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="617"/>
<source>This bookmark name already exists. Please choose another.</source>
<translation>Bu yer imi adı zaten mevcut. Lütfen başka bir ad seçin.</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="638"/>
<source>Git Repository Status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="728"/>
<source>Multimedia</source>
<translation>Multimedya</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="746"/>
<source>Slideshow</source>
<translation>Slayt gösterisi</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="926"/>
<source>Items to be removed:</source>
<translation>Kaldırılacak öğeler:</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="452"/>
<source>Verify Quit</source>
<translation>Çıkışı Doğrula</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="100"/>
<source>Ctrl+H</source>
<translation>Ctrl+H</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="101"/>
<source>Ctrl+L</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainUI.cpp" line="452"/>
<source>You have multiple tabs open. Are you sure you want to quit?</source>
<translation>Açık birden çok sekmeniz mevcut. Çıkmak istediğinize emin misiniz?</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="925"/>
<source>Verify Removal</source>
<translation>Kaldırmayı Doğrula</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="925"/>
<source>WARNING: This will permanently delete the file(s) from the system!</source>
<translation>UYARI: Bu işlemle dosya(lar) sistemden kalıcı olarak silinecek!</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="925"/>
<source>Are you sure you want to continue?</source>
<translation>Devam etmek istediğinize emin misiniz?</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="885"/>
<source>Rename File</source>
<translation>Dosyayı Yeniden Adlandır</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="885"/>
<source>New Name:</source>
<translation>Yeni Ad:</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="899"/>
<source>Overwrite File?</source>
<translation>Dosyanın Üzerine Yazılsın Mı?</translation>
</message>
<message>
<location filename="../MainUI.cpp" line="899"/>
<source>An existing file with the same name will be replaced. Are you sure you want to proceed?</source>
<translation>Aynı ada sahip mevcut bir dosya yenisiyle değiştirilecek. İlerlemek istediğinize emin misiniz?</translation>
</message>
</context>
<context>
<name>MultimediaWidget</name>
<message>
<location filename="../widgets/MultimediaWidget.ui" line="14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../widgets/MultimediaWidget.ui" line="28"/>
<source>Go To Next</source>
<translation>Sonrakine Git</translation>
</message>
<message>
<location filename="../widgets/MultimediaWidget.ui" line="107"/>
<source>(No Running Video)</source>
<translation>(Oynatılan Video Yok)</translation>
</message>
<message>
<location filename="../widgets/MultimediaWidget.cpp" line="124"/>
<source>Playing:</source>
<translation>Oynatılıyor:</translation>
</message>
<message>
<location filename="../widgets/MultimediaWidget.cpp" line="130"/>
<source>Stopped</source>
<translation>Durdu</translation>
</message>
<message>
<location filename="../widgets/MultimediaWidget.cpp" line="157"/>
<source>Error Playing File: %1</source>
<translation>Dosya Oynatmada Hata: %1</translation>
</message>
<message>
<location filename="../widgets/MultimediaWidget.cpp" line="168"/>
<source>Finished</source>
<translation>Tamamlandı</translation>
</message>
</context>
<context>
<name>OPWidget</name>
<message>
<location filename="../OPWidget.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../OPWidget.ui" line="44"/>
<location filename="../OPWidget.ui" line="51"/>
<source>...</source>
<translation type="unfinished">...</translation>
</message>
<message>
<location filename="../OPWidget.ui" line="60"/>
<source>Evaluating...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../OPWidget.cpp" line="52"/>
<source>Move</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../OPWidget.cpp" line="53"/>
<source>Copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../OPWidget.cpp" line="54"/>
<source>Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../OPWidget.cpp" line="96"/>
<source>File Operation Errors</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../OPWidget.cpp" line="108"/>
<source>%1 Finished</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../OPWidget.cpp" line="108"/>
<source>Errors Occured</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SlideshowWidget</name>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="36"/>
<source>Delete this image file</source>
<translation>Bu görüntü dosyasını sil</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="56"/>
<source>Rotate this image file counter-clockwise</source>
<translation>Bu görüntü dosyasını saat yönünün tersinde döndür</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="69"/>
<source>Rotate this image file clockwise</source>
<translation>Bu görüntü dosyasını saat yönünde döndür</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="89"/>
<location filename="../widgets/SlideshowWidget.ui" line="92"/>
<source>Zoom in</source>
<translation>Yakınlaştır</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="105"/>
<location filename="../widgets/SlideshowWidget.ui" line="108"/>
<source>Zoom out</source>
<translation>Uzaklaştır</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="212"/>
<source>Go to Beginning</source>
<translation>Başa Git</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="215"/>
<location filename="../widgets/SlideshowWidget.ui" line="231"/>
<location filename="../widgets/SlideshowWidget.ui" line="304"/>
<location filename="../widgets/SlideshowWidget.ui" line="320"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="218"/>
<source>Shift+Left</source>
<translation>Shift+Sol</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="228"/>
<source>Go to Previous</source>
<translation>Öncekine Git</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="234"/>
<source>Left</source>
<translation>Sol</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="267"/>
<source>File Name</source>
<translation>Dosya Adı</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="301"/>
<source>Go to Next</source>
<translation>Sonrakine Git</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="307"/>
<source>Right</source>
<translation>Sağ</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="317"/>
<source>Go to End</source>
<translation>Sona Git</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.ui" line="323"/>
<source>Shift+Right</source>
<translation>Shift+Sağ</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.cpp" line="125"/>
<source>Verify Removal</source>
<translation>Kaldırmayı Doğrula</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.cpp" line="125"/>
<source>WARNING: This will permanently delete the file from the system!</source>
<translation>UYARI: Bu, dosyayı sistemden kalıcı olarak silecek!</translation>
</message>
<message>
<location filename="../widgets/SlideshowWidget.cpp" line="125"/>
<source>Are you sure you want to continue?</source>
<translation>Devam etmek istediğinize emin misiniz?</translation>
</message>
</context>
<context>
<name>TrayUI</name>
<message>
<location filename="../TrayUI.cpp" line="76"/>
<source>Finished</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../TrayUI.cpp" line="76"/>
<source>Errors during operation. Click to view details</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../TrayUI.cpp" line="91"/>
<source>New Tasks Running</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>XDGDesktopList</name>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="608"/>
<source>Multimedia</source>
<translation type="unfinished">Multimedya</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="609"/>
<source>Development</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="610"/>
<source>Education</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="611"/>
<source>Games</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="612"/>
<source>Graphics</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="613"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="614"/>
<source>Office</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="615"/>
<source>Science</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="616"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="617"/>
<source>System</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/>
<source>Utility</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/>
<source>Wine</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/>
<source>Unsorted</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| cpforbes/lumina | src-qt5/desktop-utils/lumina-fm/i18n/lumina-fm_tr.ts | TypeScript | bsd-3-clause | 49,754 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__wchar_t_alloca_loop_73a.cpp
Label Definition File: CWE124_Buffer_Underwrite.stack.label.xml
Template File: sources-sink-73a.tmpl.cpp
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: loop
* BadSink : Copy string to data using a loop
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#include <wchar.h>
using namespace std;
namespace CWE124_Buffer_Underwrite__wchar_t_alloca_loop_73
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(list<wchar_t *> dataList);
void bad()
{
wchar_t * data;
list<wchar_t *> dataList;
wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
badSink(dataList);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<wchar_t *> dataList);
static void goodG2B()
{
wchar_t * data;
list<wchar_t *> dataList;
wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
goodG2BSink(dataList);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE124_Buffer_Underwrite__wchar_t_alloca_loop_73; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE124_Buffer_Underwrite/s03/CWE124_Buffer_Underwrite__wchar_t_alloca_loop_73a.cpp | C++ | bsd-3-clause | 2,835 |
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import AddComment from './AddComment';
const USER = {
user: {
user: 'RSwanson',
username: 'Ron_Swanson',
imageURL: '',
users: [
{
name: 'April Ludwig',
url: 'aprilL@parksdept.com',
display: 'April',
},
],
},
};
describe('<AddComment>', () => {
it('calls submitComment function', () => {
const submitCommentFn = sinon.spy();
const wrapper = shallow(
<AddComment {...USER} submitComment={submitCommentFn} />,
);
const event = {
preventDefault: sinon.spy(),
};
wrapper.find('button').simulate('onClick', event);
expect(submitCommentFn.calledOnce).toBeTruthy;
});
});
| mathjazz/pontoon | translate/src/core/comments/components/AddComment.test.js | JavaScript | bsd-3-clause | 761 |
/* -- translated by f2c (version 20100827).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
/* Table of constant values */
static doublecomplex c_b1 = {1.,0.};
static blasint c__1 = 1;
/** ZSYTRF_REC2 computes a partial factorization of a complex symmetric matrix using the Bunch-Kaufman diagon al pivoting method.
*
* This routine is a minor modification of LAPACK's zlasyf.
* It serves as an unblocked kernel in the recursive algorithms.
* The blocked BLAS Level 3 updates were removed and moved to the
* recursive algorithm.
* */
/* Subroutine */ void RELAPACK_zsytrf_rec2(char *uplo, blasint *n, blasint *
nb, blasint *kb, doublecomplex *a, blasint *lda, blasint *ipiv,
doublecomplex *w, blasint *ldw, blasint *info, ftnlen uplo_len)
{
/* System generated locals */
blasint a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3, i__4;
double d__1, d__2, d__3, d__4;
doublecomplex z__1, z__2, z__3;
/* Builtin functions */
double sqrt(double), d_imag(doublecomplex *);
void z_div(doublecomplex *, doublecomplex *, doublecomplex *);
/* Local variables */
static blasint j, k;
static doublecomplex t, r1, d11, d21, d22;
static blasint jj, kk, jp, kp, kw, kkw, imax, jmax;
static double alpha;
extern logical lsame_(char *, char *, ftnlen, ftnlen);
extern /* Subroutine */ blasint zscal_(int *, doublecomplex *,
doublecomplex *, blasint *);
static blasint kstep;
extern /* Subroutine */ blasint zgemv_(char *, blasint *, blasint *,
doublecomplex *, doublecomplex *, blasint *, doublecomplex *,
blasint *, doublecomplex *, doublecomplex *, blasint *, ftnlen),
zcopy_(int *, doublecomplex *, blasint *, doublecomplex *,
blasint *), zswap_(int *, doublecomplex *, blasint *,
doublecomplex *, blasint *);
static double absakk, colmax;
extern blasint izamax_(int *, doublecomplex *, blasint *);
static double rowmax;
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--ipiv;
w_dim1 = *ldw;
w_offset = 1 + w_dim1;
w -= w_offset;
/* Function Body */
*info = 0;
alpha = (sqrt(17.) + 1.) / 8.;
if (lsame_(uplo, "U", (ftnlen)1, (ftnlen)1)) {
k = *n;
L10:
kw = *nb + k - *n;
if ((k <= *n - *nb + 1 && *nb < *n) || k < 1) {
goto L30;
}
zcopy_(&k, &a[k * a_dim1 + 1], &c__1, &w[kw * w_dim1 + 1], &c__1);
if (k < *n) {
i__1 = *n - k;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &k, &i__1, &z__1, &a[(k + 1) * a_dim1 + 1],
lda, &w[k + (kw + 1) * w_dim1], ldw, &c_b1, &w[kw *
w_dim1 + 1], &c__1, (ftnlen)12);
}
kstep = 1;
i__1 = k + kw * w_dim1;
absakk = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[k + kw *
w_dim1]), abs(d__2));
if (k > 1) {
i__1 = k - 1;
imax = izamax_(&i__1, &w[kw * w_dim1 + 1], &c__1);
i__1 = imax + kw * w_dim1;
colmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax +
kw * w_dim1]), abs(d__2));
} else {
colmax = 0.;
}
if (max(absakk,colmax) == 0.) {
if (*info == 0) {
*info = k;
}
kp = k;
} else {
if (absakk >= alpha * colmax) {
kp = k;
} else {
zcopy_(&imax, &a[imax * a_dim1 + 1], &c__1, &w[(kw - 1) *
w_dim1 + 1], &c__1);
i__1 = k - imax;
zcopy_(&i__1, &a[imax + (imax + 1) * a_dim1], lda, &w[imax +
1 + (kw - 1) * w_dim1], &c__1);
if (k < *n) {
i__1 = *n - k;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &k, &i__1, &z__1, &a[(k + 1) *
a_dim1 + 1], lda, &w[imax + (kw + 1) * w_dim1],
ldw, &c_b1, &w[(kw - 1) * w_dim1 + 1], &c__1, (
ftnlen)12);
}
i__1 = k - imax;
jmax = imax + izamax_(&i__1, &w[imax + 1 + (kw - 1) * w_dim1],
&c__1);
i__1 = jmax + (kw - 1) * w_dim1;
rowmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[
jmax + (kw - 1) * w_dim1]), abs(d__2));
if (imax > 1) {
i__1 = imax - 1;
jmax = izamax_(&i__1, &w[(kw - 1) * w_dim1 + 1], &c__1);
/* Computing MAX */
i__1 = jmax + (kw - 1) * w_dim1;
d__3 = rowmax, d__4 = (d__1 = w[i__1].r, abs(d__1)) + (
d__2 = d_imag(&w[jmax + (kw - 1) * w_dim1]), abs(
d__2));
rowmax = max(d__3,d__4);
}
if (absakk >= alpha * colmax * (colmax / rowmax)) {
kp = k;
} else /* if(complicated condition) */ {
i__1 = imax + (kw - 1) * w_dim1;
if ((d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[
imax + (kw - 1) * w_dim1]), abs(d__2)) >= alpha *
rowmax) {
kp = imax;
zcopy_(&k, &w[(kw - 1) * w_dim1 + 1], &c__1, &w[kw *
w_dim1 + 1], &c__1);
} else {
kp = imax;
kstep = 2;
}
}
}
kk = k - kstep + 1;
kkw = *nb + kk - *n;
if (kp != kk) {
i__1 = kp + kp * a_dim1;
i__2 = kk + kk * a_dim1;
a[i__1].r = a[i__2].r, a[i__1].i = a[i__2].i;
i__1 = kk - 1 - kp;
zcopy_(&i__1, &a[kp + 1 + kk * a_dim1], &c__1, &a[kp + (kp +
1) * a_dim1], lda);
if (kp > 1) {
i__1 = kp - 1;
zcopy_(&i__1, &a[kk * a_dim1 + 1], &c__1, &a[kp * a_dim1
+ 1], &c__1);
}
if (k < *n) {
i__1 = *n - k;
zswap_(&i__1, &a[kk + (k + 1) * a_dim1], lda, &a[kp + (k
+ 1) * a_dim1], lda);
}
i__1 = *n - kk + 1;
zswap_(&i__1, &w[kk + kkw * w_dim1], ldw, &w[kp + kkw *
w_dim1], ldw);
}
if (kstep == 1) {
zcopy_(&k, &w[kw * w_dim1 + 1], &c__1, &a[k * a_dim1 + 1], &
c__1);
z_div(&z__1, &c_b1, &a[k + k * a_dim1]);
r1.r = z__1.r, r1.i = z__1.i;
i__1 = k - 1;
zscal_(&i__1, &r1, &a[k * a_dim1 + 1], &c__1);
} else {
if (k > 2) {
i__1 = k - 1 + kw * w_dim1;
d21.r = w[i__1].r, d21.i = w[i__1].i;
z_div(&z__1, &w[k + kw * w_dim1], &d21);
d11.r = z__1.r, d11.i = z__1.i;
z_div(&z__1, &w[k - 1 + (kw - 1) * w_dim1], &d21);
d22.r = z__1.r, d22.i = z__1.i;
z__3.r = d11.r * d22.r - d11.i * d22.i, z__3.i = d11.r *
d22.i + d11.i * d22.r;
z__2.r = z__3.r - 1., z__2.i = z__3.i - 0.;
z_div(&z__1, &c_b1, &z__2);
t.r = z__1.r, t.i = z__1.i;
z_div(&z__1, &t, &d21);
d21.r = z__1.r, d21.i = z__1.i;
i__1 = k - 2;
for (j = 1; j <= i__1; ++j) {
i__2 = j + (k - 1) * a_dim1;
i__3 = j + (kw - 1) * w_dim1;
z__3.r = d11.r * w[i__3].r - d11.i * w[i__3].i,
z__3.i = d11.r * w[i__3].i + d11.i * w[i__3]
.r;
i__4 = j + kw * w_dim1;
z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4]
.i;
z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i =
d21.r * z__2.i + d21.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
i__2 = j + k * a_dim1;
i__3 = j + kw * w_dim1;
z__3.r = d22.r * w[i__3].r - d22.i * w[i__3].i,
z__3.i = d22.r * w[i__3].i + d22.i * w[i__3]
.r;
i__4 = j + (kw - 1) * w_dim1;
z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4]
.i;
z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i =
d21.r * z__2.i + d21.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
/* L20: */
}
}
i__1 = k - 1 + (k - 1) * a_dim1;
i__2 = k - 1 + (kw - 1) * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k - 1 + k * a_dim1;
i__2 = k - 1 + kw * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k + k * a_dim1;
i__2 = k + kw * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
}
}
if (kstep == 1) {
ipiv[k] = kp;
} else {
ipiv[k] = -kp;
ipiv[k - 1] = -kp;
}
k -= kstep;
goto L10;
L30:
j = k + 1;
L60:
jj = j;
jp = ipiv[j];
if (jp < 0) {
jp = -jp;
++j;
}
++j;
if (jp != jj && j <= *n) {
i__1 = *n - j + 1;
zswap_(&i__1, &a[jp + j * a_dim1], lda, &a[jj + j * a_dim1], lda);
}
if (j < *n) {
goto L60;
}
*kb = *n - k;
} else {
k = 1;
L70:
if ((k >= *nb && *nb < *n) || k > *n) {
goto L90;
}
i__1 = *n - k + 1;
zcopy_(&i__1, &a[k + k * a_dim1], &c__1, &w[k + k * w_dim1], &c__1);
i__1 = *n - k + 1;
i__2 = k - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__1, &i__2, &z__1, &a[k + a_dim1], lda, &w[k
+ w_dim1], ldw, &c_b1, &w[k + k * w_dim1], &c__1, (ftnlen)12);
kstep = 1;
i__1 = k + k * w_dim1;
absakk = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[k + k *
w_dim1]), abs(d__2));
if (k < *n) {
i__1 = *n - k;
imax = k + izamax_(&i__1, &w[k + 1 + k * w_dim1], &c__1);
i__1 = imax + k * w_dim1;
colmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax +
k * w_dim1]), abs(d__2));
} else {
colmax = 0.;
}
if (max(absakk,colmax) == 0.) {
if (*info == 0) {
*info = k;
}
kp = k;
} else {
if (absakk >= alpha * colmax) {
kp = k;
} else {
i__1 = imax - k;
zcopy_(&i__1, &a[imax + k * a_dim1], lda, &w[k + (k + 1) *
w_dim1], &c__1);
i__1 = *n - imax + 1;
zcopy_(&i__1, &a[imax + imax * a_dim1], &c__1, &w[imax + (k +
1) * w_dim1], &c__1);
i__1 = *n - k + 1;
i__2 = k - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__1, &i__2, &z__1, &a[k + a_dim1],
lda, &w[imax + w_dim1], ldw, &c_b1, &w[k + (k + 1) *
w_dim1], &c__1, (ftnlen)12);
i__1 = imax - k;
jmax = k - 1 + izamax_(&i__1, &w[k + (k + 1) * w_dim1], &c__1)
;
i__1 = jmax + (k + 1) * w_dim1;
rowmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[
jmax + (k + 1) * w_dim1]), abs(d__2));
if (imax < *n) {
i__1 = *n - imax;
jmax = imax + izamax_(&i__1, &w[imax + 1 + (k + 1) *
w_dim1], &c__1);
/* Computing MAX */
i__1 = jmax + (k + 1) * w_dim1;
d__3 = rowmax, d__4 = (d__1 = w[i__1].r, abs(d__1)) + (
d__2 = d_imag(&w[jmax + (k + 1) * w_dim1]), abs(
d__2));
rowmax = max(d__3,d__4);
}
if (absakk >= alpha * colmax * (colmax / rowmax)) {
kp = k;
} else /* if(complicated condition) */ {
i__1 = imax + (k + 1) * w_dim1;
if ((d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[
imax + (k + 1) * w_dim1]), abs(d__2)) >= alpha *
rowmax) {
kp = imax;
i__1 = *n - k + 1;
zcopy_(&i__1, &w[k + (k + 1) * w_dim1], &c__1, &w[k +
k * w_dim1], &c__1);
} else {
kp = imax;
kstep = 2;
}
}
}
kk = k + kstep - 1;
if (kp != kk) {
i__1 = kp + kp * a_dim1;
i__2 = kk + kk * a_dim1;
a[i__1].r = a[i__2].r, a[i__1].i = a[i__2].i;
i__1 = kp - kk - 1;
zcopy_(&i__1, &a[kk + 1 + kk * a_dim1], &c__1, &a[kp + (kk +
1) * a_dim1], lda);
if (kp < *n) {
i__1 = *n - kp;
zcopy_(&i__1, &a[kp + 1 + kk * a_dim1], &c__1, &a[kp + 1
+ kp * a_dim1], &c__1);
}
if (k > 1) {
i__1 = k - 1;
zswap_(&i__1, &a[kk + a_dim1], lda, &a[kp + a_dim1], lda);
}
zswap_(&kk, &w[kk + w_dim1], ldw, &w[kp + w_dim1], ldw);
}
if (kstep == 1) {
i__1 = *n - k + 1;
zcopy_(&i__1, &w[k + k * w_dim1], &c__1, &a[k + k * a_dim1], &
c__1);
if (k < *n) {
z_div(&z__1, &c_b1, &a[k + k * a_dim1]);
r1.r = z__1.r, r1.i = z__1.i;
i__1 = *n - k;
zscal_(&i__1, &r1, &a[k + 1 + k * a_dim1], &c__1);
}
} else {
if (k < *n - 1) {
i__1 = k + 1 + k * w_dim1;
d21.r = w[i__1].r, d21.i = w[i__1].i;
z_div(&z__1, &w[k + 1 + (k + 1) * w_dim1], &d21);
d11.r = z__1.r, d11.i = z__1.i;
z_div(&z__1, &w[k + k * w_dim1], &d21);
d22.r = z__1.r, d22.i = z__1.i;
z__3.r = d11.r * d22.r - d11.i * d22.i, z__3.i = d11.r *
d22.i + d11.i * d22.r;
z__2.r = z__3.r - 1., z__2.i = z__3.i - 0.;
z_div(&z__1, &c_b1, &z__2);
t.r = z__1.r, t.i = z__1.i;
z_div(&z__1, &t, &d21);
d21.r = z__1.r, d21.i = z__1.i;
i__1 = *n;
for (j = k + 2; j <= i__1; ++j) {
i__2 = j + k * a_dim1;
i__3 = j + k * w_dim1;
z__3.r = d11.r * w[i__3].r - d11.i * w[i__3].i,
z__3.i = d11.r * w[i__3].i + d11.i * w[i__3]
.r;
i__4 = j + (k + 1) * w_dim1;
z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4]
.i;
z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i =
d21.r * z__2.i + d21.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
i__2 = j + (k + 1) * a_dim1;
i__3 = j + (k + 1) * w_dim1;
z__3.r = d22.r * w[i__3].r - d22.i * w[i__3].i,
z__3.i = d22.r * w[i__3].i + d22.i * w[i__3]
.r;
i__4 = j + k * w_dim1;
z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4]
.i;
z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i =
d21.r * z__2.i + d21.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
/* L80: */
}
}
i__1 = k + k * a_dim1;
i__2 = k + k * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k + 1 + k * a_dim1;
i__2 = k + 1 + k * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k + 1 + (k + 1) * a_dim1;
i__2 = k + 1 + (k + 1) * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
}
}
if (kstep == 1) {
ipiv[k] = kp;
} else {
ipiv[k] = -kp;
ipiv[k + 1] = -kp;
}
k += kstep;
goto L70;
L90:
j = k - 1;
L120:
jj = j;
jp = ipiv[j];
if (jp < 0) {
jp = -jp;
--j;
}
--j;
if (jp != jj && j >= 1) {
zswap_(&j, &a[jp + a_dim1], lda, &a[jj + a_dim1], lda);
}
if (j > 1) {
goto L120;
}
*kb = k - 1;
}
return;
}
| xianyi/OpenBLAS | relapack/src/zsytrf_rec2.c | C | bsd-3-clause | 13,490 |
--pass out-of-range data of string type to the parameter
--1. [error] out-of-range argument: timestamptz type
select last_day(timestamptz'23:00:00 13/01');
select last_day(timestamptz'04:14:07 1/19/2038');
select last_day(timestamptz'03:15:07 1/19/2038');
select last_day(timestamptz'03:14:08 1/19/2038');
select last_day(timestamptz'03:14:07 2/19/2038');
select last_day(timestamptz'03:14:07 1/20/2038');
select last_day(timestamptz'03:14:07 1/19/2039');
--??
select last_day(timestamptz'03:14:07 PM 1/19/2038');
select last_day(timestamptz'0:0:0 PM 1969-01-01');
select last_day(timestamptz'11:03:22 PM 1864-01-23');
select last_day(timestamptz'2300-12-12 22:02:33');
select last_day(timestamptz'2020-23-11 03:14:66 pm');
select last_day(timestamptz'1970-10-101 0:0');
select last_day(timestamptz'1999/12/11 3:14:7 am');
select last_day(timestamptz'2010-4-31 3:14:7 am');
--2. [error] out-of-range argument: datetimetz type
select last_day(datetimetz'2010-10 10:10:100.00 am');
select last_day(datetimetz'24:59:59.999 12/31/9999');
select last_day(datetimetz'23:60:59.999 12/31/9999');
select last_day(datetimetz'23:59:60.999 12/31/9999');
select last_day(datetimetz'23:59:59.1000 12/31/9999');
select last_day(datetimetz'23:59:59.999 13/31/9999');
select last_day(datetimetz'23:59:59.999 12/32/9999');
select last_day(datetimetz'23:59:59.999 12/31/10000');
select last_day(datetimetz'20:33:61.111 1990-10-19 ');
select last_day(datetimetz'2/31/2022 10:20:30.400');
select last_day(datetimetz'12/31/9999 23:59:59.999');
select last_day(datetimetz'0-12-12 23:59:59.999');
| CUBRID/cubrid-testcases | sql/_27_banana_qa/issue_5765_timezone_support/_00_dev_cases/_02_operator/_31_lastday_with_tz/cases/last_day_007.sql | SQL | bsd-3-clause | 1,603 |
/*************************************************************
* Project: NetCoreCMS *
* Web: http://dotnetcorecms.org *
* Author: OnnoRokom Software Ltd. *
* Website: www.onnorokomsoftware.com *
* Email: info@onnorokomsoftware.com *
* Copyright: OnnoRokom Software Ltd. *
* License: BSD-3-Clause *
*************************************************************/
using NetCoreCMS.Framework.Core.Data;
using NetCoreCMS.Framework.Core.Models;
using NetCoreCMS.Framework.Core.Mvc.Repository;
namespace NetCoreCMS.Framework.Core.Repository
{
public class NccWebSiteRepository : BaseRepository<NccWebSite, long>
{
public NccWebSiteRepository(NccDbContext context) : base(context)
{
}
}
}
| OnnoRokomSoftware/NetCoreCMS | NetCoreCMS.Framework/Core/Repository/NccWebSiteRepository.cs | C# | bsd-3-clause | 926 |
# -*- coding: utf-8 -*-
#
# アルゴリズムデザインコンテストのさまざまな処理
#
# Copyright (C) 2015 Fujitsu
import numberlink
from datastore import *
from hashlib import sha1, sha256
from flask import make_response, render_template
import random
import datetime
from tz import gae_datetime_JST
from define import DEFAULT_YEAR
def adc_response(msg, isjson, code=200, json_encoded=False):
if json_encoded:
body = msg
else:
template = 'response.json' if isjson else 'response.html'
body = render_template(template, msg=msg)
resp = make_response(body)
if code == 200:
resp.status = 'OK'
elif code == 400:
resp.status = 'Bad Request'
elif code == 401:
resp.status = 'Unauthorized'
resp.status_code = code
resp.headers['Content-Type'] = 'application/json' if isjson else 'text/html; charset=utf-8'
return resp
def adc_response_html(html, code=200):
template = 'raw.html'
body = render_template(template, raw=html)
resp = make_response(body)
resp.status_code = code
resp.headers['Content-Type'] = 'text/html; charset=utf-8'
return resp
def adc_response_text(body, code=200):
resp = make_response(body)
resp.status_code = code
resp.headers['Content-Type'] = 'text/plain; charset=utf-8'
return resp
def adc_response_json(body, code=200):
resp = make_response(body)
resp.status_code = code
resp.headers['Content-Type'] = 'application/json'
return resp
def adc_response_Q_data(result):
"問題テキストデータを返す"
if result is None:
code = 404
text = "Not Found\r\n"
else:
code = 200
text = result.text
return adc_response_text(text, code)
def log(username, what):
root = log_key()
i = Log(parent = root,
username = username,
what = what)
i.put()
def log_get_or_delete(username=None, fetch_num=100, when=None, delete=False):
query = Log.query(ancestor = log_key()).order(-Log.date)
if username is not None:
query = query.filter(Log.username == username)
if when is not None:
before = datetime.datetime.now() - when
#print "before=", before
query = query.filter(Log.date > before)
q = query.fetch(fetch_num)
results = []
for i in q:
if delete:
tmp = { 'date': gae_datetime_JST(i.date) }
i.key.delete()
else:
tmp = { 'date': gae_datetime_JST(i.date),
'username': i.username,
'what': i.what }
results.append( tmp )
return results
def adc_login(salt, username, password, users):
"パスワードがあっているかチェックする"
hashed256 = hashed_password(username, password, salt)
u = adc_get_user_info(username, users)
if u is not None and u[1]==hashed256:
return u
else:
return None
def adc_change_password(salt, username, users, attr, priv_admin=False):
"パスワード変更。管理者は他人のパスワードも変更できる。"
if ('password_old' in attr and
'password_new1' in attr and
'password_new2' in attr):
if not priv_admin: # 管理者でないときは、現在のパスワードをチェック
u = adc_login(salt, username, attr['password_old'], users)
if u is None:
return False, "password mismatched"
if attr['password_new1'] != attr['password_new2']:
return False, "new password is not same"
if change_password(username, attr['password_new1'].encode('utf-8'), salt):
return True, "password changed"
else:
return False, "password change failed"
else:
return False, "error"
def adc_get_user_info(username, users):
# まずはローカルに定義されたユーザを検索
for u in users:
if username == (u[0]):
return u
# 次に、データベースに登録されたユーザを検索
r = get_userinfo(username)
if r is not None:
return [r.username, r.password, r.displayname, r.uid, r.gid]
else:
return None
def adc_get_user_list(users):
res = []
# まずはローカルに定義されたユーザを検索
for u in users:
res.append(u[0])
# 次に、データベースに登録されたユーザを検索
res2 = get_username_list()
res.extend(res2)
return res
def insert_Q_data(q_num, text, author="DASymposium", year=DEFAULT_YEAR, uniq=True):
"""
問題データをデータベースに登録する。
uniq==Trueのとき、q_numとauthorが重複する場合、登録は失敗する。
"""
#重複チェック
if uniq:
q = get_user_Q_data(q_num, author, year)
if q is not None:
return (False, "Error: Q%d data already exists" % q_num) # 重複エラー
# 問題データのチェック
(size, line_num, line_mat, msg, ok) = numberlink.read_input_data(text)
if not ok:
return (False, "Error: syntax error in Q data\n"+msg)
# text2は、textを正規化したテキストデータ(改行コードなど)
text2 = numberlink.generate_Q_data(size, line_num, line_mat)
# rootエンティティを決める
userinfo = get_userinfo(author)
if userinfo is None:
return (False, "Error: user not found: %s" % author)
else:
root = userinfo.key
# 問題データのエンティティ
q = Question( parent = root,
id = str(q_num),
qnum = q_num,
text = text2,
rows = size[1], # Y
cols = size[0], # X
linenum = line_num,
author = author )
# 登録する
q.put()
#
return (True, size, line_num)
def update_Q_data(q_num, text, author="DASymposium", year=DEFAULT_YEAR):
"問題データを変更する"
# 問題データの内容チェック
(size, line_num, line_mat, msg, ok) = numberlink.read_input_data(text)
if not ok:
return (False, "Error: syntax error in Q data\n"+msg, None, None)
text2 = numberlink.generate_Q_data(size, line_num, line_mat)
# 既存のエンティティを取り出す
res = get_user_Q_data(q_num, author, year)
if res is None:
num = 0
else:
num = 1
res.text = text2
res.rows = size[1]
res.cols = size[0]
res.linenum = line_num
res.put()
return (True, num, size, line_num)
def get_Q_data(q_num, year=DEFAULT_YEAR, fetch_num=5):
"出題の番号を指定して、Question問題データをデータベースから取り出す"
qla = ndb.Key(QuestionListAll, 'master', parent=qdata_key()).get()
if qla is None:
return None
# q_numは1から始まる整数なので、配列のインデックスとは1だけずれる
qn = q_num-1
if qn < 0 or len(qla.qs) <= qn:
return None
return qla.qs[q_num-1].get()
def get_Q_author_all():
"出題の番号から、authorを引けるテーブルを作る"
qla = ndb.Key(QuestionListAll, 'master', parent=qdata_key()).get()
if qla is None:
return None
authors = ['']*(len(qla.qs)+1) # q_numは1から始まるので、+1しておく
qn = 1 # 出題番号
for q_key in qla.qs:
q = q_key.get()
authors[qn] = q.author
qn += 1
# q.qnum は、問題登録したときの番号であり、出題番号ではない
return authors
def get_Q_data_text(q_num, year=DEFAULT_YEAR, fetch_num=5):
"問題のテキストを返す"
result = get_Q_data(q_num, year, fetch_num)
if result is not None:
text = result.text
ret = True
else: # result is None
text = "Error: data not found: Q%d" % q_num
ret = False
return ret, text
def get_user_Q_data(q_num, author, year=DEFAULT_YEAR, fetch_num=99):
"qnumとauthorを指定して問題データをデータベースから取り出す"
userinfo = get_userinfo(author)
if userinfo is None:
root = qdata_key(year)
else:
root = userinfo.key
key = ndb.Key(Question, str(q_num), parent=root)
return key.get()
def get_admin_Q_all():
"データベースに登録されたすべての問題の一覧リスト"
#query = Question.query().order(Question.author, Question.qnum)
query = Question.query(ancestor=userlist_key()).order(Question.author, Question.qnum)
q = query.fetch()
num = len(q)
out = str(num) + "\n"
for i in q:
dt = gae_datetime_JST(i.date)
out += "Q%02d SIZE %dX%d LINE_NUM %d (%s) %s\n" % (i.qnum, i.cols, i.rows, i.linenum, i.author, dt)
return out
def admin_Q_list_get():
"コンテストの出題リストを取り出す"
qla = ndb.Key(QuestionListAll, 'master', parent=qdata_key()).get()
if qla is None:
return ''
else:
return qla.text_admin
def admin_Q_list_create():
"コンテスト用の出題リストを作成する"
#query = Question.query(ancestor=userlist_key()).order(Question.author, Question.qnum)
query = Question.query(ancestor=userlist_key())
qlist = []
q = query.fetch()
num = len(q)
for i in q:
qlist.append([i.qnum, i.author, i.key])
random.shuffle(qlist)
out = str(num) + "\n"
root = qdata_key()
#既存の問題リストを削除する … のはやめた
#out += admin_Q_list_delete() + "\n"
num = 1
out_admin = ""
out_user = ""
qs = []
for i in qlist:
qs.append(i[2])
out_admin += "Q%d %s %d\n" % (num, i[1], i[0])
out_user += "Q%d\n" % num
num += 1
out += out_admin
qla = QuestionListAll.get_or_insert('master', parent=root, qs=qs, text_admin=out_admin, text_user=out_user)
if qla.text_admin != out_admin:
out += "Already inserted\n"
return out
def admin_Q_list_delete():
"コンテストの出題リストを削除する"
root = qdata_key()
ndb.Key(QuestionListAll, 'master', parent=root).delete()
return "DELETE Q-list"
def get_Q_all(html=False):
"問題データの一覧リストを返す"
qla = ndb.Key(QuestionListAll, 'master', parent=qdata_key()).get()
if qla is None:
return ''
if html:
out = ""
num=1
for i in qla.text_user.splitlines():
out += '<a href="/Q/%d">%s</a><br />\n' % (num, i)
num += 1
return out
else:
return qla.text_user
def menu_post_A(username):
"回答ファイルをアップロードするフォームを返す"
qla = ndb.Key(QuestionListAll, 'master', parent=qdata_key()).get()
if qla is None:
return ''
out = ""
num=1
for i in qla.text_user.splitlines():
out += '<a href="/A/%s/Q/%d">post answer %s</a><br />\n' % (username, num, i)
num += 1
return out
def post_A(username, atext, form):
anum = (int)(form['anum'])
cpu_sec = 0
mem_byte = 0
try:
cpu_sec = (float)(form['cpu_sec'])
mem_byte = (int)(form['mem_byte'])
except ValueError:
# (float)'' がエラー
pass
misc_text = form['misc_text']
print "A%d\n%f\n%d\n%s" % (anum, cpu_sec, mem_byte, misc_text.encode('utf-8'))
return put_A_data(anum, username, atext, cpu_sec, mem_byte, misc_text)
def get_user_Q_all(author, html=None):
"authorを指定して、問題データの一覧リストを返す"
userinfo = get_userinfo(author)
if userinfo is None:
root = qdata_key()
else:
root = userinfo.key
query = Question.query( ancestor = root ).order(Question.qnum)
#query = query.filter(Question.author == author )
q = query.fetch()
num = len(q)
out = ""
for i in q:
if html is None:
out += "Q%d SIZE %dX%d LINE_NUM %d (%s)\n" % (i.qnum, i.cols, i.rows, i.linenum, i.author)
else:
url = '/user/%s/Q/%d' % (author, i.qnum)
out += '<a href="%s">Q%d SIZE %dX%d LINE_NUM %d (%s)</a><br />\n' % (url, i.qnum, i.cols, i.rows, i.linenum, i.author)
return out
def delete_user_Q_data(q_num, author, year=DEFAULT_YEAR):
"qnumとauthorを指定して、問題データをデータベースから削除する"
res = get_user_Q_data(q_num, author, year)
msg = ""
if res is None:
msg = "Q%d data not found" % q_num
else:
msg += "DELETE /user/%s/Q/%d\n" % (author, q_num)
res.key.delete()
return msg
def get_admin_A_all():
"データベースに登録されたすべての回答データの一覧リスト"
#query = Answer.query(ancestor=userlist_key()).order(Answer.owner, Answer.anum)
query = Answer.query(ancestor=userlist_key())
q = query.fetch()
num = len(q)
out = str(num) + "\n"
for i in q:
dt = gae_datetime_JST(i.date)
out += "A%02d (%s) %s\n" % (i.anum, i.owner, dt)
return out
def get_A_data(a_num=None, username=None):
"""
データベースから回答データを取り出す。
a_numがNoneのとき、複数のデータを返す。
a_numが数値のとき、その数値のデータを1つだけ返す。存在しないときはNone。
"""
if username is None:
root = userlist_key()
else:
userinfo = get_userinfo(username)
if userinfo is None:
msg = "ERROR: user not found: %s" % username
return False, msg, None
root = userinfo.key
if a_num is not None:
a = ndb.Key(Answer, str(a_num), parent=root).get()
return True, a, root
#query = Answer.query(ancestor=root).order(Answer.anum)
query = Answer.query(ancestor=root)
#if a_num is not None:
# query = query.filter(Answer.anum == a_num)
q = query.fetch()
return True, q, root
def put_A_data(a_num, username, text, cpu_sec=None, mem_byte=None, misc_text=None):
"回答データをデータベースに格納する"
msg = ""
# 出題データを取り出す
ret, q_text = get_Q_data_text(a_num)
if not ret:
msg = "Error in Q%d data: " % a_num + q_text
return False, msg
# 重複回答していないかチェック
ret, q, root = get_A_data(a_num, username)
if ret==True and q is not None:
msg += "ERROR: duplicated answer\n";
return False, msg
# 回答データのチェックをする
judges, msg = numberlink.check_A_data(text, q_text)
q = 0.0
if judges[0] != True:
msg += "Error in answer A%d\n" % a_num
check_A = False
else:
check_A = True # 正解
q = judges[1]
# 解の品質
msg += "Quality factor = %1.19f\n" % q
# データベースに登録する。不正解でも登録する
a = Answer( parent = root,
id = str(a_num),
anum = a_num,
text = text,
owner = username,
cpu_sec = cpu_sec,
mem_byte = mem_byte,
misc_text = misc_text,
result = msg[-1499:], # 長さ制限がある。末尾のみ保存。
judge = int(check_A),
q_factor = q )
a_key = a.put()
return True, msg
def put_A_info(a_num, username, info):
"回答データの補足情報をデータベースに格納する"
msg = ""
# 回答データを取り出す。rootはUserInfoのkey、aはAnswer
ret, a, root = get_A_data(a_num, username)
if ret==False or a is None:
if ret==False: msg += a + "\n"
msg += "ERROR: A%d data not found" % a_num
return False, msg
a.cpu_sec = info['cpu_sec']
a.mem_byte = info['mem_byte']
a.misc_text = info['misc_text']
a.put()
msg += "UPDATE A%d info\n" % a_num
return True, msg
def get_or_delete_A_data(a_num=None, username=None, delete=False):
"回答データをデータベースから、削除or取り出し"
ret, q, root = get_A_data(a_num=a_num, username=username)
if not ret:
return False, q # q==msg
if q is None:
return ret, []
result = []
if a_num is None: # a_num==Noneのとき、データが複数個になる
q2 = q
else:
q2 = [q]
if delete:
get_or_delete_A_info(a_num=a_num, username=username, delete=True)
for i in q2:
result.append("DELETE A%d" % i.anum)
i.key.delete()
else: # GETの場合
for i in q2:
result.append("GET A%d" % i.anum)
result.append(i.text)
return True, result
def get_user_A_all(username, html=None):
"ユーザーを指定して、回答データの一覧リストを返す"
ret, q, root = get_A_data(username=username)
if not ret:
return False, q
text = ""
for i in q:
if html:
text += '<a href="/A/%s/Q/%d">A%d</a> <a href="/A/%s/Q/%d/info">info</a><br />\n' % (username, i.anum, i.anum, username, i.anum)
else:
text += 'A%d\n' % i.anum
return True, text
def get_or_delete_A_info(a_num=None, username=None, delete=False):
"回答データの補足情報をデータベースから、削除or取り出し"
msg = ""
r, a, root = get_A_data(a_num, username)
if not r:
return False, a, None
if a_num is None:
q = a
else:
if a is None:
msg += "A%d not found" % a_num
return True, msg, []
q = [a]
results = []
num = 0
for i in q:
num += 1
if delete:
results.append({'anum': i.anum})
i.cpu_sec = None
i.mem_byte = None
i.misc_text = None
i.put()
else:
tmp = i.to_dict()
del tmp['text']
results.append( tmp )
method = 'DELETE' if delete else 'GET'
a_num2 = 0 if a_num is None else a_num
msg += "%s A%d info %d" % (method, a_num2, num)
return True, msg, results
def hashed_password(username, password, salt):
"ハッシュ化したパスワード"
tmp = salt + username.encode('utf-8') + password.encode('utf-8')
return sha256(tmp).hexdigest()
def create_user(username, password, displayname, uid, gid, salt):
"ユーザーをデータベースに登録"
hashed = hashed_password(username, password, salt)
userlist = userlist_key()
u = UserInfo( parent = userlist,
id = username,
username = username,
password = hashed,
displayname = displayname,
uid = uid,
gid = gid )
u.put()
def change_password(username, password, salt):
"パスワード変更"
info = get_userinfo(username)
if info is None:
return False
hashed = hashed_password(username, password, salt)
info.password = hashed
info.put()
return True
def get_username_list():
"ユーザー名の一覧リストをデータベースから取り出す"
#query = UserInfo.query( ancestor = userlist_key() ).order(UserInfo.uid)
query = UserInfo.query( ancestor = userlist_key() )
q = query.fetch()
res = []
for u in q:
res.append(u.username)
return res
def get_userinfo(username):
"ユーザー情報をデータベースから取り出す"
key = ndb.Key(UserInfo, username, parent=userlist_key())
info = key.get()
return info
def delete_user(username):
"ユーザーをデータベースから削除"
userinfo = get_userinfo(username)
if userinfo is None:
return 0
else:
userinfo.key.delete()
return 1
return n
def Q_check(qtext):
"問題ファイルの妥当性チェックを行う"
hr = '-'*40 + "\n"
(size, line_num, line_mat, msg, ok) = numberlink.read_input_data(qtext)
if ok:
q = numberlink.generate_Q_data(size, line_num, line_mat)
out = "OK\n" + hr + q + hr
else:
out = "NG\n" + hr + qtext + hr + msg
return out, ok
def calc_score_all():
"スコア計算"
authors = get_Q_author_all()
#print "authors=", authors
q_factors = {}
q_point = {}
ok_point = {}
bonus_point = {}
result = {}
misc = {}
query = Answer.query(ancestor=userlist_key())
q = query.fetch()
all_numbers = {}
all_users = {}
for i in q:
#anum = 'A%d' % i.anum
anum = 'A%02d' % i.anum
username = i.owner
all_numbers[anum] = 1
all_users[username] = 1
# 正解ポイント
if not(anum in ok_point):
ok_point[anum] = {}
ok_point[anum][username] = i.judge
# 品質ポイント
if not(anum in q_factors):
q_factors[anum] = {}
q_factors[anum][username] = i.q_factor
# 出題ボーナスポイント
if i.judge in (0,1) and authors[i.anum] == username:
#print "check_bonus:", i.anum, i.judge, authors[i.anum], username
if not(anum in bonus_point):
bonus_point[anum] = {}
bonus_point[anum][username] = i.judge
# result(ログメッセージ)
if not(anum in result):
result[anum] = {}
result[anum][username] = i.result
# (その他) date, cpu_sec, mem_byte, misc_text
if not(anum in misc):
misc[anum] = {}
misc[anum][username] = [i.date, i.cpu_sec, i.mem_byte, i.misc_text]
#print "ok_point=", ok_point
#print "bonus_point=", bonus_point
#print "q_factors=", q_factors
#print "result=\n", result
# 品質ポイントを計算する
q_pt = 10.0
for anum, values in q_factors.iteritems(): # 問題番号ごとに
#print "anum=", anum
qf_total = 0.0 # Q_factorの合計
for user, qf in values.iteritems():
#print "qf=", qf
qf_total += qf
#print "qf_total=", qf_total
for user, qf in values.iteritems():
if qf_total == 0.0:
tmp = 0.0
else:
tmp = q_pt * qf / qf_total
if not anum in q_point:
q_point[anum] = {}
q_point[anum][user] = tmp
#print "q_point=", q_point
# 集計する
tmp = ['']*(len(all_numbers) + 1)
i = 0
for anum in sorted(all_numbers.keys()):
tmp[i] = anum
i += 1
tmp[i] = 'TOTAL'
score_board = {'/header/': tmp} # 見出しの行
for user in sorted(all_users.keys()):
#print user
if not(user in score_board):
score_board[user] = [0]*(len(all_numbers) + 1)
i = 0
ptotal = 0.0
for anum in sorted(all_numbers.keys()):
#print anum
p = 0.0
if user in ok_point[anum]: p += ok_point[anum][user]
if user in q_point[anum]: p += q_point[anum][user]
if anum in bonus_point and user in bonus_point[anum]:
p += bonus_point[anum][user]
#print "p=", p
score_board[user][i] = p
ptotal += p
i += 1
score_board[user][i] = ptotal
#print "score_board=", score_board
return score_board, ok_point, q_point, bonus_point, q_factors, result, misc
def html_score_board(score_board):
hd_key = '/header/'
out = '<table border=1>\n'
line = '<tr><th>-</th>'
for hd in score_board[hd_key]:
line += '<th>%s</th>' % hd
line += '</tr>\n'
out += line
for user in sorted(score_board.keys()):
if user == hd_key: continue
line = '<tr><th>%s</th>' % user
for val in score_board[user]:
line += '<td>%1.1f</td>' % val
line += '</tr>\n'
out += line
out += '</table>\n'
#print "out=\n", out
return out
| dasadc/conmgr | adc2018/server/adcutil.py | Python | bsd-3-clause | 23,866 |
{% extends "hub/base.html" %}
{% load staticfiles %}
{% block pagetitle %}Users{% endblock %}
{% block content %}
<div class="dashhead">
<div class="dashhead-titles">
<h6 class="dashhead-subtitle">UoP Botswana MoH / TB Training</h6>
<h2 class="dashhead-title">Users</h2>
</div>
</div>
<hr class="m-t">
<div class="flextable">
<form class="form-inline" method="post" action=".">
{% csrf_token %}
<div class="form-group">
<label for="code">Facility Code</label>
{{ form.code }}
<!-- <select class="custom-select form-control" name="address_type" id="address_type">
<option value="msisdn">Cell Phone</option>
</select> -->
</div>
<button type="submit" class="btn btn-default">Search</button>
<b>Results:</b> {{ identities.count }}
</form>
</div>
<div class="table-full">
<div class="table-responsive">
<table class="table" data-sort="table">
<thead>
<tr>
<th>Identity</th>
<th>Created At</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for identity in identities.results %}
<tr>
{% url 'user-detail' identity.id as url %}
<td>{{ identity.id }}</td>
<td>{{ identity.created_at|get_date|date:"D d M Y H:i" }}</td>
<td><a href="{{ url }}">view</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!-- <div class="text-center">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</div> -->
{% endblock %}
| westerncapelabs/uopbmoh-hub | hub/templates/hub/users.html | HTML | bsd-3-clause | 1,920 |
#include "mex.h"
#include <iostream>
#include "drakeMexUtil.h"
#include "RigidBodyManipulator.h"
#include "math.h"
using namespace Eigen;
using namespace std;
/*
* mex interface for bullet collision detection
* closest-distance for each body to all other bodies (~(NB^2-NB)/2 points)
*
* MATLAB signature:
*
* [xA,xB,normal,distance,idxA,idxB] = ...
* collisionDetectmex( mex_model_ptr,allow_multiple_contacts,
* active_collision_options);
*/
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
//check number of arguments
if (nrhs < 3) {
mexErrMsgIdAndTxt("Drake:collisionDetectmex:NotEnoughInputs", "Usage: [xA,xB,normal,distance,idxA,idxB] = collisionDetectmex(mex_model_ptr, allow_multiple_contacts, active_collision_options)");
}
//check argument types
if (!mxIsClass(prhs[0], "DrakeMexPointer")) {
mexErrMsgIdAndTxt("Drake:collisionDetectmex:InvalidInputType", "Expected a DrakeMexPointer for mex_model_ptr but got something else.");
}
if (!mxIsLogical(prhs[1])) {
mexErrMsgIdAndTxt("Drake:collisionDetectmex:InvalidInputType", "Expected a boolean logic type for allow_multiple_collisions but got something else.");
}
if (!mxIsStruct(prhs[2])) {
mexErrMsgIdAndTxt("Drake:collisionDetectmex:InvalidInputType", "Expected a struct type for active_collision_options but got something else.");
}
// first get the model_ptr back from matlab
RigidBodyManipulator *model= (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]);
// Parse `active_collision_options`
vector<int> active_bodies_idx;
set<string> active_group_names;
const mxArray* active_collision_options = prhs[2];
const mxArray* allow_multiple_contacts = prhs[1];
const mxArray* body_idx = mxGetField(active_collision_options, 0, "body_idx");
if (body_idx != NULL) {
size_t n_active_bodies = static_cast<size_t>(mxGetNumberOfElements(body_idx));
active_bodies_idx.resize(n_active_bodies);
memcpy(active_bodies_idx.data(),(int*) mxGetData(body_idx),
sizeof(int)*n_active_bodies);
transform(active_bodies_idx.begin(), active_bodies_idx.end(),
active_bodies_idx.begin(),
[](int i){return --i;});
}
const mxArray* collision_groups = mxGetField(active_collision_options, 0, "collision_groups");
if (collision_groups != NULL) {
size_t num_collision_groups = static_cast<size_t>(mxGetNumberOfElements(collision_groups));
for (size_t i = 0; i < num_collision_groups; i++) {
const mxArray *ptr = mxGetCell(collision_groups, i);
size_t buflen = static_cast<size_t>(mxGetN(ptr) * sizeof(mxChar)) + 1;
char* str = (char*)mxMalloc(buflen);
mxGetString(ptr, str, buflen);
active_group_names.insert(str);
mxFree(str);
}
}
vector<int> bodyA_idx, bodyB_idx;
MatrixXd ptsA, ptsB, normals, JA, JB, Jd;
VectorXd dist;
if (active_bodies_idx.size() > 0) {
if (active_group_names.size() > 0) {
model->collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_bodies_idx,active_group_names);
} else {
model->collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_bodies_idx);
}
} else {
const bool multiple_contacts = mxIsLogicalScalarTrue(allow_multiple_contacts);
if(multiple_contacts) {
model->potentialCollisions(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx);
} else if (active_group_names.size() > 0) {
model->collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx,
active_group_names);
} else {
model->collisionDetect(dist, normals, ptsA, ptsB, bodyA_idx, bodyB_idx);
}
}
vector<int32_T> idxA(bodyA_idx.size());
transform(bodyA_idx.begin(), bodyA_idx.end(), idxA.begin(),
[](int i){return ++i;});
vector<int32_T> idxB(bodyB_idx.size());
transform(bodyB_idx.begin(), bodyB_idx.end(), idxB.begin(),
[](int i){return ++i;});
if (nlhs>0) {
plhs[0] = mxCreateDoubleMatrix(3,static_cast<int>(ptsA.cols()),mxREAL);
memcpy(mxGetPrSafe(plhs[0]),ptsA.data(),sizeof(double)*3*ptsA.cols());
}
if (nlhs>1) {
plhs[1] = mxCreateDoubleMatrix(3,static_cast<int>(ptsB.cols()),mxREAL);
memcpy(mxGetPrSafe(plhs[1]),ptsB.data(),sizeof(double)*3*ptsB.cols());
}
if (nlhs>2) {
plhs[2] = mxCreateDoubleMatrix(3,static_cast<int>(normals.cols()),mxREAL);
memcpy(mxGetPrSafe(plhs[2]),normals.data(),sizeof(double)*3*normals.cols());
}
if (nlhs>3) {
plhs[3] = mxCreateDoubleMatrix(1,static_cast<int>(dist.size()),mxREAL);
memcpy(mxGetPrSafe(plhs[3]),dist.data(),sizeof(double)*dist.size());
}
if (nlhs>4) {
plhs[4] = mxCreateNumericMatrix(1,static_cast<int>(idxA.size()),mxINT32_CLASS,mxREAL);
memcpy(mxGetData(plhs[4]),idxA.data(),sizeof(int32_T)*idxA.size());
}
if (nlhs>5) {
plhs[5] = mxCreateNumericMatrix(1,static_cast<int>(idxB.size()),mxINT32_CLASS,mxREAL);
memcpy(mxGetData(plhs[5]),idxB.data(),sizeof(int32_T)*idxB.size());
}
}
| thientu/drake | systems/plants/collisionDetectmex.cpp | C++ | bsd-3-clause | 5,102 |
#include "MutableValueSetterProxy.h"
#include <jsi/jsi.h>
#include "MutableValue.h"
#include "SharedParent.h"
using namespace facebook;
namespace reanimated {
void MutableValueSetterProxy::set(
jsi::Runtime &rt,
const jsi::PropNameID &name,
const jsi::Value &newValue) {
auto propName = name.utf8(rt);
if (propName == "_value") {
mutableValue->setValue(rt, newValue);
} else if (propName == "_animation") {
// TODO: assert to allow animation to be set from UI only
if (mutableValue->animation.expired()) {
mutableValue->animation = mutableValue->getWeakRef(rt);
}
*mutableValue->animation.lock() = jsi::Value(rt, newValue);
} else if (propName == "value") {
// you call `this.value` inside of value setter, we should throw
}
}
jsi::Value MutableValueSetterProxy::get(
jsi::Runtime &rt,
const jsi::PropNameID &name) {
auto propName = name.utf8(rt);
if (propName == "value") {
return mutableValue->getValue(rt);
} else if (propName == "_value") {
return mutableValue->getValue(rt);
} else if (propName == "_animation") {
if (mutableValue->animation.expired()) {
mutableValue->animation = mutableValue->getWeakRef(rt);
}
return jsi::Value(rt, *mutableValue->animation.lock());
}
return jsi::Value::undefined();
}
} // namespace reanimated
| exponentjs/exponent | ios/vendored/unversioned/react-native-reanimated/Common/cpp/SharedItems/MutableValueSetterProxy.cpp | C++ | bsd-3-clause | 1,341 |
/*
* Copyright (c) 2014, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company 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.
*/
#ifndef TEST_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MOCK_H_
#define TEST_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MOCK_H_
#include <gmock/gmock.h>
#include <string>
#include "transport_manager/transport_manager.h"
#include "transport_manager/transport_adapter/transport_adapter_event.h"
namespace test {
namespace components {
namespace transport_manager_test {
using ::transport_manager::DeviceHandle;
using ::transport_manager::ConnectionUID;
using ::transport_manager::transport_adapter::TransportAdapter;
using ::transport_manager::TransportAdapterEvent;
using ::transport_manager::TransportManagerListener;
/*
* MOCK implementation of ::transport_manager::TransportManager interface
*/
class TransportManagerMock: public ::transport_manager::TransportManager {
public:
MOCK_METHOD0(Init,
int());
MOCK_METHOD0(Reinit,
int());
MOCK_METHOD0(SearchDevices,
int());
MOCK_METHOD1(ConnectDevice,
int(const DeviceHandle &));
MOCK_METHOD1(DisconnectDevice,
int(const DeviceHandle &));
MOCK_METHOD1(Disconnect,
int(const ConnectionUID &));
MOCK_METHOD1(DisconnectForce,
int(const ConnectionUID &));
MOCK_METHOD1(SendMessageToDevice,
int(const ::protocol_handler::RawMessagePtr));
MOCK_METHOD1(ReceiveEventFromDevice,
int(const TransportAdapterEvent&));
MOCK_METHOD1(AddTransportAdapter,
int(TransportAdapter *));
MOCK_METHOD1(AddEventListener,
int(TransportManagerListener *));
MOCK_METHOD0(Stop,
int());
MOCK_METHOD1(RemoveDevice,
int(const DeviceHandle &));
MOCK_CONST_METHOD1(Visibility,
int(const bool &));
};
} // namespace transport_manager_test
} // namespace components
} // namespace test
#endif // TEST_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MOCK_H_
| VProdanov/sdl_core | src/components/transport_manager/test/include/transport_manager_mock.h | C | bsd-3-clause | 3,528 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>colour.models.cie_xyy Module — Colour 0.3.4 documentation</title>
<link rel="stylesheet" href="_static/basic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
<link rel="stylesheet" href="_static/styles.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '0.3.4',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="_static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="_static/js/jquery-fix.js"></script>
<script type="text/javascript" src="_static/bootstrap-3.1.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="_static/bootstrap-sphinx.js"></script>
<link rel="top" title="Colour 0.3.4 documentation" href="index.html" />
<link rel="up" title="colour.models Package" href="colour.models.html" />
<link rel="next" title="colour.models.common Module" href="colour.models.common.html" />
<link rel="prev" title="colour.models.cie_uvw Module" href="colour.models.cie_uvw.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">
</head>
<body>
<div id="navbar" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"><img src="_static/Colour_Logo_Icon_001.png">
Colour 0.3</a>
<!--<span class="navbar-text navbar-version pull-left"><b>0.3</b></span>-->
</div>
<div class="collapse navbar-collapse nav-collapse">
<ul class="nav navbar-nav">
<li class="divider-vertical"></li>
<li><a href="https://www.colour-science.org">colour-science.org</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-life-ring"> Documentation</i><b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<a href="api.html" class="fa fa-life-ring"> API Reference</a>
</li>
<li>
<a href="http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/colour.ipynb', True)" class="fa fa-book"> IPython Notebooks</a>
</li>
<li>
<a href="https://www.colour-science.org/features.php" class="fa fa-lightbulb-o"> Features</a>
</li>
<li>
<a href="https://www.colour-science.org/contributing.php"><span class="fa fa-gears"> Contributing</span></a>
</li>
</ul>
</li>
<li>
<a href="colour.models.cie_uvw.html" title="Previous Chapter: colour.models.cie_uvw Module"><span class="glyphicon glyphicon-chevron-left visible-sm"></span><span class="hidden-sm">« colour.models.ci...</span>
</a>
</li>
<li>
<a href="colour.models.common.html" title="Next Chapter: colour.models.common Module"><span class="glyphicon glyphicon-chevron-right visible-sm"></span><span class="hidden-sm">colour.models.co... »</span>
</a>
</li>
</ul>
<form class="navbar-form navbar-right" action="search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section" id="module-colour.models.cie_xyy">
<span id="colour-models-cie-xyy-module"></span><h1>colour.models.cie_xyy Module<a class="headerlink" href="#module-colour.models.cie_xyy" title="Permalink to this headline">¶</a></h1>
<div class="section" id="cie-xyy-colourspace">
<h2>CIE xyY Colourspace<a class="headerlink" href="#cie-xyy-colourspace" title="Permalink to this headline">¶</a></h2>
<p>Defines the <em>CIE xyY</em> colourspace transformations:</p>
<ul class="simple">
<li><a class="reference internal" href="#colour.models.cie_xyy.XYZ_to_xyY" title="colour.models.cie_xyy.XYZ_to_xyY"><tt class="xref py py-func docutils literal"><span class="pre">XYZ_to_xyY()</span></tt></a></li>
<li><a class="reference internal" href="#colour.models.cie_xyy.xyY_to_XYZ" title="colour.models.cie_xyy.xyY_to_XYZ"><tt class="xref py py-func docutils literal"><span class="pre">xyY_to_XYZ()</span></tt></a></li>
<li><a class="reference internal" href="#colour.models.cie_xyy.xy_to_XYZ" title="colour.models.cie_xyy.xy_to_XYZ"><tt class="xref py py-func docutils literal"><span class="pre">xy_to_XYZ()</span></tt></a></li>
<li><a class="reference internal" href="#colour.models.cie_xyy.XYZ_to_xy" title="colour.models.cie_xyy.XYZ_to_xy"><tt class="xref py py-func docutils literal"><span class="pre">XYZ_to_xy()</span></tt></a></li>
</ul>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/cie_xyy.ipynb">CIE xyY Colourspace IPython Notebook</a></p>
</div>
<p class="rubric">References</p>
<table class="docutils footnote" frame="void" id="id1" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[1]</td><td>Wikipedia. (n.d.). CIE 1931 color space. Retrieved February 24, 2014,
from <a class="reference external" href="http://en.wikipedia.org/wiki/CIE_1931_color_space">http://en.wikipedia.org/wiki/CIE_1931_color_space</a></td></tr>
</tbody>
</table>
<dl class="function">
<dt id="colour.models.cie_xyy.XYZ_to_xyY">
<tt class="descclassname">colour.models.cie_xyy.</tt><tt class="descname">XYZ_to_xyY</tt><big>(</big><em>XYZ</em>, <em>illuminant=(0.34567</em>, <em>0.3585)</em><big>)</big><a class="reference internal" href="_modules/colour/models/cie_xyy.html#XYZ_to_xyY"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#colour.models.cie_xyy.XYZ_to_xyY" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts from <em>CIE XYZ</em> colourspace to <em>CIE xyY</em> colourspace and reference
<em>illuminant</em>.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>XYZ</strong> (<em>array_like, (3,)</em>) – <em>CIE XYZ</em> colourspace matrix.</li>
<li><strong>illuminant</strong> (<em>array_like, optional</em>) – Reference <em>illuminant</em> chromaticity coordinates.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><em>CIE xyY</em> colourspace matrix.</p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Return type:</th><td class="field-body"><p class="first last">ndarray, (3,)</p>
</td>
</tr>
</tbody>
</table>
<p class="rubric">Notes</p>
<ul class="simple">
<li>Input <em>CIE XYZ</em> colourspace matrix is in domain [0, 1].</li>
<li>Output <em>CIE xyY</em> colourspace matrix is in domain [0, 1].</li>
</ul>
<p class="rubric">References</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[2]</td><td>Lindbloom, B. (2003). XYZ to xyY. Retrieved February 24, 2014,
from <a class="reference external" href="http://www.brucelindbloom.com/Eqn_XYZ_to_xyY.html">http://www.brucelindbloom.com/Eqn_XYZ_to_xyY.html</a></td></tr>
</tbody>
</table>
<p class="rubric">Examples</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">XYZ</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.07049534</span><span class="p">,</span> <span class="mf">0.1008</span><span class="p">,</span> <span class="mf">0.09558313</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">XYZ_to_xyY</span><span class="p">(</span><span class="n">XYZ</span><span class="p">)</span>
<span class="go">array([ 0.2641477..., 0.3777000..., 0.1008 ])</span>
</pre></div>
</div>
</dd></dl>
<dl class="function">
<dt id="colour.models.cie_xyy.xyY_to_XYZ">
<tt class="descclassname">colour.models.cie_xyy.</tt><tt class="descname">xyY_to_XYZ</tt><big>(</big><em>xyY</em><big>)</big><a class="reference internal" href="_modules/colour/models/cie_xyy.html#xyY_to_XYZ"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#colour.models.cie_xyy.xyY_to_XYZ" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts from <em>CIE xyY</em> colourspace to <em>CIE XYZ</em> colourspace.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>xyY</strong> (<em>array_like, (3,)</em>) – <em>CIE xyY</em> colourspace matrix.</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><em>CIE XYZ</em> colourspace matrix.</td>
</tr>
<tr class="field-odd field"><th class="field-name">Return type:</th><td class="field-body">ndarray, (3,)</td>
</tr>
</tbody>
</table>
<p class="rubric">Notes</p>
<ul class="simple">
<li>Input <em>CIE xyY</em> colourspace matrix is in domain [0, 1].</li>
<li>Output <em>CIE XYZ</em> colourspace matrix is in domain [0, 1].</li>
</ul>
<p class="rubric">References</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[3]</td><td>Lindbloom, B. (2009). xyY to XYZ. Retrieved February 24, 2014,
from <a class="reference external" href="http://www.brucelindbloom.com/Eqn_xyY_to_XYZ.html">http://www.brucelindbloom.com/Eqn_xyY_to_XYZ.html</a></td></tr>
</tbody>
</table>
<p class="rubric">Examples</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">xyY</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.26414772</span><span class="p">,</span> <span class="mf">0.37770001</span><span class="p">,</span> <span class="mf">0.1008</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">xyY_to_XYZ</span><span class="p">(</span><span class="n">xyY</span><span class="p">)</span>
<span class="go">array([ 0.0704953..., 0.1008 , 0.0955831...])</span>
</pre></div>
</div>
</dd></dl>
<dl class="function">
<dt id="colour.models.cie_xyy.xy_to_XYZ">
<tt class="descclassname">colour.models.cie_xyy.</tt><tt class="descname">xy_to_XYZ</tt><big>(</big><em>xy</em><big>)</big><a class="reference internal" href="_modules/colour/models/cie_xyy.html#xy_to_XYZ"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#colour.models.cie_xyy.xy_to_XYZ" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the <em>CIE XYZ</em> colourspace matrix from given <em>xy</em> chromaticity
coordinates.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>xy</strong> (<em>array_like</em>) – <em>xy</em> chromaticity coordinates.</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><em>CIE XYZ</em> colourspace matrix.</td>
</tr>
<tr class="field-odd field"><th class="field-name">Return type:</th><td class="field-body">ndarray, (3,)</td>
</tr>
</tbody>
</table>
<p class="rubric">Notes</p>
<ul class="simple">
<li>Input <em>xy</em> chromaticity coordinates are in domain [0, 1].</li>
<li>Output <em>CIE XYZ</em> colourspace matrix is in domain [0, 1].</li>
</ul>
<p class="rubric">Examples</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">xy</span> <span class="o">=</span> <span class="p">(</span><span class="mf">0.26414772236966133</span><span class="p">,</span> <span class="mf">0.37770000704815188</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">xy_to_XYZ</span><span class="p">(</span><span class="n">xy</span><span class="p">)</span>
<span class="go">array([ 0.6993585..., 1. , 0.9482453...])</span>
</pre></div>
</div>
</dd></dl>
<dl class="function">
<dt id="colour.models.cie_xyy.XYZ_to_xy">
<tt class="descclassname">colour.models.cie_xyy.</tt><tt class="descname">XYZ_to_xy</tt><big>(</big><em>XYZ</em>, <em>illuminant=(0.34567</em>, <em>0.3585)</em><big>)</big><a class="reference internal" href="_modules/colour/models/cie_xyy.html#XYZ_to_xy"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#colour.models.cie_xyy.XYZ_to_xy" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the <em>xy</em> chromaticity coordinates from given <em>CIE XYZ</em> colourspace
matrix.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>XYZ</strong> (<em>array_like, (3,)</em>) – <em>CIE XYZ</em> colourspace matrix.</li>
<li><strong>illuminant</strong> (<em>array_like, optional</em>) – Reference <em>illuminant</em> chromaticity coordinates.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><em>xy</em> chromaticity coordinates.</p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Return type:</th><td class="field-body"><p class="first last">tuple</p>
</td>
</tr>
</tbody>
</table>
<p class="rubric">Notes</p>
<ul class="simple">
<li>Input <em>CIE XYZ</em> colourspace matrix is in domain [0, 1].</li>
<li>Output <em>xy</em> chromaticity coordinates are in domain [0, 1].</li>
</ul>
<p class="rubric">Examples</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">XYZ</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.07049534</span><span class="p">,</span> <span class="mf">0.1008</span><span class="p">,</span> <span class="mf">0.09558313</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">XYZ_to_xy</span><span class="p">(</span><span class="n">XYZ</span><span class="p">)</span>
<span class="go">(0.2641477..., 0.3777000...)</span>
</pre></div>
</div>
</dd></dl>
</div>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-right">
<a href="#">Back to top</a>
</p>
<p>
© Copyright 2013 - 2015, Colour Developers.<br/>
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.2.<br/>
</p>
</div>
</footer>
</body>
</html> | colour-science/colour-science.org | output/api/0.3.4/html/colour.models.cie_xyy.html | HTML | bsd-3-clause | 17,130 |
Because the ```gpu_test_expectations``` directory is based on parts of Chromium's ```gpu/config``
directory, we want to keep a patch of the changes added to make it compile with ANGLE. This
will allow us to merge Chromium changes easily in our ```gpu_test_expectations```.
In order to make a change to this directory, do the following:
* copy the directory somewhere like in ```gpu_test_expectations_reverted```
* in ```gpu_test_expectations_reverted``` run ```patch -p 1 -R < angle-mods.patch```
* do your changes in ```gpu_test_expectations```
* delete angle-mods.path in both directories
* run ```diff -rupN gpu_test_expectations_reverted gpu_test_expectations > angle-mods.patch```
* copy ```angle-mods.patch``` in ```gpu_test_expectations```
How to update from Chromium:
* ```git apply -R angle-mods.patch```, ```git add . -u```, ```git commit```
* Copy over Chromium files, ```git add . -u```, ```git commit```
* ```git revert HEAD~2```
* ```rm angle-mods.patch```
* ```git diff HEAD~1 (`)ls(`) > angle-mods.patch```,```git add angle-mods.patch```, ```git commit --amend```
* ```git rebase -i``` to squash the three patches into one.
| crezefire/angle | src/tests/third_party/gpu_test_expectations/HowToMakeChanges.md | Markdown | bsd-3-clause | 1,157 |
local Dta = select(2, ...)
Dta.Lang.English = {}
local English = Dta.Lang.English
----------------------------------------
--Help
----------------------------------------
---Intro------------------------------------------------------------------
English.Intro = {}
English.Intro.Label = "Intro"
English.Intro.Text1 = "\
Hello Dimensioneers!\
\
This Addon is the continuation of Dimension Tools, originally developed\
by Kikimora with the support of the Rift Dream Dimensions team.\
And Dimension Tools is an advancement of Dimension Toolbox by Arkzy.\
\
The following is a summary of the core features:\
\
<u>Tinker Tools Features:</u>\
- Compact user interface giving you more screen space when building dimensions.\
All the tools can be brought up individually with the buttons provided in\
the main window.\
\
- Move, scale and rotate hundreds of items at once precisely in various modes.\
(Though you must keep in mind that the more items you modify, the longer it\
takes to finish processing it.)\
\
- The functionality of the Copy/Paste tool ranges from transfering selected values\
between items with optional offset to cloning whole groups of items and placing\
multiple copies in your dimension directly from your bags and/or bank.\
\
- With the Load/Save feature you can choose between loading one of the\
default sets or your own saved sets. And for convenience you can place\
multiple copies of a saved set at once with an offset on the X, Y or X axis.\
\
- The Import/Export feature allows you to transfer your saved sets using a global file\
or via text copy and paste. Also supports importing Toolbox sets in text format.\
\
Thanks for all the support from the dimension community,\
and have fun building your dreams!"
English.Intro.Text2 = "<u>Change Log</u>\
For the changes please refer to the included Changelog.txt file.\
\
For a more detailed list of changes, you can also check the commit log at\
https://github.com/Lynx3d/dimension_tools/commits/master"
English.Intro.Text3 = ""
---Main-------------------------------------------------------------------
English.Main = {}
English.Main.Label = "Main"
English.Main.Text1 = "\
The tool button is where it all starts. Left-click it to open the main window,\
right-click it to drag it. The main window holds the basic information about\
the selected items along with the buttons to open up all the individual tools.\
\
Tinker Tools can only be opened inside of dimensions, unless you override\
this with the '/tt force' chat command."
English.Main.Text2 = "\
The item icon has a small 'x'-button to clear the selection, and a right-click\
on the icon will set a waypoint on the minimap.\
\
<u>Window Toggle Buttons:</u>\
- ?: Opens up this help window.\
- Move: A tool to move items in various modes.\
- Rotate: A tool to rotate items in various modes.\
- Scale: A tool to scale items in various modes.\
- Offset Calc.: A tool to determine offset values for proper item alignment.\
- Copy / Paste: A tool to copy and paste items with many options.\
- Load / Save: A tool to load and save structures. Also links to Import / Export.\
- Tribal Magic: A tool that allows you to move more freely.\
- Alfiebet: A text creation tool using standard building blocks.\
- Reskin: A tool to replace building blocks with a different appearance."
English.Main.Text3 = ""
---Move-------------------------------------------------------------------
English.Move = {}
English.Move.Label = "Move"
English.Move.Text1 = "\
The Move Window is where you modify the positions of the selected items."
English.Move.Text2 = "\
<u>Descriptions:</u>\
- X/Y/Z: Specifies the coordinates for the X/Y/Z axis.\
Empty fields will leave the associated axis unaffected.\
- Absolute: Moves the item(s) to the coordinates set in X,Y,Z.\
- Relative: Moves the item(s) with an offset from current position by the\
numbers set in X,Y,Z.\
- As Group: Treats the whole selection as one object with the selection center\
as position; only available in absolute mode.\
- Local Axes: Moves each item along its local axes. Local axis means the item's\
rotation is applied to the global axis, creating a coordinate system that rotates\
with the object. Since the item itself defines the origin, this is only available\
in relative mode.\
- Move: Starts the moving of the item(s).\
- Reset: Resets the item(s) to your current position."
English.Move.Text3 = ""
---Rotate-----------------------------------------------------------------
English.Rotate = {}
English.Rotate.Label = "Rotate"
English.Rotate.Text1 = "\
The Rotate Window is where you modify the Rotation of the selected item(s)."
English.Rotate.Text2 = "\
<u>Descriptions:</u>\
- Pitch: Specifies the rotation about the X axis.\
- Yaw: Specifies the rotation about the Y axis.\
- Roll: Specifies the rotation about the Z axis.\
- Absolute: Sets the item(s) rotation to the exact numbers you put in Pitch,\
Yaw and Roll.\
NOTE: While empty fields will use the current values, there is always more\
than one way to represent the same rotation. Rift may convert the angles if\
your input exceeds certain boundaries, and hence chance all 3 values, which\
may greatly confuse you on subsequent rotation adjustments. So it is highly\
recommended to not leave fields empty in absolute mode.\
- Relative: Rotates the item(s) with the numbers you set in Yaw, Pitch and\
Roll from the current rotation. So if current rotation is 30 degrees Yaw\
and you put 20 degrees in the Yaw box it will end up having a rotation\
of 50 degrees.\
- As Group: Treats the whole selection as one object. Note that since selections\
are temporary, there is no way to save a current rotation for the group.\
This has two consequences: This mode is only available in relative mode, and\
the rotation happens around the global axis.\
Note that you can rotate a single item around global axis too this way.\
- Rotate: Starts the rotation of the item(s).\
- Reset: Resets the item(s) Pitch, Yaw and Roll to 0 degrees."
English.Rotate.Text3 = ""
---Scale------------------------------------------------------------------
English.Scale = {}
English.Scale.Label = "Scale"
English.Scale.Text1 = "\
The Scale Window is where you modify the Scale of the selected item(s)."
English.Scale.Text2 = "\
<u>Descriptions:</u>\
- Scale: Specifies the scale factor for the selected item(s).\
- Absolute: Sets the scale of the item(s) to the exact number you put in.\
- Relative: Sets the scale of the item(s) to the current scale multiplied by\
the number you put in.\
- As Group: Treats the whole selection as one object. Note that since selections\
are temporary, there is no way to determine a current scale of the group,\
so it is only available in relative mode.\
Warning: Items have diverse scale limitations. If you exceed those, your group\
will fall apart, so to speak, because this mode also has to move items.\
- Scale: Starts the scaling of the item(s).\
- Reset: Resets the item(s) scale to 1."
English.Scale.Text3 = ""
---Copy and Paste---------------------------------------------------------
English.CopyandPaste = {}
English.CopyandPaste.Label = "Copy and Paste"
English.CopyandPaste.Text1 = "\
The Copy / Paste Tool is pretty versatile, and behaves a bit different\
depending on what you do.\
When you copy a single item, you can paste its values to any other item,\
the item type gets ignored in this case, and individual values can be excluded.\
But the real power lies in the ability to copy a group of items and paste an\
array with incremental offsets, using items from your inventory."
English.CopyandPaste.Text2 = "\
You can disable and enable any of the offsets by clicking the selection box\
in front of the text fields. When pasting to a single selected object, this\
also controls which properties are transferred to the selected item.\
\
<u>Descriptions:</u>\
- Offset X, Y, Z: Sets the offset for the X, Y, Z axis for the item(s) you\
are going to paste the clipboard to.\
- Offset Pitch, Yaw, Roll: Sets the rotation offset for the Pitch, Yaw,\
Roll axis for the item(s) you are going to paste the clipboard to.\
For single items, the values are simply added to the original values.\
For item groups or when a pivot is used, the items get transformed using the\
global coordinate axis.\
- Offset Scale: Sets the scale change for the paste. For example, 0.2 will make\
the placed copy 20% larger, and -0.2 consequently 20% smaller.\
- Offset multiple items: Makes it possible to paste an array by iteratively adding\
the offsets to the values of the previously placed copy. This accepts either\
a count or a range in the form first:last. So 5 is equivalent to 1:5. First and\
last may be zero or even negative. This way you can include the original position\
with 0:5, extend a previously pasted array like 6:10 for 5 more copies, inverse\
the direction with -1:-5 etc.\
- Flicker reduction: This adds a small quasi-random offset to each placed copy to\
prevent visual flickering from overlapping coplanar parts (Z-fighting).\
The input field lets you adjust the amplitude of the offset sequence.\
- Custom Pivot: This causes rotation and scaling to be calculated relative to the\
point you picked (see below for details).\
- Use New Items: Activates the possibility to place new items from your bags or\
bank into your dimension. Your inventory will be scanned to ensure you have\
enough items before the pasting begins\
- Copy: Copies the stats of the items you have selected to clipboard.\
- Paste: Pastes the clipboard according to the settings you made.\
This may take a while when placing many new items.\
\
Depending on the settings, additional controls become available, as seen below:"
English.CopyandPaste.Text3 = "\
<u>Descriptions of additional options:</u>\
- Nr. of Copies: This will be showing up when Offset multiple items is activated.\
- Pick: This button is available when Custom Pivot is active and lets you record the\
position of your current selection. This lets you for example build a spiral\
staircase around a specific center point.\
The pivot is kept until you pick a new one (or leave the dimension), and doesn't\
change if you move or remove the item(s) afterwards.\
- Bags: Controls whether to include items from your bags to place new items.\
- Bank: Controls whether to include items from your bank (bags and vaults) to\
place new items. Note that this has limitations when you don't have\
actual bank access."
---Load and Save----------------------------------------------------------
English.LoadandSave = {}
English.LoadandSave.Label = "Load and Save"
English.LoadandSave.Text1 = "\
The Load / Save Sets window is all about saving the sets you created to be\
able to load them up on other places in your dimension or in other dimensions\
you have."
English.LoadandSave.Text2 = "\
<u>Descriptions:</u>\
- Name (Textbox): Here you set the name for the set you want to save.\
- Save Set: Saves the set to file.\
- Import/Export: Opens the Import/Export dialog (see next help topic)\
\
- Default Sets: Gives you the possibility to load the default sets provided\
by the RiftDreamDimensions team.\
These sets are tools created to aid you in your creativity.\
\
For a detailed guide on how to use these tools you can go to\
http://RiftDreamDimensions.com and take a look at the\
Dimension Tools PDF file.\
\
- Saved Sets: Gives you the possibility to load your own made sets into your\
Dimensions.\
- Tbx Sets: Gives you the possibility to load your old Toolbox Sets, explanation\
on how that works you find later in this help.\
\
- Search: Filters the drop-down below, refreshes when hitting 'return'.\
- Name (Drop-down): A list of all available set. Depending on if you have\
chosen Default Sets or Saved Sets the drop box will go to different lists.\
- Load Set: Loads the selected set into your dimension using items you have\
selected in your dimension or using items from your bags.\
- Print Materials: Print out a list of items needed for the selected set.\
- Delete Set: Removes the selected set from your saved list (only Saved Sets).\
- To Clipboard: This copies the set to the Copy&Paste clipboard, so you can paste\
it with that tool. This gives you more options, for example pasting multiple\
copies, but also allows using the Reskin tool to change materials before pasting.\
- Use New Items: This places new items from your inventory. Otherwise you need\
to have the required items placed and selected.\
- Load at original location: If this is selected, the set will be loaded with\
the coordinates it was originally saved with. Otherwise it will be loaded close\
to your current position, or if enabled, at your reference point.\
Only advisable when dimension keys of load and save match.\
\
- Use Reference Point: This option allows for more control over the placement of\
loaded sets. When saving a set, the picked point is simply saved along with the\
items of the set. When you later load this set, the set will be moved so that\
the saved reference point aligns with your current pick. If the set has no\
reference point, the center point of the set will be used instead.\
- Pick: This sets your current selection center as reference point."
English.LoadandSave.Text3 = "\
Tbx Sets is somewhat special. By default that set is empty, but for old Dimension\
Toolbox users this is a way to get your sets that you made with Dimension\
Toolbox to work within Tinker Tools as well.\
\
To get your old sets loaded into Dimension Tools you need to do the following:\
1: Locate the tbx.lua File, found under:\
/Users/[YourName]/Documents/RIFT/Interface/Saved/[YourRiftAccount]\
/SavedVariables\
2: Copy the file txb.lua into the same directory.\
3: Rename the new file to tbx_Import.lua\
4: Now start up rift and you should have all your old Dimension Toolbox Sets\
there to load up and place in your dimensions.\
\
Be aware you will not be able to remove any of the sets loaded under Tbx Sets,\
so I highly recommend that before you copy and rename the file go to Dimension\
Toolbox and delete all sets you don't want to use in Dimension Tools."
---Import and Export------------------------------------------------------
English.ImportandExport = {}
English.ImportandExport.Label = "Import and Export"
English.ImportandExport.Text1 = "\
The Import / Export Sets window is all about sharing your sets with other\
friends in the game.\
There are two ways to exchange sets, with the Dimension Tools export addon\
and by converting it to/from text you can copy/paste using the system clipboard.\
\
The Dimension Tools export is an embedded addon that uses saved variabls to\
exchange the data, the file will be named Dimtools_Export.lua\
Usually you will find that file at:\
C:/Users/%USERNAME%/My Documents/RIFT/Interface/Saved/SavedVariables\
Note that the default path depends on the Windows version and locale, and\
furthermore depends on the DocumentsDirectory variable in rift.cfg.\
But generally, Saved/ resides in the same directory as your Addons/ directory,\
which can be opened from Rift's addons configuration dialog."
English.ImportandExport.Text2 = "\
<u>Descriptions:</u>\
- Saved Sets: Sets the source for sets to your Tinker Tools saved sets.\
- Tbx Sets: Sets the source to your Toolbox sets that were auto-imported.\
- Name (First drop-down): Here you can select any of your own saved sets to\
be exported.\
- Export: Exports the selected set to the Dimtools_Export.lua file.\
- Export Text: Exports the selected set to the text box at the bottom.\
- Name (Second drop-down): Here you can select any of the sets saved in the\
export File.\
- New Name: Specify the name this set will have. Optional for Dimension Tools\
Import, mandatory for Text Import.\
- Import: Imports the selected set to your saved sets list and then removes\
the set from the export file.\
- Import Text: Imports the text from the text box at the bottom to your saved\
sets list. Also accepts the Dimension Toolbox format (auto-detected).\
\
When using Dimension Tools file export, keep in mind that addon data is not\
written to disk until addons are unloaded, so either logout or use the /reloadui\
chat command to save the data to Dimtools_Export.lua\
\
When you import from a foreign Dimtools_Export.lua file, you must not be logged in\
with your character when you copy it into the SavedVariables directory, otherwise\
it will be overwritten before you can import anything from it."
English.ImportandExport.Text3 = ""
---Tribal Magic-----------------------------------------------------------
English.TribalMagic = {}
English.TribalMagic.Label = "Tribal Magic"
English.TribalMagic.Text1 = "\
Tribal Magic is based on the Magic Carpet addon made by AladdinRift.\
Instead of an Ochre Rug it uses the smaller Round Tribal Table to give you\
more room to look around without seeing the edges of the item you fly on."
English.TribalMagic.Text2 = "\
<u>Descriptions:</u>\
- Place: places the Round Tribal Table in your dimension for flying.\
- Pick up: Picks up the Round Tribal Table from your dimension.\
- Slider: Changes the angle of the Round Tribal Table.\
0: Levels out the Round Tribal Table, so you can move around on the altitude\
you currently are.\
+1 to +4: The higher the number the more you will go upwards as you move.\
-1 to -4: The lower the number the more you will go downwards as you move.\
The slider can also be moved with the mouse wheel when the cursor is above it."
English.TribalMagic.Text3 = ""
---Reskin-----------------------------------------------------------------
English.Reskin = {}
English.Reskin.Label = "Reskin"
English.Reskin.Text1 = "\
The Reskin Tool replaces building blocks of one surface appearance (skin)\
with another skin of your choice.\
It works on the Copy / Paste clipboard, so before you can start, you need\
to copy something first. Note that you can also copy a saved set to the\
clipboard.\
When you're finished, you can paste the reskinned clipboard. You'll probably\
want to activate the 'Use New Items' option for this, and pick up the original\
structure if you're pasting at the original location."
English.Reskin.Text2 = "\
<u>Descriptions:</u>\
- Old Skin: The skin you want to replace.\
- New Skin: The skin that will replace the old one.\
- Checkboxes: Select the building block shapes you want to be included.\
- Apply: Applies the changes to the clipboard and prints a summary."
English.Reskin.Text3 = ""
---Afterword--------------------------------------------------------------
English.Afterword = {}
English.Afterword.Label = "Afterword"
English.Afterword.Text1 = "\
Many thanks to the Rift Community for supporting me. Your feedback\
and in-game donations have helped me a lot to stay motivated and continue\
from where Kikimora left Dimension Tools at.\
\
A lot of work was put into refactoring the old code, effectively making\
this a whole new addon.\
\
I hope you will enjoy the addon with its signifficant interface changes\
and keep making a lot of wonderful creations with it.\
For questions, errors, suggestions or other information about the addon you\
want to share, have a look at the Dimensions section of the Rift forums.\
\
Special Thanks:\
AladdinRift, for allowing to integrate his code from Magic Carpet into\
Dimension Tools.\
\
The Translators:\
Aeryle, French translations.\
Thanks for continuing to work on the translation for this remake of the\
Dimension Tools addon.\
\
A little word from Aeryle:\
It was a pleasure for me to translate this Add-on in French.\
I hope the French Dimension community will enjoy it and i hope this\
translation will allow them to use this add-on more easily!"
English.Afterword.Text2 = ""
English.Afterword.Text3 = ""
---Offset Calc.-----------------------------------------------------------
English.OffsetCalc = {}
English.OffsetCalc.Label = "Offset Calc."
English.OffsetCalc.Text1 = "\
The Offset Calculator is a tool you can use to see what offset is need to\
place building blocks seamlessly against each other.\
This tool has come to life because of questions about how you determine the\
offset of a building block."
English.OffsetCalc.Text2 = "\
- Shape: Here you choose the type of item you want the offset for.\
Supported shapes: Pole, Square, Cube, Plank, Rectangle and Floors.\
- Orientation: Here you choose the orientation of an item.\
Supported are all 6 possible +/- 90° rotation combinations.\
For arbitrarily rotated items, Transformed X, Y and Z Offset give the\
vector that represents the item's local X, Y or Z vector respectively.\
A special case is 'Selection Delta', this does not work on the\
shape of an item, but calculates the differences between two\
selected items, and hence ignores the Shape and Scale setting.\
- Scale: Here you set the scale of the item.\
- Multiplier: Optional input. If present, the result will be multiplied\
by this value.\
- Calculate: Calculates the offsets for you.\
- X: The offset on the X axis.\
- Y: The offset on the Y axis.\
- Z: The offset on the Z axis.\
- Detect: This tries to detect all parameters from the item selection."
English.OffsetCalc.Text3 = ""
---Alfiebet-----------------------------------------------------------
English.Alfiebet = {}
English.Alfiebet.Label = "Alfiebet"
English.Alfiebet.Text1 = "\
Going through allot of dimensions over time one thing you see a lot, people\
writing words using different items. Some are really clear others are really\
bright using light sources to make them. But one thing they all have in common,\
people want to say something to their dimension visitors. That is why we as\
the RiftDreamDimensions team came up with the idea to make a word processor\
in Dimension Tools. And after a lot of thinking and work done by the\
RiftDreamDimensions team creating fonts for it we managed to get this tool\
working for you all to enjoy."
English.Alfiebet.Text2 = "\
- Word: This is where you type in the word you want in your dimension.\
- The tool only works with letters A to Z.\
- Font: This is where you choose what font you like to use.\
- Size: Here you can choose the size of the font.\
- Skin: Here you can choose what type of skin you want to give your word.\
- Place Horizontal: Writes the word horizontal along the X axis.\
- Place Vertical: Writes the word vertical along the Y axis.\
- Load Word: places the word into your dimension.\
- Print Materials: Prints a list of items you need in your chat window.\
This list will adjust itself depending on what skin you choose."
English.Alfiebet.Text3 = ""
English.Selection = {}
English.Selection.Label = "Selection"
English.Selection.Text1 = "\
The Selection tool mainly helps you saving and restoring the selection state\
of placed items. Some tool actions also automatically save a set of the items\
they used. Note that item identifiers are only valid for one building session.\
If the dimension gets unloaded (when the last player leaves), IDs become invalid\
and new ones are generated when you enter again. Consequently these sets are not\
saved when you log out, they are only temporary."
English.Selection.Text2 = "\
- Save Set: Saves your current selection\
- Load Set: Selects all items in the set. Currently selected items will remain\
selected so you can combine selections as you please.\
- Name (drop-down): Lists all saved sets, including automatically created ones.\
Automatically saved are your last copy selection, and the items placed by your\
last paste and set loading.\
- Delete Set: Delete a saved set.\
- Invert: This inverts the selection state of all items, i.e. what's currently\
selected will be unselected, and what's unselected will be selected. So if\
nothing is selected, this will attempt to select everything (selecting requires\
items to be in vewing range too).\
*WARNING*: Attempting to modify too many items with Rift's own tools will cause\
disconnects, losing all temporary data of your building session like TT's clipboard\
and selection sets.\
- Pick Up: This does the same thing as Rift's Pick Up button. But this function\
can handle large item counts without disconnect, you're only limited by the\
bag space you have."
English.Selection.Text3 = ""
----------------------------------------
--Buttons
----------------------------------------
English.Buttons = {}
English.Buttons.MoveWindow = "Move"
English.Buttons.RotateWindow = "Rotate"
English.Buttons.ScaleWindow = "Scale"
English.Buttons.CopyPaste = "Copy / Paste"
English.Buttons.LoadSave = "Load / Save"
English.Buttons.ImportExport = "Import / Export"
English.Buttons.TribalMagic = "Tribal Magic"
English.Buttons.OffsetCalc = "Offset Calc."
English.Buttons.Reskin = "Reskin"
English.Buttons.Selection = "Selection"
English.Buttons.Copy = "Copy"
English.Buttons.Paste = "Paste"
English.Buttons.Pick = "Pick"
English.Buttons.Import = "Import"
English.Buttons.ImportText = "Import Text"
English.Buttons.Export = "Export"
English.Buttons.ExportText = "Export Text"
English.Buttons.Place = "Place"
English.Buttons.PickUp = "Pick Up"
English.Buttons.SaveSet = "Save Set"
English.Buttons.LoadSet = "Load Set"
English.Buttons.RemoveSet = "Delete Set"
English.Buttons.PrintMaterials = "Material List"
English.Buttons.ToClipboard = "To Clipboard"
English.Buttons.Move = "Move"
English.Buttons.Reset = "Reset"
English.Buttons.Rotate = "Rotate"
English.Buttons.Scale = "Scale"
English.Buttons.Calculate = "Calculate"
English.Buttons.Detect = "Detect"
English.Buttons.Transfer = "Transfer"
English.Buttons.LoadWord = "Load Word"
English.Buttons.Yes = "Yes"
English.Buttons.No = "No"
English.Buttons.OK = "OK"
English.Buttons.Cancel = "CANCEL"
English.Buttons.Apply = "Apply"
English.Buttons.More = "More..."
English.Buttons.Less = "Less..."
English.Buttons.InvertSelection = "Invert"
----------------------------------------
--Menus
----------------------------------------
English.Menus = {}
English.Menus.WindowStyle = { "Default", "Borderless" }
English.Menus.ItemType = {
"Cubes",
"Plank",
"Pole",
"Rectangle",
"Square",
"Floor",
"Hall Floor",
"Large Floor"
}
English.Menus.Orientation = {
"Default",
"Pitch 90",
"Yaw 90",
"Roll 90",
"Pitch & Yaw 90",
"Pitch & Roll 90",
"Selection Delta",
"Transformed X Offset",
"Transformed Y Offset",
"Transformed Z Offset"
}
----------------------------------------
--Titles
----------------------------------------
English.Titles = {}
English.Titles.Main = "Tinker Tools"
English.Titles.Move = "Move"
English.Titles.Rotate = "Rotate"
English.Titles.Scale = "Scale"
English.Titles.CopyPaste = "Copy / Paste Items"
English.Titles.LoadSave = "Load / Save Sets"
English.Titles.ImportExport = "Import / Export Sets"
English.Titles.TribalMagic = "Tribal Magic"
English.Titles.OffsetCalc = "Offset Calculation"
English.Titles.Help = "Tinker Tools Help"
English.Titles.Settings = "Settings"
English.Titles.TransferValues = "Transfer Values to:"
English.Titles.Reskin = "Replace Skins"
English.Titles.Selection = "Selection"
English.Titles.MaterialList = "Material List"
----------------------------------------
--Text
----------------------------------------
English.Text = {}
English.Text.Yaw = "Yaw"
English.Text.Pitch = "Pitch"
English.Text.Roll = "Roll"
English.Text.Scale = "Scale"
English.Text.NothingSelected = "Nothing selected"
English.Text.NrSelectItems = "Nr. of selected items:"
English.Text.MultiSelectItems = "%d items selected"
English.Text.Offset = "Offset"
English.Text.OffsetMultiItems = "Offset multiple items"
English.Text.FlickerReduce = "Flicker Reduction"
English.Text.UseNewItems = "Use New Items"
English.Text.SelectionPivot = "Custom Pivot"
English.Text.NrItems = "Nr. of Copies"
English.Text.Bags = "Bags"
English.Text.BankBags = "Bank"
English.Text.Vaults = "Vaults"
English.Text.DefaultSets = "Default Sets"
English.Text.SavedSets = "Saved Sets"
English.Text.TbxSets = "Tbx Sets"
English.Text.Name = "Name"
English.Text.Search = "Search"
English.Text.LoadOrigionalLocation = "Load at original location"
English.Text.UseRefPoint = "Use reference point"
English.Text.Absolute = "Absolute"
English.Text.Relative = "Relative"
English.Text.MoveAsGroup = "As group"
English.Text.LocalAxes = "Local Axes"
English.Text.Type = "Shape"
English.Text.Orientation = "Orientation"
English.Text.Word = "Word"
English.Text.Font = "Font"
English.Text.Size = "Size"
English.Text.Skin = "Skin"
English.Text.Horizontal = "Place Horizontal"
English.Text.Vertical = "Place Vertical"
English.Text.ConsoleMessages = "Console Messages"
English.Text.WindowStyle = "Window Style"
English.Text.RestoreTools = "Remember opened Tools when closing\nMain Window"
English.Text.NotIdleNotification = "Previous operation has not finished yet.\nAbort currently running operation now?"
English.Text.ConfirmDeleteSet = "Delete item set '%s'?"
English.Text.ConfirmOverwrite = "The set '%s' already exists.\nOverwrite this set?"
English.Text.ConfirmUsePosition = "The original position of this set is %.1fm away.\nContinue operation?"
English.Text.ConfirmPickup = "Are you sure you want to pick up all selected items?"
English.Text.ConfirmInvSelect = "Handling too many items may cause disconnects.\nSelect %d items?"
English.Text.Invert = "Inverse Direction"
English.Text.OldSkin = "Old Skin"
English.Text.NewSkin = "New Skin"
English.Text.Tile = "Square"
English.Text.Rectangle = "Rectangle"
English.Text.Triangle = "Triangle"
English.Text.Plank = "Plank"
English.Text.Cube = "Cube"
English.Text.Sphere = "Sphere"
English.Text.Pole = "Pole"
English.Text.Disc = "Disc"
English.Text.NewName = "New Name"
English.Text.Category = "Category"
English.Text.AnySkin = "<Any Skin>"
English.Text.Multiplier = "Multiplier"
----------------------------------------
--Prints
----------------------------------------
English.Prints = {}
--Main
English.Prints.DimensionOnly = "This addon is intended for use in Dimensions only."
English.Prints.ProcessFinished = "Processing Finished."
English.Prints.SetFinished = "Item set \"%s\" loaded and selected."
English.Prints.PasteFinished = "All items are placed and selected."
English.Prints.WordFinished = "The word is placed and selected."
--Copy / Paste
English.Prints.Copy_SelectItem = "Please select an item in order to copy attributes"
English.Prints.NumbersOnly = "Please enter numeric values only"
English.Prints.CopyFirst = "Please copy an item before pasting"
English.Prints.SelectItemSource = "Please select at least one source for new items"
English.Prints.NotPasteInventory = "Cannot paste clipboard - your inventory is missing the following items:"
English.Prints.NotPasteSelection = "Cannot paste clipboard - the selection is missing the following items:"
--Tribal Magic
English.Prints.NoRoundTable = "You do not seem to have an Round Tribal Table in your inventory!"
--Alfiebet
English.Prints.SelectFont = "Select a Font"
English.Prints.SelectSize = "Select a Size"
English.Prints.SelectSkin = "Select a Skin"
English.Prints.OnlyLetters = "Only letters allowed in the word"
English.Prints.TypeWord = "Please type a word first"
English.Prints.WordMissingItems = "Cannot build this word - the following items are missing from your bags:"
English.Prints.WordNeededItems = "The following items are required to create the word \"%s\":"
English.Prints.WordCouldNotPrint = "Could not print materials"
--Import/Export
English.Prints.SetNotFound = "Item set \"%s\" not found"
English.Prints.SelectExport = "You must select a set in order to Export it"
English.Prints.Exported = "Item set \"%s\" Exported"
English.Prints.SelectImport = "You must select a set in order to Import it"
English.Prints.Imported = "Item set \"%s\" Imported"
English.Prints.TextHint = "<Text input/output>\nCtrl+C: Copy\nCtrl+V: Paste\nCtrl+A: Select all\n"
--Load / Save
English.Prints.Saved = "Item set \"%s\" saved"
English.Prints.MinOneItem = "Must select 1 or more items in order to save them"
English.Prints.EnterName = "Must enter a name in order to save the set"
English.Prints.LoadNeededItems = "The following items are required for loading \"%s\":"
English.Prints.LoadPrintMats = "You must select a set in order to view its materials"
English.Prints.LoadSelectSet = "You must select a set in order to load it"
English.Prints.NotLoadedBags = "Cannot load set - the following items are missing from your bags:"
English.Prints.NotLoadedSelection = "Cannot load set - the following items are missing from your selection:"
English.Prints.SetLoaded = "Item set \"%s\" loaded"
English.Prints.SetRemoved = "Item set \"%s\" removed"
English.Prints.NotRemoved = "Could not remove \"%s\" - no such set found"
English.Prints.RemoveSelectSet = "You must select a set in order to remove it"
English.Prints.CopiedClipboard = "Item set \"%s\" has been copied to the Copy & Paste tool's clipboard."
English.Prints.PickRefPoint = "Please pick a reference point first."
English.Prints.NoRefPointWarn = "This item set has no reference point. Using center point instead."
--Measurements
English.Prints.SelectType = "Select a Type"
English.Prints.SelectOrientation = "Select an Orientation"
English.Prints.TypeSize = "Type a Size"
English.Prints.SizeC = "Make sure Size is between %.2f and %.1f"
English.Prints.Selection1 = "Transformed mode requires one selected item."
English.Prints.Selection2 = "Selection Delta requires two selected items."
--Move, Rotate, Scale
English.Prints.ModifyPosition = "Please select an item in order to modify its position"
English.Prints.ModifyRotation = "Please select an item in order to modify its rotation"
English.Prints.ModifyScale = "Please select an item in order to modify its scale"
--Reskin
English.Prints.ClipboardEmpty = "The Copy & Paste clipboard is empty."
English.Prints.Summary = "Replacement summary:"
| Lynx3d/tinker_tools | Language/Language_Eng.lua | Lua | bsd-3-clause | 33,867 |
from constance.admin import ConstanceForm
from django.forms import fields
from django.test import TestCase
class TestForm(TestCase):
def test_form_field_types(self):
f = ConstanceForm({})
self.assertIsInstance(f.fields['INT_VALUE'], fields.IntegerField)
self.assertIsInstance(f.fields['BOOL_VALUE'], fields.BooleanField)
self.assertIsInstance(f.fields['STRING_VALUE'], fields.CharField)
self.assertIsInstance(f.fields['DECIMAL_VALUE'], fields.DecimalField)
self.assertIsInstance(f.fields['DATETIME_VALUE'], fields.SplitDateTimeField)
self.assertIsInstance(f.fields['TIMEDELTA_VALUE'], fields.DurationField)
self.assertIsInstance(f.fields['FLOAT_VALUE'], fields.FloatField)
self.assertIsInstance(f.fields['DATE_VALUE'], fields.DateField)
self.assertIsInstance(f.fields['TIME_VALUE'], fields.TimeField)
# from CONSTANCE_ADDITIONAL_FIELDS
self.assertIsInstance(f.fields['CHOICE_VALUE'], fields.ChoiceField)
self.assertIsInstance(f.fields['EMAIL_VALUE'], fields.EmailField)
| jazzband/django-constance | tests/test_form.py | Python | bsd-3-clause | 1,084 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_free_struct_54b.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_free.label.xml
Template File: sources-sinks-54b.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: Allocate data using new
* GoodSource: Allocate data using malloc()
* Sinks:
* GoodSink: Deallocate data using delete
* BadSink : Deallocate data using free()
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__new_free_struct_54
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_c(twoIntsStruct * data);
void badSink_b(twoIntsStruct * data)
{
badSink_c(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(twoIntsStruct * data);
void goodG2BSink_b(twoIntsStruct * data)
{
goodG2BSink_c(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink_c(twoIntsStruct * data);
void goodB2GSink_b(twoIntsStruct * data)
{
goodB2GSink_c(data);
}
#endif /* OMITGOOD */
} /* close namespace */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s07/CWE762_Mismatched_Memory_Management_Routines__new_free_struct_54b.cpp | C++ | bsd-3-clause | 1,396 |
<script>
var xx = [];
var x = ["aa", "bb"];
var j=Math.random();
for(var i=0; i <2; i++){
for(var k=0; k<2; k++) {
if(i==k)
xx[i] = x[k];
}
}
// xx = ["aa", "bb"]
</script>
| darkrsw/safe | tests/loop_test/l9.html | HTML | bsd-3-clause | 188 |
// Copyright (c) 2014-2016, The Monero Project
//
// All rights reserved.
//
// 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 name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include "gtest/gtest.h"
#include "cryptonote_core/cryptonote_core.h"
#include "p2p/net_node.h"
#include "cryptonote_protocol/cryptonote_protocol_handler.h"
namespace cryptonote {
class blockchain_storage;
}
class test_core
{
public:
void on_synchronized(){}
uint64_t get_current_blockchain_height() const {return 1;}
void set_target_blockchain_height(uint64_t) {}
bool init(const boost::program_options::variables_map& vm) {return true ;}
bool deinit(){return true;}
bool get_short_chain_history(std::list<crypto::hash>& ids) const { return true; }
bool get_stat_info(cryptonote::core_stat_info& st_inf) const {return true;}
bool have_block(const crypto::hash& id) const {return true;}
bool get_blockchain_top(uint64_t& height, crypto::hash& top_id)const{height=0;top_id=cryptonote::null_hash;return true;}
bool handle_incoming_tx(const cryptonote::blobdata& tx_blob, cryptonote::tx_verification_context& tvc, bool keeped_by_block, bool relaued) { return true; }
bool handle_incoming_block(const cryptonote::blobdata& block_blob, cryptonote::block_verification_context& bvc, bool update_miner_blocktemplate = true) { return true; }
void pause_mine(){}
void resume_mine(){}
bool on_idle(){return true;}
bool find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, cryptonote::NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp){return true;}
bool handle_get_objects(cryptonote::NOTIFY_REQUEST_GET_OBJECTS::request& arg, cryptonote::NOTIFY_RESPONSE_GET_OBJECTS::request& rsp, cryptonote::cryptonote_connection_context& context){return true;}
cryptonote::blockchain_storage &get_blockchain_storage() { throw std::runtime_error("Called invalid member function: please never call get_blockchain_storage on the TESTING class test_core."); }
bool get_test_drop_download() const {return true;}
bool get_test_drop_download_height() const {return true;}
bool prepare_handle_incoming_blocks(const std::list<cryptonote::block_complete_entry> &blocks) { return true; }
bool cleanup_handle_incoming_blocks(bool force_sync = false) { return true; }
uint64_t get_target_blockchain_height() const { return 1; }
};
typedef nodetool::node_server<cryptonote::t_cryptonote_protocol_handler<test_core>> Server;
static bool is_blocked(Server &server, uint32_t ip, time_t *t = NULL)
{
std::map<uint32_t, time_t> ips = server.get_blocked_ips();
for (auto rec: ips)
{
if (rec.first == ip)
{
if (t)
*t = rec.second;
return true;
}
}
return false;
}
TEST(ban, add)
{
test_core pr_core;
cryptonote::t_cryptonote_protocol_handler<test_core> cprotocol(pr_core, NULL);
Server server(cprotocol);
cprotocol.set_p2p_endpoint(&server);
// starts empty
ASSERT_TRUE(server.get_blocked_ips().empty());
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
// add an IP
ASSERT_TRUE(server.block_ip(MAKE_IP(1,2,3,4)));
ASSERT_TRUE(server.get_blocked_ips().size() == 1);
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
// add the same, should not change
ASSERT_TRUE(server.block_ip(MAKE_IP(1,2,3,4)));
ASSERT_TRUE(server.get_blocked_ips().size() == 1);
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
// remove an unblocked IP, should not change
ASSERT_FALSE(server.unblock_ip(MAKE_IP(1,2,3,5)));
ASSERT_TRUE(server.get_blocked_ips().size() == 1);
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
// remove the IP, ends up empty
ASSERT_TRUE(server.unblock_ip(MAKE_IP(1,2,3,4)));
ASSERT_TRUE(server.get_blocked_ips().size() == 0);
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
// remove the IP from an empty list, still empty
ASSERT_FALSE(server.unblock_ip(MAKE_IP(1,2,3,4)));
ASSERT_TRUE(server.get_blocked_ips().size() == 0);
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
// add two for known amounts of time, they're both blocked
ASSERT_TRUE(server.block_ip(MAKE_IP(1,2,3,4), 1));
ASSERT_TRUE(server.block_ip(MAKE_IP(1,2,3,5), 3));
ASSERT_TRUE(server.get_blocked_ips().size() == 2);
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,5)));
ASSERT_TRUE(server.unblock_ip(MAKE_IP(1,2,3,4)));
ASSERT_TRUE(server.unblock_ip(MAKE_IP(1,2,3,5)));
// these tests would need to call is_remote_ip_allowed, which is private
#if 0
// after two seconds, the first IP is unblocked, but not the second yet
sleep(2);
ASSERT_TRUE(server.get_blocked_ips().size() == 1);
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,5)));
// after two more seconds, the second IP is also unblocked
sleep(2);
ASSERT_TRUE(server.get_blocked_ips().size() == 0);
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,4)));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
#endif
// add an IP again, then re-ban for longer, then shorter
time_t t;
ASSERT_TRUE(server.block_ip(MAKE_IP(1,2,3,4), 2));
ASSERT_TRUE(server.get_blocked_ips().size() == 1);
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,4), &t));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
ASSERT_TRUE(t >= 1);
ASSERT_TRUE(server.block_ip(MAKE_IP(1,2,3,4), 9));
ASSERT_TRUE(server.get_blocked_ips().size() == 1);
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,4), &t));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
ASSERT_TRUE(t >= 8);
ASSERT_TRUE(server.block_ip(MAKE_IP(1,2,3,4), 5));
ASSERT_TRUE(server.get_blocked_ips().size() == 1);
ASSERT_TRUE(is_blocked(server,MAKE_IP(1,2,3,4), &t));
ASSERT_FALSE(is_blocked(server,MAKE_IP(1,2,3,5)));
ASSERT_TRUE(t >= 4);
}
| eiabea/bitmonero | tests/unit_tests/ban.cpp | C++ | bsd-3-clause | 7,588 |
<?php
namespace app\models;
use Yii;
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
/**
* This is the model class for table "tbl_ref_jawatan_induk".
*
* @property integer $id
* @property string $desc
* @property integer $aktif
* @property integer $created_by
* @property integer $updated_by
* @property string $created
* @property string $updated
*/
class RefJawatanInduk extends \yii\db\ActiveRecord
{
const PRESIDEN = 1;
const TIMBALAN_PRESIDEN = 2;
const NAIB_PRESIDEN_1 = 3;
const NAIB_PRESIDEN_2 = 4;
const NAIB_PRESIDEN_3 = 5;
const NAIB_PRESIDEN_4 = 6;
const NAIB_PRESIDEN_5 = 7;
const NAIB_PRESIDEN_6 = 8;
const NAIB_PRESIDEN_7 = 9;
const NAIB_PRESIDEN_8 = 10;
const NAIB_PRESIDEN_9 = 11;
const NAIB_PRESIDEN_10 = 12;
const BENDAHARI = 13;
const PENOLONG_BENDAHARI = 14;
const SETIAUSAHA = 15;
const PENOLONG_SETIAUSAHA = 16;
const AHLI_JAWATANKUASA = 17;
const JURUAUDIT_1 = 18;
const JURUAUDIT_2 = 19;
const PENAUNG = 20;
const PENASIHAT = 21;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_ref_jawatan_induk';
}
public function behaviors()
{
return [
'bedezign\yii2\audit\AuditTrailBehavior',
[
'class' => \yii\behaviors\BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
[
'class' => \yii\behaviors\TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => 'updated',
'value' => new \yii\db\Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['desc'], 'required', 'message' => GeneralMessage::yii_validation_required],
[['aktif', 'created_by', 'updated_by'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
[['created', 'updated'], 'safe'],
[['desc'], 'string', 'max' => 80, 'tooLong' => GeneralMessage::yii_validation_string_max],
[['desc'], function ($attribute, $params) {
if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
$this->addError($attribute, GeneralMessage::yii_validation_xss);
}
}],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => GeneralLabel::id,
'desc' => GeneralLabel::desc,
'aktif' => GeneralLabel::aktif,
'created_by' => GeneralLabel::created_by,
'updated_by' => GeneralLabel::updated_by,
'created' => GeneralLabel::created,
'updated' => GeneralLabel::updated,
];
}
}
| hung101/kbs | frontend/models/RefJawatanInduk.php | PHP | bsd-3-clause | 2,995 |
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
#include <time.h>
#include <assert.h>
#include "engine/globals.h"
#include "public/logging.h"
#include "engine/memory.h"
#include "engine/utils.h"
#include "engine/opcode.h"
#include "engine/map.h"
#include "engine/scope.h"
#include "engine/type.h"
#include "engine/node.h"
#include "engine/proc.h"
namespace sawzall {
Scope* Scope::New(Proc* proc) {
Scope* s = NEWP(proc, Scope);
return s;
}
bool Scope::Insert(Object* obj) {
assert(obj != NULL);
if (obj->is_anonymous() || Lookup(obj->name()) == NULL) {
// object doesn't exist yet in this scope => insert it
list_.Append(obj);
obj->set_scope(this);
return true;
} else {
// object exists already
return false;
}
}
void Scope::InsertOrDie(Object* obj) {
if (!Insert(obj))
FatalError("identifier '%s' already declared in this scope", obj->name());
}
bool Scope::InsertOrOverload(Intrinsic* fun) {
assert(fun != NULL);
if (Insert(fun))
return true;
Object* obj = Lookup(fun->name());
Intrinsic* existing = obj->AsIntrinsic();
if (existing != NULL && existing->add_overload(fun)) {
fun->object()->set_scope(this);
return true;
}
return false;
}
void Scope::InsertOrOverloadOrDie(Intrinsic* fun) {
if (!InsertOrOverload(fun))
FatalError("identifier '%s' already declared in this scope", fun->name());
}
Object* Scope::Lookup(szl_string name) const {
return Lookup(name, strlen(name));
}
static bool SamePossiblyDottedName(szl_string dotted_name, szl_string name,
int length) {
const char* p;
const char* q;
for (p = dotted_name, q = name; *p != '\0' && q < name + length;
p++, q++) {
if (*p != *q) {
// Possible mismatch, check for the exception case.
if (*p == '.' && *q == '_')
continue; // Was '.' vs '_', treat it as a match
else
return false; // Not '.' vs '_', really was a mismatch
}
}
return (*p == '\0' && q == name + length);
}
Object* Scope::Lookup(szl_string name, int length) const {
assert(name != NULL);
for (int i = 0; i < list_.length(); i++) {
Object* obj = list_[i];
if (!obj->is_anonymous()) {
if (memcmp(obj->name(), name, length) == 0 && obj->name()[length] == '\0')
return obj;
// Temporarily find dotted names (package-qualified names using dot as
// the separator) when given a name that matches except for using
// underscores where the first name uses dots.
if (obj->AsTypeName() != NULL && obj->type()->is_tuple() &&
obj->type()->as_tuple()->is_message() &&
SamePossiblyDottedName(obj->name(), name, length)) {
return obj;
}
}
}
return NULL;
}
Object* Scope::LookupOrDie(szl_string name) const {
Object* obj = Lookup(name);
if (obj == NULL)
FatalError("identifier '%s' not found in this scope", name);
return obj;
}
Field* Scope::LookupByTag(int tag) const {
assert(tag > 0); // tags must be > 0, 0 indicates no tag
for (int i = 0; i < list_.length(); i++) {
Field* field = list_[i]->AsField();
if (field != NULL && field->tag() == tag)
return field;
}
return NULL;
}
void Scope::Clone(CloneMap* cmap, Scope* src, Scope* dst) {
// Scope entries are just for lookup, so we never clone them; instead
// we rely on their having already been cloned where originally written.
for (int i = 0; i < src->num_entries(); i++) {
// Block scope entries can be VarDecl, TypeName, QuantVarDecl
Object* obj = src->entry_at(i);
if (obj->AsVarDecl() != NULL) {
VarDecl* vardecl = cmap->Find(obj->AsVarDecl());
assert(vardecl != NULL);
dst->InsertOrDie(vardecl);
} else if (obj->AsTypeName() != NULL) {
TypeName* tname = cmap->Find(obj->AsTypeName());
assert(tname != NULL);
dst->InsertOrDie(tname);
} else {
ShouldNotReachHere();
}
}
}
void Scope::Print() const {
if (is_empty()) {
F.print("{}\n");
} else {
F.print("{\n");
for (int i = 0; i < num_entries(); i++) {
Object* obj = entry_at(i);
F.print(" %s: %T;", obj->display_name(), obj->type());
// print more detail, if possible
VarDecl* var = obj->AsVarDecl();
if (var != NULL) {
const char* kind = "";
if (var->is_local())
kind = "local";
else if (var->is_param())
kind = "parameter";
else if (var->is_static())
kind = "static";
else
ShouldNotReachHere();
F.print(" # %s, offset = %d", kind, var->offset());
}
F.print("\n");
}
F.print("}\n");
}
}
// Simulate multiple inheritance.
// These should be in the header but that introduces too many dependencies.
bool Scope::Insert(BadExpr* x) { return Insert(x->object()); }
bool Scope::Insert(Field* x) { return Insert(x->object()); }
bool Scope::Insert(Intrinsic* x) { return Insert(x->object()); }
bool Scope::Insert(Literal* x) { return Insert(x->object()); }
bool Scope::Insert(TypeName* x) { return Insert(x->object()); }
bool Scope::Insert(VarDecl* x) { return Insert(x->object()); }
void Scope::InsertOrDie(BadExpr* x) { InsertOrDie(x->object()); }
void Scope::InsertOrDie(Field* x) { InsertOrDie(x->object()); }
void Scope::InsertOrDie(Intrinsic* x) { InsertOrDie(x->object()); }
void Scope::InsertOrDie(Literal* x) { InsertOrDie(x->object()); }
void Scope::InsertOrDie(TypeName* x) { InsertOrDie(x->object()); }
void Scope::InsertOrDie(VarDecl* x) { InsertOrDie(x->object()); }
} // namespace sawzall
| xushiwei/szl | src/engine/scope.cc | C++ | bsd-3-clause | 6,221 |
/* sbt -- Simple Build Tool
* Copyright 2009, 2010 Mark Harrah
*/
package sbt
package compiler
import scala.util
import java.io.File
import CompilerArguments.{abs, absString, BootClasspathOption}
/** Forms the list of options that is passed to the compiler from the required inputs and other options.
* The directory containing scala-library.jar and scala-compiler.jar (scalaLibDirectory) is required in
* order to add these jars to the boot classpath. The 'scala.home' property must be unset because Scala
* puts jars in that directory on the bootclasspath. Because we use multiple Scala versions,
* this would lead to compiling against the wrong library jar.*/
final class CompilerArguments(scalaInstance: ScalaInstance, cp: ClasspathOptions)
{
def apply(sources: Seq[File], classpath: Seq[File], outputDirectory: File, options: Seq[String]): Seq[String] =
{
checkScalaHomeUnset()
val cpWithCompiler = finishClasspath(classpath)
// Scala compiler's treatment of empty classpath is troublesome (as of 2.9.1).
// We append a random dummy element as workaround.
val dummy = "dummy_" + Integer.toHexString(util.Random.nextInt)
val classpathOption = Seq("-classpath", if(cpWithCompiler.isEmpty) dummy else absString(cpWithCompiler))
val outputOption = Seq("-d", outputDirectory.getAbsolutePath)
options ++ outputOption ++ bootClasspathOption ++ classpathOption ++ abs(sources)
}
def finishClasspath(classpath: Seq[File]): Seq[File] =
filterLibrary(classpath) ++ include(cp.compiler, scalaInstance.compilerJar) ++ include(cp.extra, scalaInstance.extraJars : _*)
private def include(flag: Boolean, jars: File*) = if(flag) jars else Nil
protected def abs(files: Seq[File]) = files.map(_.getAbsolutePath).sortWith(_ < _)
protected def checkScalaHomeUnset()
{
val scalaHome = System.getProperty("scala.home")
assert((scalaHome eq null) || scalaHome.isEmpty, "'scala.home' should not be set (was " + scalaHome + ")")
}
/** Add the correct Scala library jar to the boot classpath.*/
def createBootClasspath =
{
val originalBoot = System.getProperty("sun.boot.class.path", "")
if(cp.bootLibrary)
{
val newBootPrefix = if(originalBoot.isEmpty) "" else originalBoot + File.pathSeparator
newBootPrefix + scalaInstance.libraryJar.getAbsolutePath
}
else
originalBoot
}
def filterLibrary(classpath: Seq[File]) =
if(cp.filterLibrary) classpath.filterNot(_.getName contains ScalaArtifacts.LibraryID) else classpath
def bootClasspathOption = if(cp.autoBoot) Seq(BootClasspathOption, createBootClasspath) else Nil
def bootClasspath = if(cp.autoBoot) IO.parseClasspath(createBootClasspath) else Nil
}
object CompilerArguments
{
val BootClasspathOption = "-bootclasspath"
def abs(files: Seq[File]): Seq[String] = files.map(_.getAbsolutePath)
def abs(files: Set[File]): Seq[String] = abs(files.toSeq)
def absString(files: Seq[File]): String = abs(files).mkString(File.pathSeparator)
def absString(files: Set[File]): String = absString(files.toSeq)
}
| kuochaoyi/xsbt | compile/CompilerArguments.scala | Scala | bsd-3-clause | 2,999 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/version_info_updater.h"
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/chromeos/chromeos_version.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/cros_settings_names.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/device_cloud_policy_manager_chromeos.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_version_info.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace chromeos {
namespace {
const char* kReportingFlags[] = {
chromeos::kReportDeviceVersionInfo,
chromeos::kReportDeviceActivityTimes,
chromeos::kReportDeviceBootMode,
chromeos::kReportDeviceLocation,
};
}
///////////////////////////////////////////////////////////////////////////////
// VersionInfoUpdater public:
VersionInfoUpdater::VersionInfoUpdater(Delegate* delegate)
: cros_settings_(chromeos::CrosSettings::Get()),
delegate_(delegate),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_pointer_factory_(this)) {
}
VersionInfoUpdater::~VersionInfoUpdater() {
policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
g_browser_process->browser_policy_connector()->
GetDeviceCloudPolicyManager();
if (policy_manager)
policy_manager->core()->store()->RemoveObserver(this);
for (unsigned int i = 0; i < arraysize(kReportingFlags); ++i)
cros_settings_->RemoveSettingsObserver(kReportingFlags[i], this);
}
void VersionInfoUpdater::StartUpdate(bool is_official_build) {
if (base::chromeos::IsRunningOnChromeOS()) {
version_loader_.GetVersion(
is_official_build ? VersionLoader::VERSION_SHORT_WITH_DATE
: VersionLoader::VERSION_FULL,
base::Bind(&VersionInfoUpdater::OnVersion,
weak_pointer_factory_.GetWeakPtr()),
&tracker_);
boot_times_loader_.GetBootTimes(
base::Bind(is_official_build ? &VersionInfoUpdater::OnBootTimesNoop
: &VersionInfoUpdater::OnBootTimes,
weak_pointer_factory_.GetWeakPtr()),
&tracker_);
} else {
UpdateVersionLabel();
}
policy::CloudPolicySubsystem* cloud_policy =
g_browser_process->browser_policy_connector()->
device_cloud_policy_subsystem();
if (cloud_policy) {
// Two-step reset because we want to construct new ObserverRegistrar after
// destruction of old ObserverRegistrar to avoid DCHECK violation because
// of adding existing observer.
cloud_policy_registrar_.reset();
cloud_policy_registrar_.reset(
new policy::CloudPolicySubsystem::ObserverRegistrar(
cloud_policy, this));
// Ensure that we have up-to-date enterprise info in case enterprise policy
// is already fetched and has finished initialization.
UpdateEnterpriseInfo();
}
policy::DeviceCloudPolicyManagerChromeOS* policy_manager =
g_browser_process->browser_policy_connector()->
GetDeviceCloudPolicyManager();
if (policy_manager) {
policy_manager->core()->store()->AddObserver(this);
// Ensure that we have up-to-date enterprise info in case enterprise policy
// is already fetched and has finished initialization.
UpdateEnterpriseInfo();
}
// Watch for changes to the reporting flags.
for (unsigned int i = 0; i < arraysize(kReportingFlags); ++i)
cros_settings_->AddSettingsObserver(kReportingFlags[i], this);
}
void VersionInfoUpdater::UpdateVersionLabel() {
if (version_text_.empty())
return;
chrome::VersionInfo version_info;
std::string label_text = l10n_util::GetStringFUTF8(
IDS_LOGIN_VERSION_LABEL_FORMAT,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
UTF8ToUTF16(version_info.Version()),
UTF8ToUTF16(version_text_));
// Workaround over incorrect width calculation in old fonts.
// TODO(glotov): remove the following line when new fonts are used.
label_text += ' ';
if (delegate_)
delegate_->OnOSVersionLabelTextUpdated(label_text);
}
void VersionInfoUpdater::UpdateEnterpriseInfo() {
SetEnterpriseInfo(
g_browser_process->browser_policy_connector()->GetEnterpriseDomain());
}
void VersionInfoUpdater::SetEnterpriseInfo(const std::string& domain_name) {
if (domain_name != enterprise_domain_text_) {
enterprise_domain_text_ = domain_name;
UpdateVersionLabel();
// Update the notification about device status reporting.
if (delegate_) {
std::string enterprise_info;
if (!domain_name.empty()) {
enterprise_info = l10n_util::GetStringFUTF8(
IDS_DEVICE_OWNED_BY_NOTICE,
UTF8ToUTF16(domain_name));
delegate_->OnEnterpriseInfoUpdated(enterprise_info);
}
}
}
}
void VersionInfoUpdater::OnVersion(const std::string& version) {
version_text_ = version;
UpdateVersionLabel();
}
void VersionInfoUpdater::OnBootTimesNoop(
const BootTimesLoader::BootTimes& boot_times) {}
void VersionInfoUpdater::OnBootTimes(
const BootTimesLoader::BootTimes& boot_times) {
const char* kBootTimesNoChromeExec =
"Non-firmware boot took %.2f seconds (kernel %.2fs, system %.2fs)";
const char* kBootTimesChromeExec =
"Non-firmware boot took %.2f seconds "
"(kernel %.2fs, system %.2fs, chrome %.2fs)";
std::string boot_times_text;
if (boot_times.chrome > 0) {
boot_times_text =
base::StringPrintf(
kBootTimesChromeExec,
boot_times.total,
boot_times.pre_startup,
boot_times.system,
boot_times.chrome);
} else {
boot_times_text =
base::StringPrintf(
kBootTimesNoChromeExec,
boot_times.total,
boot_times.pre_startup,
boot_times.system);
}
// Use UTF8ToWide once this string is localized.
if (delegate_)
delegate_->OnBootTimesLabelTextUpdated(boot_times_text);
}
void VersionInfoUpdater::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
UpdateEnterpriseInfo();
}
void VersionInfoUpdater::OnStoreLoaded(policy::CloudPolicyStore* store) {
UpdateEnterpriseInfo();
}
void VersionInfoUpdater::OnStoreError(policy::CloudPolicyStore* store) {
UpdateEnterpriseInfo();
}
void VersionInfoUpdater::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED)
UpdateEnterpriseInfo();
else
NOTREACHED();
}
} // namespace chromeos
| leiferikb/bitpop-private | chrome/browser/chromeos/login/version_info_updater.cc | C++ | bsd-3-clause | 7,139 |
// Copyright (c) 2016 Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "source/opt/fold.h"
#include <limits>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
#include "effcee/effcee.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "source/opt/build_module.h"
#include "source/opt/def_use_manager.h"
#include "source/opt/ir_context.h"
#include "source/opt/module.h"
#include "spirv-tools/libspirv.hpp"
#include "test/opt/pass_utils.h"
namespace spvtools {
namespace opt {
namespace {
using ::testing::Contains;
std::string Disassemble(const std::string& original, IRContext* context,
uint32_t disassemble_options = 0) {
std::vector<uint32_t> optimized_bin;
context->module()->ToBinary(&optimized_bin, true);
spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
SpirvTools tools(target_env);
std::string optimized_asm;
EXPECT_TRUE(
tools.Disassemble(optimized_bin, &optimized_asm, disassemble_options))
<< "Disassembling failed for shader:\n"
<< original << std::endl;
return optimized_asm;
}
void Match(const std::string& original, IRContext* context,
uint32_t disassemble_options = 0) {
std::string disassembly = Disassemble(original, context, disassemble_options);
auto match_result = effcee::Match(disassembly, original);
EXPECT_EQ(effcee::Result::Status::Ok, match_result.status())
<< match_result.message() << "\nChecking result:\n"
<< disassembly;
}
template <class ResultType>
struct InstructionFoldingCase {
InstructionFoldingCase(const std::string& tb, uint32_t id, ResultType result)
: test_body(tb), id_to_fold(id), expected_result(result) {}
std::string test_body;
uint32_t id_to_fold;
ResultType expected_result;
};
using IntegerInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<uint32_t>>;
TEST_P(IntegerInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_TRUE(succeeded);
if (inst != nullptr) {
EXPECT_EQ(inst->opcode(), SpvOpCopyObject);
inst = def_use_mgr->GetDef(inst->GetSingleWordInOperand(0));
EXPECT_EQ(inst->opcode(), SpvOpConstant);
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::IntConstant* result =
const_mrg->GetConstantFromInst(inst)->AsIntConstant();
EXPECT_NE(result, nullptr);
if (result != nullptr) {
EXPECT_EQ(result->GetU32BitValue(), tc.expected_result);
}
}
}
// Returns a common SPIR-V header for all of the test that follow.
#define INT_0_ID 100
#define TRUE_ID 101
#define VEC2_0_ID 102
#define INT_7_ID 103
#define FLOAT_0_ID 104
#define DOUBLE_0_ID 105
#define VEC4_0_ID 106
#define DVEC4_0_ID 106
#define HALF_0_ID 108
const std::string& Header() {
static const std::string header = R"(OpCapability Shader
OpCapability Float16
OpCapability Float64
OpCapability Int16
OpCapability Int64
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 140
OpName %main "main"
%void = OpTypeVoid
%void_func = OpTypeFunction %void
%bool = OpTypeBool
%float = OpTypeFloat 32
%double = OpTypeFloat 64
%half = OpTypeFloat 16
%101 = OpConstantTrue %bool ; Need a def with an numerical id to define id maps.
%true = OpConstantTrue %bool
%false = OpConstantFalse %bool
%bool_null = OpConstantNull %bool
%short = OpTypeInt 16 1
%int = OpTypeInt 32 1
%long = OpTypeInt 64 1
%uint = OpTypeInt 32 0
%v2int = OpTypeVector %int 2
%v4int = OpTypeVector %int 4
%v4float = OpTypeVector %float 4
%v4double = OpTypeVector %double 4
%v2float = OpTypeVector %float 2
%v2double = OpTypeVector %double 2
%v2half = OpTypeVector %half 2
%v2bool = OpTypeVector %bool 2
%struct_v2int_int_int = OpTypeStruct %v2int %int %int
%_ptr_int = OpTypePointer Function %int
%_ptr_uint = OpTypePointer Function %uint
%_ptr_bool = OpTypePointer Function %bool
%_ptr_float = OpTypePointer Function %float
%_ptr_double = OpTypePointer Function %double
%_ptr_half = OpTypePointer Function %half
%_ptr_long = OpTypePointer Function %long
%_ptr_v2int = OpTypePointer Function %v2int
%_ptr_v4int = OpTypePointer Function %v4int
%_ptr_v4float = OpTypePointer Function %v4float
%_ptr_v4double = OpTypePointer Function %v4double
%_ptr_struct_v2int_int_int = OpTypePointer Function %struct_v2int_int_int
%_ptr_v2float = OpTypePointer Function %v2float
%_ptr_v2double = OpTypePointer Function %v2double
%short_0 = OpConstant %short 0
%short_2 = OpConstant %short 2
%short_3 = OpConstant %short 3
%100 = OpConstant %int 0 ; Need a def with an numerical id to define id maps.
%103 = OpConstant %int 7 ; Need a def with an numerical id to define id maps.
%int_0 = OpConstant %int 0
%int_1 = OpConstant %int 1
%int_2 = OpConstant %int 2
%int_3 = OpConstant %int 3
%int_4 = OpConstant %int 4
%int_n24 = OpConstant %int -24
%int_min = OpConstant %int -2147483648
%int_max = OpConstant %int 2147483647
%long_0 = OpConstant %long 0
%long_2 = OpConstant %long 2
%long_3 = OpConstant %long 3
%uint_0 = OpConstant %uint 0
%uint_1 = OpConstant %uint 1
%uint_2 = OpConstant %uint 2
%uint_3 = OpConstant %uint 3
%uint_4 = OpConstant %uint 4
%uint_32 = OpConstant %uint 32
%uint_42 = OpConstant %uint 42
%uint_max = OpConstant %uint 4294967295
%v2int_undef = OpUndef %v2int
%v2int_0_0 = OpConstantComposite %v2int %int_0 %int_0
%v2int_1_0 = OpConstantComposite %v2int %int_1 %int_0
%v2int_2_2 = OpConstantComposite %v2int %int_2 %int_2
%v2int_2_3 = OpConstantComposite %v2int %int_2 %int_3
%v2int_3_2 = OpConstantComposite %v2int %int_3 %int_2
%v2int_4_4 = OpConstantComposite %v2int %int_4 %int_4
%v2bool_null = OpConstantNull %v2bool
%v2bool_true_false = OpConstantComposite %v2bool %true %false
%v2bool_false_true = OpConstantComposite %v2bool %false %true
%struct_v2int_int_int_null = OpConstantNull %struct_v2int_int_int
%v2int_null = OpConstantNull %v2int
%102 = OpConstantComposite %v2int %103 %103
%v4int_0_0_0_0 = OpConstantComposite %v4int %int_0 %int_0 %int_0 %int_0
%struct_undef_0_0 = OpConstantComposite %struct_v2int_int_int %v2int_undef %int_0 %int_0
%float_n1 = OpConstant %float -1
%104 = OpConstant %float 0 ; Need a def with an numerical id to define id maps.
%float_null = OpConstantNull %float
%float_0 = OpConstant %float 0
%float_1 = OpConstant %float 1
%float_2 = OpConstant %float 2
%float_3 = OpConstant %float 3
%float_4 = OpConstant %float 4
%float_2049 = OpConstant %float 2049
%float_n2049 = OpConstant %float -2049
%float_0p5 = OpConstant %float 0.5
%float_0p2 = OpConstant %float 0.2
%float_pi = OpConstant %float 1.5555
%float_1e16 = OpConstant %float 1e16
%float_n1e16 = OpConstant %float -1e16
%float_1en16 = OpConstant %float 1e-16
%float_n1en16 = OpConstant %float -1e-16
%v2float_0_0 = OpConstantComposite %v2float %float_0 %float_0
%v2float_2_2 = OpConstantComposite %v2float %float_2 %float_2
%v2float_2_3 = OpConstantComposite %v2float %float_2 %float_3
%v2float_3_2 = OpConstantComposite %v2float %float_3 %float_2
%v2float_4_4 = OpConstantComposite %v2float %float_4 %float_4
%v2float_2_0p5 = OpConstantComposite %v2float %float_2 %float_0p5
%v2float_0p2_0p5 = OpConstantComposite %v2float %float_0p2 %float_0p5
%v2float_null = OpConstantNull %v2float
%double_n1 = OpConstant %double -1
%105 = OpConstant %double 0 ; Need a def with an numerical id to define id maps.
%double_null = OpConstantNull %double
%double_0 = OpConstant %double 0
%double_1 = OpConstant %double 1
%double_2 = OpConstant %double 2
%double_3 = OpConstant %double 3
%double_4 = OpConstant %double 4
%double_5 = OpConstant %double 5
%double_0p5 = OpConstant %double 0.5
%double_0p2 = OpConstant %double 0.2
%v2double_0_0 = OpConstantComposite %v2double %double_0 %double_0
%v2double_2_2 = OpConstantComposite %v2double %double_2 %double_2
%v2double_2_3 = OpConstantComposite %v2double %double_2 %double_3
%v2double_3_2 = OpConstantComposite %v2double %double_3 %double_2
%v2double_4_4 = OpConstantComposite %v2double %double_4 %double_4
%v2double_2_0p5 = OpConstantComposite %v2double %double_2 %double_0p5
%v2double_null = OpConstantNull %v2double
%108 = OpConstant %half 0
%half_1 = OpConstant %half 1
%half_0_1 = OpConstantComposite %v2half %108 %half_1
%106 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0
%v4float_0_0_0_0 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0
%v4float_0_0_0_1 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_1
%v4float_0_1_0_0 = OpConstantComposite %v4float %float_0 %float_1 %float_null %float_0
%v4float_1_1_1_1 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%107 = OpConstantComposite %v4double %double_0 %double_0 %double_0 %double_0
%v4double_0_0_0_0 = OpConstantComposite %v4double %double_0 %double_0 %double_0 %double_0
%v4double_0_0_0_1 = OpConstantComposite %v4double %double_0 %double_0 %double_0 %double_1
%v4double_0_1_0_0 = OpConstantComposite %v4double %double_0 %double_1 %double_null %double_0
%v4double_1_1_1_1 = OpConstantComposite %v4double %double_1 %double_1 %double_1 %double_1
%v4double_1_1_1_0p5 = OpConstantComposite %v4double %double_1 %double_1 %double_1 %double_0p5
%v4double_null = OpConstantNull %v4double
%v4float_n1_2_1_3 = OpConstantComposite %v4float %float_n1 %float_2 %float_1 %float_3
)";
return header;
}
// Returns the header with definitions of float NaN and double NaN. Since FC
// "; CHECK: [[double_n0:%\\w+]] = OpConstant [[double]] -0\n" finds
// %double_nan = OpConstant %double -0x1.8p+1024 instead of
// %double_n0 = OpConstant %double -0,
// we separates those definitions from Header().
const std::string& HeaderWithNaN() {
static const std::string headerWithNaN =
Header() +
R"(%float_nan = OpConstant %float -0x1.8p+128
%double_nan = OpConstant %double -0x1.8p+1024
)";
return headerWithNaN;
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(TestCase, IntegerInstructionFoldingTest,
::testing::Values(
// Test case 0: fold 0*n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpIMul %int %int_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: fold n*0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpIMul %int %load %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 2: fold 0/n (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSDiv %int %int_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: fold n/0 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSDiv %int %load %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 4: fold 0/n (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpUDiv %uint %uint_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 5: fold n/0 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSDiv %int %load %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 6: fold 0 remainder n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSRem %int %int_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 7: fold n remainder 0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSRem %int %load %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 8: fold 0%n (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSMod %int %int_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 9: fold n%0 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSMod %int %load %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 10: fold 0%n (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpUMod %uint %uint_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 11: fold n%0 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpUMod %uint %load %uint_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 12: fold n << 32
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpShiftLeftLogical %uint %load %uint_32\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 13: fold n >> 32
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpShiftRightLogical %uint %load %uint_32\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 14: fold n | 0xFFFFFFFF
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpBitwiseOr %uint %load %uint_max\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0xFFFFFFFF),
// Test case 15: fold 0xFFFFFFFF | n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpBitwiseOr %uint %uint_max %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0xFFFFFFFF),
// Test case 16: fold n & 0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpBitwiseAnd %uint %load %uint_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 17: fold 1/0 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpSDiv %int %int_1 %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 18: fold 1/0 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpUDiv %uint %uint_1 %uint_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 19: fold OpSRem 1 0 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpSRem %int %int_1 %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 20: fold 1%0 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpSMod %int %int_1 %int_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 21: fold 1%0 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpUMod %uint %uint_1 %uint_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 22: fold unsigned n >> 42 (undefined, so set to zero).
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpShiftRightLogical %uint %load %uint_42\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 23: fold signed n >> 42 (undefined, so set to zero).
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpShiftRightLogical %int %load %uint_42\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 24: fold n << 42 (undefined, so set to zero).
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpShiftLeftLogical %int %load %uint_42\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 25: fold -24 >> 32 (defined as -1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpShiftRightArithmetic %int %int_n24 %uint_32\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, -1),
// Test case 26: fold 2 >> 32 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpShiftRightArithmetic %int %int_2 %uint_32\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 27: fold 2 >> 32 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpShiftRightLogical %int %int_2 %uint_32\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 28: fold 2 << 32
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpShiftLeftLogical %int %int_2 %uint_32\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 29: fold -INT_MIN
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpSNegate %int %int_min\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, std::numeric_limits<int32_t>::min()),
// Test case 30: fold UMin 3 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %uint %1 UMin %uint_3 %uint_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 31: fold UMin 4 2
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %uint %1 UMin %uint_4 %uint_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2),
// Test case 32: fold SMin 3 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %int %1 UMin %int_3 %int_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 33: fold SMin 4 2
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %int %1 SMin %int_4 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2),
// Test case 34: fold UMax 3 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %uint %1 UMax %uint_3 %uint_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4),
// Test case 35: fold UMax 3 2
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %uint %1 UMax %uint_3 %uint_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 36: fold SMax 3 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %int %1 UMax %int_3 %int_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4),
// Test case 37: fold SMax 3 2
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %int %1 SMax %int_3 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 38: fold UClamp 2 3 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %uint %1 UClamp %uint_2 %uint_3 %uint_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 39: fold UClamp 2 0 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %uint %1 UClamp %uint_2 %uint_0 %uint_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2),
// Test case 40: fold UClamp 2 0 1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %uint %1 UClamp %uint_2 %uint_0 %uint_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1),
// Test case 41: fold SClamp 2 3 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %int %1 SClamp %int_2 %int_3 %int_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 42: fold SClamp 2 0 4
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %int %1 SClamp %int_2 %int_0 %int_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2),
// Test case 43: fold SClamp 2 0 1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %int %1 SClamp %int_2 %int_0 %int_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1),
// Test case 44: SClamp 1 2 x
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %int\n" +
"%2 = OpExtInst %int %1 SClamp %int_1 %int_2 %undef\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2),
// Test case 45: SClamp 2 x 1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %int\n" +
"%2 = OpExtInst %int %1 SClamp %int_2 %undef %int_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1),
// Test case 44: UClamp 1 2 x
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %uint\n" +
"%2 = OpExtInst %uint %1 UClamp %uint_1 %uint_2 %undef\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2),
// Test case 45: UClamp 2 x 1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %uint\n" +
"%2 = OpExtInst %uint %1 UClamp %uint_2 %undef %uint_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1)
));
// clang-format on
using IntVectorInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<std::vector<uint32_t>>>;
TEST_P(IntVectorInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
SpvOp original_opcode = inst->opcode();
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_EQ(succeeded, inst == nullptr || inst->opcode() != original_opcode);
if (succeeded && inst != nullptr) {
EXPECT_EQ(inst->opcode(), SpvOpCopyObject);
inst = def_use_mgr->GetDef(inst->GetSingleWordInOperand(0));
std::vector<SpvOp> opcodes = {SpvOpConstantComposite};
EXPECT_THAT(opcodes, Contains(inst->opcode()));
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::Constant* result = const_mrg->GetConstantFromInst(inst);
EXPECT_NE(result, nullptr);
if (result != nullptr) {
const std::vector<const analysis::Constant*>& componenets =
result->AsVectorConstant()->GetComponents();
EXPECT_EQ(componenets.size(), tc.expected_result.size());
for (size_t i = 0; i < componenets.size(); i++) {
EXPECT_EQ(tc.expected_result[i], componenets[i]->GetU32());
}
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(TestCase, IntVectorInstructionFoldingTest,
::testing::Values(
// Test case 0: fold 0*n
InstructionFoldingCase<std::vector<uint32_t>>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpVectorShuffle %v2int %v2int_2_2 %v2int_2_3 0 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, {2,3}),
InstructionFoldingCase<std::vector<uint32_t>>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpVectorShuffle %v2int %v2int_null %v2int_2_3 0 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, {0,3}),
InstructionFoldingCase<std::vector<uint32_t>>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpVectorShuffle %v2int %v2int_null %v2int_2_3 4294967295 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, {0,0}),
InstructionFoldingCase<std::vector<uint32_t>>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpVectorShuffle %v2int %v2int_null %v2int_2_3 0 4294967295 \n" +
"OpReturn\n" +
"OpFunctionEnd",
2, {0,0})
));
// clang-format on
using FloatVectorInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<std::vector<float>>>;
TEST_P(FloatVectorInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
SpvOp original_opcode = inst->opcode();
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_EQ(succeeded, inst == nullptr || inst->opcode() != original_opcode);
if (succeeded && inst != nullptr) {
EXPECT_EQ(inst->opcode(), SpvOpCopyObject);
inst = def_use_mgr->GetDef(inst->GetSingleWordInOperand(0));
std::vector<SpvOp> opcodes = {SpvOpConstantComposite};
EXPECT_THAT(opcodes, Contains(inst->opcode()));
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::Constant* result = const_mrg->GetConstantFromInst(inst);
EXPECT_NE(result, nullptr);
if (result != nullptr) {
const std::vector<const analysis::Constant*>& componenets =
result->AsVectorConstant()->GetComponents();
EXPECT_EQ(componenets.size(), tc.expected_result.size());
for (size_t i = 0; i < componenets.size(); i++) {
EXPECT_EQ(tc.expected_result[i], componenets[i]->GetFloat());
}
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(TestCase, FloatVectorInstructionFoldingTest,
::testing::Values(
// Test case 0: FMix {2.0, 2.0}, {2.0, 3.0} {0.2,0.5}
InstructionFoldingCase<std::vector<float>>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %v2float %1 FMix %v2float_2_3 %v2float_0_0 %v2float_0p2_0p5\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, {1.6f,1.5f})
));
// clang-format on
using BooleanInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<bool>>;
TEST_P(BooleanInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_TRUE(succeeded);
if (inst != nullptr) {
EXPECT_EQ(inst->opcode(), SpvOpCopyObject);
inst = def_use_mgr->GetDef(inst->GetSingleWordInOperand(0));
std::vector<SpvOp> bool_opcodes = {SpvOpConstantTrue, SpvOpConstantFalse};
EXPECT_THAT(bool_opcodes, Contains(inst->opcode()));
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::BoolConstant* result =
const_mrg->GetConstantFromInst(inst)->AsBoolConstant();
EXPECT_NE(result, nullptr);
if (result != nullptr) {
EXPECT_EQ(result->value(), tc.expected_result);
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(TestCase, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold true || n
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%load = OpLoad %bool %n\n" +
"%2 = OpLogicalOr %bool %true %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 1: fold n || true
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%load = OpLoad %bool %n\n" +
"%2 = OpLogicalOr %bool %load %true\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold false && n
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%load = OpLoad %bool %n\n" +
"%2 = OpLogicalAnd %bool %false %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 3: fold n && false
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%load = OpLoad %bool %n\n" +
"%2 = OpLogicalAnd %bool %load %false\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 4: fold n < 0 (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpULessThan %bool %load %uint_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 5: fold UINT_MAX < n (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpULessThan %bool %uint_max %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 6: fold INT_MAX < n (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSLessThan %bool %int_max %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 7: fold n < INT_MIN (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSLessThan %bool %load %int_min\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 8: fold 0 > n (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpUGreaterThan %bool %uint_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 9: fold n > UINT_MAX (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpUGreaterThan %bool %load %uint_max\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 10: fold n > INT_MAX (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSGreaterThan %bool %load %int_max\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 11: fold INT_MIN > n (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpSGreaterThan %bool %int_min %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 12: fold 0 <= n (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpULessThanEqual %bool %uint_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 13: fold n <= UINT_MAX (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpULessThanEqual %bool %load %uint_max\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 14: fold INT_MIN <= n (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSLessThanEqual %bool %int_min %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 15: fold n <= INT_MAX (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSLessThanEqual %bool %load %int_max\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 16: fold n >= 0 (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpUGreaterThanEqual %bool %load %uint_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 17: fold UINT_MAX >= n (unsigned)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load = OpLoad %uint %n\n" +
"%2 = OpUGreaterThanEqual %bool %uint_max %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 18: fold n >= INT_MIN (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSGreaterThanEqual %bool %load %int_min\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 19: fold INT_MAX >= n (signed)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSGreaterThanEqual %bool %int_max %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
INSTANTIATE_TEST_SUITE_P(FClampAndCmpLHS, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold 0.0 > clamp(n, 0.0, 1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFOrdGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold 0.0 > clamp(n, -1.0, -1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_n1\n" +
"%2 = OpFOrdGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold 0.0 >= clamp(n, 1, 2)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFOrdGreaterThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 3: fold 0.0 >= clamp(n, -1.0, 0.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFOrdGreaterThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 4: fold 0.0 <= clamp(n, 0.0, 1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFOrdLessThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 5: fold 0.0 <= clamp(n, -1.0, -1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_n1\n" +
"%2 = OpFOrdLessThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 6: fold 0.0 < clamp(n, 1, 2)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFOrdLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 7: fold 0.0 < clamp(n, -1.0, 0.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFOrdLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 8: fold 0.0 > clamp(n, 0.0, 1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFUnordGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 9: fold 0.0 > clamp(n, -1.0, -1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_n1\n" +
"%2 = OpFUnordGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 10: fold 0.0 >= clamp(n, 1, 2)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFUnordGreaterThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 11: fold 0.0 >= clamp(n, -1.0, 0.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFUnordGreaterThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 12: fold 0.0 <= clamp(n, 0.0, 1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFUnordLessThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 13: fold 0.0 <= clamp(n, -1.0, -1.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_n1\n" +
"%2 = OpFUnordLessThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 14: fold 0.0 < clamp(n, 1, 2)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFUnordLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 15: fold 0.0 < clamp(n, -1.0, 0.0)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFUnordLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false)
));
INSTANTIATE_TEST_SUITE_P(FClampAndCmpRHS, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold clamp(n, 0.0, 1.0) > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFOrdGreaterThan %bool %clamp %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold clamp(n, 1.0, 1.0) > 0.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_1\n" +
"%2 = OpFOrdGreaterThan %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold clamp(n, 1, 2) >= 0.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFOrdGreaterThanEqual %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 3: fold clamp(n, 1.0, 2.0) >= 3.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFOrdGreaterThanEqual %bool %clamp %float_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 4: fold clamp(n, 0.0, 1.0) <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFOrdLessThanEqual %bool %clamp %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 5: fold clamp(n, 1.0, 2.0) <= 0.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFOrdLessThanEqual %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 6: fold clamp(n, 1, 2) < 3
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFOrdLessThan %bool %clamp %float_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 7: fold clamp(n, -1.0, 0.0) < -1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFOrdLessThan %bool %clamp %float_n1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 8: fold clamp(n, 0.0, 1.0) > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFUnordGreaterThan %bool %clamp %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 9: fold clamp(n, 1.0, 2.0) > 0.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFUnordGreaterThan %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 10: fold clamp(n, 1, 2) >= 3.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFUnordGreaterThanEqual %bool %clamp %float_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 11: fold clamp(n, -1.0, 0.0) >= -1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFUnordGreaterThanEqual %bool %clamp %float_n1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 12: fold clamp(n, 0.0, 1.0) <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFUnordLessThanEqual %bool %clamp %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 13: fold clamp(n, 1.0, 1.0) <= 0.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_1\n" +
"%2 = OpFUnordLessThanEqual %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 14: fold clamp(n, 1, 2) < 3
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_1 %float_2\n" +
"%2 = OpFUnordLessThan %bool %clamp %float_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 15: fold clamp(n, -1.0, 0.0) < -1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFUnordLessThan %bool %clamp %float_n1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 16: fold clamp(n, -1.0, 0.0) < -1.0 (one test for double)
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%ld = OpLoad %double %n\n" +
"%clamp = OpExtInst %double %1 FClamp %ld %double_n1 %double_0\n" +
"%2 = OpFUnordLessThan %bool %clamp %double_n1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false)
));
// clang-format on
using FloatInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<float>>;
TEST_P(FloatInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_TRUE(succeeded);
if (inst != nullptr) {
EXPECT_EQ(inst->opcode(), SpvOpCopyObject);
inst = def_use_mgr->GetDef(inst->GetSingleWordInOperand(0));
EXPECT_EQ(inst->opcode(), SpvOpConstant);
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::FloatConstant* result =
const_mrg->GetConstantFromInst(inst)->AsFloatConstant();
EXPECT_NE(result, nullptr);
if (result != nullptr) {
if (!std::isnan(tc.expected_result)) {
EXPECT_EQ(result->GetFloatValue(), tc.expected_result);
} else {
EXPECT_TRUE(std::isnan(result->GetFloatValue()));
}
}
}
}
// Not testing NaNs because there are no expectations concerning NaNs according
// to the "Precision and Operation of SPIR-V Instructions" section of the Vulkan
// specification.
// clang-format off
INSTANTIATE_TEST_SUITE_P(FloatConstantFoldingTest, FloatInstructionFoldingTest,
::testing::Values(
// Test case 0: Fold 2.0 - 1.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFSub %float %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 1: Fold 2.0 + 1.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFAdd %float %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3.0),
// Test case 2: Fold 3.0 * 2.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFMul %float %float_3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 6.0),
// Test case 3: Fold 1.0 / 2.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFDiv %float %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.5),
// Test case 4: Fold 1.0 / 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFDiv %float %float_1 %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, std::numeric_limits<float>::infinity()),
// Test case 5: Fold -1.0 / 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFDiv %float %float_n1 %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, -std::numeric_limits<float>::infinity()),
// Test case 6: Fold (2.0, 3.0) dot (2.0, 0.5)
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpDot %float %v2float_2_3 %v2float_2_0p5\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 5.5f),
// Test case 7: Fold (0.0, 0.0) dot v
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %v\n" +
"%3 = OpDot %float %v2float_0_0 %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 8: Fold v dot (0.0, 0.0)
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %v\n" +
"%3 = OpDot %float %2 %v2float_0_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 9: Fold Null dot v
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %v\n" +
"%3 = OpDot %float %v2float_null %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 10: Fold v dot Null
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %v\n" +
"%3 = OpDot %float %2 %v2float_null\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 11: Fold -2.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFNegate %float %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, -2),
// Test case 12: QuantizeToF16 1.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 13: QuantizeToF16 positive non exact
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_2049\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2048),
// Test case 14: QuantizeToF16 negative non exact
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_n2049\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, -2048),
// Test case 15: QuantizeToF16 large positive
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_1e16\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, std::numeric_limits<float>::infinity()),
// Test case 16: QuantizeToF16 large negative
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_n1e16\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, -std::numeric_limits<float>::infinity()),
// Test case 17: QuantizeToF16 small positive
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_1en16\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 18: QuantizeToF16 small negative
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_n1en16\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 19: QuantizeToF16 nan
InstructionFoldingCase<float>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpQuantizeToF16 %float %float_nan\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, std::numeric_limits<float>::quiet_NaN()),
// Test case 20: FMix 1.0 4.0 0.2
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FMix %float_1 %float_4 %float_0p2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.6f),
// Test case 21: FMin 1.0 4.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FMin %float_1 %float_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0f),
// Test case 22: FMin 4.0 0.2
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FMin %float_4 %float_0p2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.2f),
// Test case 23: FMax 1.0 4.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FMax %float_1 %float_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4.0f),
// Test case 24: FMax 1.0 0.2
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FMax %float_1 %float_0p2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0f),
// Test case 25: FClamp 1.0 0.2 4.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FClamp %float_1 %float_0p2 %float_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0f),
// Test case 26: FClamp 0.2 2.0 4.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FClamp %float_0p2 %float_2 %float_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2.0f),
// Test case 27: FClamp 2049.0 2.0 4.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 FClamp %float_2049 %float_2 %float_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4.0f),
// Test case 28: FClamp 1.0 2.0 x
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %float\n" +
"%2 = OpExtInst %float %1 FClamp %float_1 %float_2 %undef\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2.0),
// Test case 29: FClamp 1.0 x 0.5
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %float\n" +
"%2 = OpExtInst %float %1 FClamp %float_1 %undef %float_0p5\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.5),
// Test case 30: Sin 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Sin %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 31: Cos 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Cos %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 32: Tan 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Tan %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 33: Asin 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Asin %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 34: Acos 1.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Acos %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 35: Atan 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Atan %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 36: Exp 0.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Exp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 37: Log 1.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Log %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 38: Exp2 2.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Exp2 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4.0),
// Test case 39: Log2 4.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Log2 %float_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2.0),
// Test case 40: Sqrt 4.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Sqrt %float_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2.0),
// Test case 41: Atan2 0.0 1.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Atan2 %float_0 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.0),
// Test case 42: Pow 2.0 3.0
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %float %1 Pow %float_2 %float_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 8.0)
));
// clang-format on
using DoubleInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<double>>;
TEST_P(DoubleInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_TRUE(succeeded);
if (inst != nullptr) {
EXPECT_EQ(inst->opcode(), SpvOpCopyObject);
inst = def_use_mgr->GetDef(inst->GetSingleWordInOperand(0));
EXPECT_EQ(inst->opcode(), SpvOpConstant);
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::FloatConstant* result =
const_mrg->GetConstantFromInst(inst)->AsFloatConstant();
EXPECT_NE(result, nullptr);
if (result != nullptr) {
EXPECT_EQ(result->GetDoubleValue(), tc.expected_result);
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(DoubleConstantFoldingTest, DoubleInstructionFoldingTest,
::testing::Values(
// Test case 0: Fold 2.0 - 1.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFSub %double %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 1: Fold 2.0 + 1.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFAdd %double %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3.0),
// Test case 2: Fold 3.0 * 2.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFMul %double %double_3 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 6.0),
// Test case 3: Fold 1.0 / 2.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFDiv %double %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.5),
// Test case 4: Fold 1.0 / 0.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFDiv %double %double_1 %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, std::numeric_limits<double>::infinity()),
// Test case 5: Fold -1.0 / 0.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFDiv %double %double_n1 %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, -std::numeric_limits<double>::infinity()),
// Test case 6: Fold (2.0, 3.0) dot (2.0, 0.5)
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpDot %double %v2double_2_3 %v2double_2_0p5\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 5.5f),
// Test case 7: Fold (0.0, 0.0) dot v
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2double Function\n" +
"%2 = OpLoad %v2double %v\n" +
"%3 = OpDot %double %v2double_0_0 %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 8: Fold v dot (0.0, 0.0)
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2double Function\n" +
"%2 = OpLoad %v2double %v\n" +
"%3 = OpDot %double %2 %v2double_0_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 9: Fold Null dot v
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2double Function\n" +
"%2 = OpLoad %v2double %v\n" +
"%3 = OpDot %double %v2double_null %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 10: Fold v dot Null
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%v = OpVariable %_ptr_v2double Function\n" +
"%2 = OpLoad %v2double %v\n" +
"%3 = OpDot %double %2 %v2double_null\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0.0f),
// Test case 11: Fold -2.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFNegate %double %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, -2),
// Test case 12: FMin 1.0 4.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %double %1 FMin %double_1 %double_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 13: FMin 4.0 0.2
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %double %1 FMin %double_4 %double_0p2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.2),
// Test case 14: FMax 1.0 4.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %double %1 FMax %double_1 %double_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4.0),
// Test case 15: FMax 1.0 0.2
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %double %1 FMax %double_1 %double_0p2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 16: FClamp 1.0 0.2 4.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %double %1 FClamp %double_1 %double_0p2 %double_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 1.0),
// Test case 17: FClamp 0.2 2.0 4.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %double %1 FClamp %double_0p2 %double_2 %double_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2.0),
// Test case 18: FClamp 5.0 2.0 4.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpExtInst %double %1 FClamp %double_5 %double_2 %double_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4.0),
// Test case 19: FClamp 1.0 2.0 x
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %double\n" +
"%2 = OpExtInst %double %1 FClamp %double_1 %double_2 %undef\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2.0),
// Test case 20: FClamp 1.0 x 0.5
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %double\n" +
"%2 = OpExtInst %double %1 FClamp %double_1 %undef %double_0p5\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0.5),
// Test case 21: Sqrt 4.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %double\n" +
"%2 = OpExtInst %double %1 Sqrt %double_4\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 2.0),
// Test case 22: Pow 2.0 3.0
InstructionFoldingCase<double>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%undef = OpUndef %double\n" +
"%2 = OpExtInst %double %1 Pow %double_2 %double_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 8.0)
));
// clang-format on
// clang-format off
INSTANTIATE_TEST_SUITE_P(DoubleOrderedCompareConstantFoldingTest, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold 1.0 == 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold 1.0 != 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdNotEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold 1.0 < 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThan %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 3: fold 1.0 > 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThan %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 4: fold 1.0 <= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThanEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 5: fold 1.0 >= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThanEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 6: fold 1.0 == 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 7: fold 1.0 != 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdNotEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 8: fold 1.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThan %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 9: fold 1.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThan %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 10: fold 1.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThanEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 11: fold 1.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThanEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 12: fold 2.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThan %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 13: fold 2.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThan %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 14: fold 2.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThanEqual %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 15: fold 2.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThanEqual %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
INSTANTIATE_TEST_SUITE_P(DoubleUnorderedCompareConstantFoldingTest, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold 1.0 == 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold 1.0 != 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordNotEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold 1.0 < 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThan %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 3: fold 1.0 > 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThan %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 4: fold 1.0 <= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThanEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 5: fold 1.0 >= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThanEqual %bool %double_1 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 6: fold 1.0 == 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 7: fold 1.0 != 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordNotEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 8: fold 1.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThan %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 9: fold 1.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThan %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 10: fold 1.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThanEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 11: fold 1.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThanEqual %bool %double_1 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 12: fold 2.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThan %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 13: fold 2.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThan %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 14: fold 2.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThanEqual %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 15: fold 2.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThanEqual %bool %double_2 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
INSTANTIATE_TEST_SUITE_P(FloatOrderedCompareConstantFoldingTest, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold 1.0 == 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold 1.0 != 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdNotEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold 1.0 < 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThan %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 3: fold 1.0 > 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThan %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 4: fold 1.0 <= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThanEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 5: fold 1.0 >= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThanEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 6: fold 1.0 == 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 7: fold 1.0 != 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdNotEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 8: fold 1.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThan %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 9: fold 1.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThan %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 10: fold 1.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThanEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 11: fold 1.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThanEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 12: fold 2.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThan %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 13: fold 2.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThan %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 14: fold 2.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdLessThanEqual %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 15: fold 2.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdGreaterThanEqual %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
INSTANTIATE_TEST_SUITE_P(FloatUnorderedCompareConstantFoldingTest, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold 1.0 == 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold 1.0 != 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordNotEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold 1.0 < 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThan %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 3: fold 1.0 > 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThan %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 4: fold 1.0 <= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThanEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 5: fold 1.0 >= 2.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThanEqual %bool %float_1 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 6: fold 1.0 == 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 7: fold 1.0 != 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordNotEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 8: fold 1.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThan %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 9: fold 1.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThan %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 10: fold 1.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThanEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 11: fold 1.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThanEqual %bool %float_1 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 12: fold 2.0 < 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThan %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 13: fold 2.0 > 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThan %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 14: fold 2.0 <= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordLessThanEqual %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 15: fold 2.0 >= 1.0
InstructionFoldingCase<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordGreaterThanEqual %bool %float_2 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
INSTANTIATE_TEST_SUITE_P(DoubleNaNCompareConstantFoldingTest, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold NaN == 0 (ord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdEqual %bool %double_nan %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold NaN == NaN (unord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordEqual %bool %double_nan %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold NaN != NaN (ord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdNotEqual %bool %double_nan %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 3: fold NaN != NaN (unord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordNotEqual %bool %double_nan %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
INSTANTIATE_TEST_SUITE_P(FloatNaNCompareConstantFoldingTest, BooleanInstructionFoldingTest,
::testing::Values(
// Test case 0: fold NaN == 0 (ord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdEqual %bool %float_nan %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 1: fold NaN == NaN (unord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordEqual %bool %float_nan %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: fold NaN != NaN (ord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFOrdNotEqual %bool %float_nan %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, false),
// Test case 3: fold NaN != NaN (unord)
InstructionFoldingCase<bool>(
HeaderWithNaN() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFUnordNotEqual %bool %float_nan %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
// clang-format on
template <class ResultType>
struct InstructionFoldingCaseWithMap {
InstructionFoldingCaseWithMap(const std::string& tb, uint32_t id,
ResultType result,
std::function<uint32_t(uint32_t)> map)
: test_body(tb), id_to_fold(id), expected_result(result), id_map(map) {}
std::string test_body;
uint32_t id_to_fold;
ResultType expected_result;
std::function<uint32_t(uint32_t)> id_map;
};
using IntegerInstructionFoldingTestWithMap =
::testing::TestWithParam<InstructionFoldingCaseWithMap<uint32_t>>;
TEST_P(IntegerInstructionFoldingTestWithMap, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
inst = context->get_instruction_folder().FoldInstructionToConstant(inst,
tc.id_map);
// Make sure the instruction folded as expected.
EXPECT_NE(inst, nullptr);
if (inst != nullptr) {
EXPECT_EQ(inst->opcode(), SpvOpConstant);
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::IntConstant* result =
const_mrg->GetConstantFromInst(inst)->AsIntConstant();
EXPECT_NE(result, nullptr);
if (result != nullptr) {
EXPECT_EQ(result->GetU32BitValue(), tc.expected_result);
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(TestCase, IntegerInstructionFoldingTestWithMap,
::testing::Values(
// Test case 0: fold %3 = 0; %3 * n
InstructionFoldingCaseWithMap<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%3 = OpCopyObject %int %int_0\n"
"%2 = OpIMul %int %3 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0, [](uint32_t id) {return (id == 3 ? INT_0_ID : id);})
));
// clang-format on
using BooleanInstructionFoldingTestWithMap =
::testing::TestWithParam<InstructionFoldingCaseWithMap<bool>>;
TEST_P(BooleanInstructionFoldingTestWithMap, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
inst = context->get_instruction_folder().FoldInstructionToConstant(inst,
tc.id_map);
// Make sure the instruction folded as expected.
EXPECT_NE(inst, nullptr);
if (inst != nullptr) {
std::vector<SpvOp> bool_opcodes = {SpvOpConstantTrue, SpvOpConstantFalse};
EXPECT_THAT(bool_opcodes, Contains(inst->opcode()));
analysis::ConstantManager* const_mrg = context->get_constant_mgr();
const analysis::BoolConstant* result =
const_mrg->GetConstantFromInst(inst)->AsBoolConstant();
EXPECT_NE(result, nullptr);
if (result != nullptr) {
EXPECT_EQ(result->value(), tc.expected_result);
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(TestCase, BooleanInstructionFoldingTestWithMap,
::testing::Values(
// Test case 0: fold %3 = true; %3 || n
InstructionFoldingCaseWithMap<bool>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%load = OpLoad %bool %n\n" +
"%3 = OpCopyObject %bool %true\n" +
"%2 = OpLogicalOr %bool %3 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true, [](uint32_t id) {return (id == 3 ? TRUE_ID : id);})
));
// clang-format on
using GeneralInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<uint32_t>>;
TEST_P(GeneralInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
std::unique_ptr<Instruction> original_inst(inst->Clone(context.get()));
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_EQ(inst->result_id(), original_inst->result_id());
EXPECT_EQ(inst->type_id(), original_inst->type_id());
EXPECT_TRUE((!succeeded) == (tc.expected_result == 0));
if (succeeded) {
EXPECT_EQ(inst->opcode(), SpvOpCopyObject);
EXPECT_EQ(inst->GetSingleWordInOperand(0), tc.expected_result);
} else {
EXPECT_EQ(inst->NumInOperands(), original_inst->NumInOperands());
for (uint32_t i = 0; i < inst->NumInOperands(); ++i) {
EXPECT_EQ(inst->GetOperand(i), original_inst->GetOperand(i));
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(IntegerArithmeticTestCases, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't fold n * m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpIMul %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Don't fold n / m (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpUDiv %uint %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 2: Don't fold n / m (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpSDiv %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: Don't fold n remainder m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpSRem %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 4: Don't fold n % m (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpSMod %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 5: Don't fold n % m (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpUMod %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 6: Don't fold n << m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpShiftRightLogical %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 7: Don't fold n >> m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpShiftLeftLogical %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 8: Don't fold n | m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpBitwiseOr %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 9: Don't fold n & m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpBitwiseAnd %int %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 10: Don't fold n < m (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpULessThan %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 11: Don't fold n > m (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpUGreaterThan %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 12: Don't fold n <= m (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpULessThanEqual %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 13: Don't fold n >= m (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%m = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%load_m = OpLoad %uint %m\n" +
"%2 = OpUGreaterThanEqual %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 14: Don't fold n < m (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpULessThan %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 15: Don't fold n > m (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpUGreaterThan %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 16: Don't fold n <= m (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpULessThanEqual %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 17: Don't fold n >= m (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%m = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%load_m = OpLoad %int %m\n" +
"%2 = OpUGreaterThanEqual %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 18: Don't fold n || m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%m = OpVariable %_ptr_bool Function\n" +
"%load_n = OpLoad %bool %n\n" +
"%load_m = OpLoad %bool %m\n" +
"%2 = OpLogicalOr %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 19: Don't fold n && m
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%m = OpVariable %_ptr_bool Function\n" +
"%load_n = OpLoad %bool %n\n" +
"%load_m = OpLoad %bool %m\n" +
"%2 = OpLogicalAnd %bool %load_n %load_m\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 20: Don't fold n * 3
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpIMul %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 21: Don't fold n / 3 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpUDiv %uint %load_n %uint_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 22: Don't fold n / 3 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpSDiv %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 23: Don't fold n remainder 3
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpSRem %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 24: Don't fold n % 3 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpSMod %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 25: Don't fold n % 3 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpUMod %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 26: Don't fold n << 3
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpShiftRightLogical %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 27: Don't fold n >> 3
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpShiftLeftLogical %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 28: Don't fold n | 3
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpBitwiseOr %int %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 29: Don't fold n & 3
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpBitwiseAnd %uint %load_n %uint_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 30: Don't fold n < 3 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpULessThan %bool %load_n %uint_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 31: Don't fold n > 3 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpUGreaterThan %bool %load_n %uint_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 32: Don't fold n <= 3 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpULessThanEqual %bool %load_n %uint_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 33: Don't fold n >= 3 (unsigned)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%load_n = OpLoad %uint %n\n" +
"%2 = OpUGreaterThanEqual %bool %load_n %uint_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 34: Don't fold n < 3 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpULessThan %bool %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 35: Don't fold n > 3 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpUGreaterThan %bool %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 36: Don't fold n <= 3 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpULessThanEqual %bool %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 37: Don't fold n >= 3 (signed)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load_n = OpLoad %int %n\n" +
"%2 = OpUGreaterThanEqual %bool %load_n %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 38: Don't fold 2 + 3 (long), bad length
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpIAdd %long %long_2 %long_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 39: Don't fold 2 + 3 (short), bad length
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpIAdd %short %short_2 %short_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 40: fold 1*n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%3 = OpLoad %int %n\n" +
"%2 = OpIMul %int %int_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 41: fold n*1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%3 = OpLoad %int %n\n" +
"%2 = OpIMul %int %3 %int_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3)
));
INSTANTIATE_TEST_SUITE_P(CompositeExtractFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: fold Insert feeding extract
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %n\n" +
"%3 = OpCompositeInsert %v4int %2 %v4int_0_0_0_0 0\n" +
"%4 = OpCompositeInsert %v4int %int_1 %3 1\n" +
"%5 = OpCompositeInsert %v4int %int_1 %4 2\n" +
"%6 = OpCompositeInsert %v4int %int_1 %5 3\n" +
"%7 = OpCompositeExtract %int %6 0\n" +
"OpReturn\n" +
"OpFunctionEnd",
7, 2),
// Test case 1: fold Composite construct feeding extract (position 0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %n\n" +
"%3 = OpCompositeConstruct %v4int %2 %int_0 %int_0 %int_0\n" +
"%4 = OpCompositeExtract %int %3 0\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, 2),
// Test case 2: fold Composite construct feeding extract (position 3)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %n\n" +
"%3 = OpCompositeConstruct %v4int %2 %int_0 %int_0 %100\n" +
"%4 = OpCompositeExtract %int %3 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, INT_0_ID),
// Test case 3: fold Composite construct with vectors feeding extract (scalar element)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %n\n" +
"%3 = OpCompositeConstruct %v2int %2 %int_0\n" +
"%4 = OpCompositeConstruct %v4int %3 %int_0 %100\n" +
"%5 = OpCompositeExtract %int %4 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, INT_0_ID),
// Test case 4: fold Composite construct with vectors feeding extract (start of vector element)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %n\n" +
"%3 = OpCompositeConstruct %v2int %2 %int_0\n" +
"%4 = OpCompositeConstruct %v4int %3 %int_0 %100\n" +
"%5 = OpCompositeExtract %int %4 0\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, 2),
// Test case 5: fold Composite construct with vectors feeding extract (middle of vector element)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %n\n" +
"%3 = OpCompositeConstruct %v2int %int_0 %2\n" +
"%4 = OpCompositeConstruct %v4int %3 %int_0 %100\n" +
"%5 = OpCompositeExtract %int %4 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, 2),
// Test case 6: fold Composite construct with multiple indices.
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %n\n" +
"%3 = OpCompositeConstruct %v2int %int_0 %2\n" +
"%4 = OpCompositeConstruct %struct_v2int_int_int %3 %int_0 %100\n" +
"%5 = OpCompositeExtract %int %4 0 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, 2),
// Test case 7: fold constant extract.
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpCompositeExtract %int %102 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, INT_7_ID),
// Test case 8: constant struct has OpUndef
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpCompositeExtract %int %struct_undef_0_0 0 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 9: Extracting a member of element inserted via Insert
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_struct_v2int_int_int Function\n" +
"%2 = OpLoad %struct_v2int_int_int %n\n" +
"%3 = OpCompositeInsert %struct_v2int_int_int %102 %2 0\n" +
"%4 = OpCompositeExtract %int %3 0 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, 103),
// Test case 10: Extracting a element that is partially changed by Insert. (Don't fold)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_struct_v2int_int_int Function\n" +
"%2 = OpLoad %struct_v2int_int_int %n\n" +
"%3 = OpCompositeInsert %struct_v2int_int_int %int_0 %2 0 1\n" +
"%4 = OpCompositeExtract %v2int %3 0\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, 0),
// Test case 11: Extracting from result of vector shuffle (first input)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%2 = OpLoad %v2int %n\n" +
"%3 = OpVectorShuffle %v2int %102 %2 3 0\n" +
"%4 = OpCompositeExtract %int %3 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, INT_7_ID),
// Test case 12: Extracting from result of vector shuffle (second input)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%2 = OpLoad %v2int %n\n" +
"%3 = OpVectorShuffle %v2int %2 %102 2 0\n" +
"%4 = OpCompositeExtract %int %3 0\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, INT_7_ID),
// Test case 13: https://github.com/KhronosGroup/SPIRV-Tools/issues/2608
// Out of bounds access. Do not fold.
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1\n" +
"%3 = OpCompositeExtract %float %2 4\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 0)
));
INSTANTIATE_TEST_SUITE_P(CompositeConstructFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: fold Extracts feeding construct
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpCopyObject %v4int %v4int_0_0_0_0\n" +
"%3 = OpCompositeExtract %int %2 0\n" +
"%4 = OpCompositeExtract %int %2 1\n" +
"%5 = OpCompositeExtract %int %2 2\n" +
"%6 = OpCompositeExtract %int %2 3\n" +
"%7 = OpCompositeConstruct %v4int %3 %4 %5 %6\n" +
"OpReturn\n" +
"OpFunctionEnd",
7, 2),
// Test case 1: Don't fold Extracts feeding construct (Different source)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpCopyObject %v4int %v4int_0_0_0_0\n" +
"%3 = OpCompositeExtract %int %2 0\n" +
"%4 = OpCompositeExtract %int %2 1\n" +
"%5 = OpCompositeExtract %int %2 2\n" +
"%6 = OpCompositeExtract %int %v4int_0_0_0_0 3\n" +
"%7 = OpCompositeConstruct %v4int %3 %4 %5 %6\n" +
"OpReturn\n" +
"OpFunctionEnd",
7, 0),
// Test case 2: Don't fold Extracts feeding construct (bad indices)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpCopyObject %v4int %v4int_0_0_0_0\n" +
"%3 = OpCompositeExtract %int %2 0\n" +
"%4 = OpCompositeExtract %int %2 0\n" +
"%5 = OpCompositeExtract %int %2 2\n" +
"%6 = OpCompositeExtract %int %2 3\n" +
"%7 = OpCompositeConstruct %v4int %3 %4 %5 %6\n" +
"OpReturn\n" +
"OpFunctionEnd",
7, 0),
// Test case 3: Don't fold Extracts feeding construct (different type)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpCopyObject %struct_v2int_int_int %struct_v2int_int_int_null\n" +
"%3 = OpCompositeExtract %v2int %2 0\n" +
"%4 = OpCompositeExtract %int %2 1\n" +
"%5 = OpCompositeExtract %int %2 2\n" +
"%7 = OpCompositeConstruct %v4int %3 %4 %5\n" +
"OpReturn\n" +
"OpFunctionEnd",
7, 0),
// Test case 4: Fold construct with constants to constant.
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpCompositeConstruct %v2int %103 %103\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, VEC2_0_ID),
// Test case 5: Don't segfault when trying to fold an OpCompositeConstruct
// for an empty struct, and we reached the id limit.
InstructionFoldingCase<uint32_t>(
Header() + "%empty_struct = OpTypeStruct\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%4194303 = OpCompositeConstruct %empty_struct\n" +
"OpReturn\n" +
"OpFunctionEnd",
4194303, 0)
));
INSTANTIATE_TEST_SUITE_P(PhiFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Fold phi with the same values for all edges.
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
" OpBranchConditional %true %l1 %l2\n" +
"%l1 = OpLabel\n" +
" OpBranch %merge_lab\n" +
"%l2 = OpLabel\n" +
" OpBranch %merge_lab\n" +
"%merge_lab = OpLabel\n" +
"%2 = OpPhi %int %100 %l1 %100 %l2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, INT_0_ID),
// Test case 1: Fold phi in pass through loop.
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
" OpBranch %l1\n" +
"%l1 = OpLabel\n" +
"%2 = OpPhi %int %100 %main_lab %2 %l1\n" +
" OpBranchConditional %true %l1 %merge_lab\n" +
"%merge_lab = OpLabel\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, INT_0_ID),
// Test case 2: Don't Fold phi because of different values.
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
" OpBranch %l1\n" +
"%l1 = OpLabel\n" +
"%2 = OpPhi %int %int_0 %main_lab %int_3 %l1\n" +
" OpBranchConditional %true %l1 %merge_lab\n" +
"%merge_lab = OpLabel\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0)
));
INSTANTIATE_TEST_SUITE_P(FloatRedundantFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't fold n + 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFAdd %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Don't fold n - 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFSub %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 2: Don't fold n * 2.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFMul %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: Fold n + 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFAdd %float %3 %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 4: Fold 0.0 + n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFAdd %float %float_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 5: Fold n - 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFSub %float %3 %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 6: Fold n * 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFMul %float %3 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 7: Fold 1.0 * n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFMul %float %float_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 8: Fold n / 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFDiv %float %3 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 9: Fold n * 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFMul %float %3 %104\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, FLOAT_0_ID),
// Test case 10: Fold 0.0 * n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFMul %float %104 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, FLOAT_0_ID),
// Test case 11: Fold 0.0 / n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFDiv %float %104 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, FLOAT_0_ID),
// Test case 12: Don't fold mix(a, b, 2.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_float Function\n" +
"%b = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %a\n" +
"%4 = OpLoad %float %b\n" +
"%2 = OpExtInst %float %1 FMix %3 %4 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 13: Fold mix(a, b, 0.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_float Function\n" +
"%b = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %a\n" +
"%4 = OpLoad %float %b\n" +
"%2 = OpExtInst %float %1 FMix %3 %4 %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 14: Fold mix(a, b, 1.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_float Function\n" +
"%b = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %a\n" +
"%4 = OpLoad %float %b\n" +
"%2 = OpExtInst %float %1 FMix %3 %4 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4),
// Test case 15: Fold vector fadd with null
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %a\n" +
"%3 = OpFAdd %v2float %2 %v2float_null\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 2),
// Test case 16: Fold vector fadd with null
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %a\n" +
"%3 = OpFAdd %v2float %v2float_null %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 2),
// Test case 17: Fold vector fsub with null
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %a\n" +
"%3 = OpFSub %v2float %2 %v2float_null\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, 2),
// Test case 18: Fold 0.0(half) * n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_half Function\n" +
"%3 = OpLoad %half %n\n" +
"%2 = OpFMul %half %108 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, HALF_0_ID),
// Test case 19: Don't fold 1.0(half) * n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_half Function\n" +
"%3 = OpLoad %half %n\n" +
"%2 = OpFMul %half %half_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 20: Don't fold 1.0 * 1.0 (half)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFMul %half %half_1 %half_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 21: Don't fold (0.0, 1.0) * (0.0, 1.0) (half)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFMul %v2half %half_0_1 %half_0_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 22: Don't fold (0.0, 1.0) dotp (0.0, 1.0) (half)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpDot %half %half_0_1 %half_0_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0)
));
INSTANTIATE_TEST_SUITE_P(DoubleRedundantFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't fold n + 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFAdd %double %3 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Don't fold n - 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFSub %double %3 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 2: Don't fold n * 2.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFMul %double %3 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: Fold n + 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFAdd %double %3 %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 4: Fold 0.0 + n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFAdd %double %double_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 5: Fold n - 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFSub %double %3 %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 6: Fold n * 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFMul %double %3 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 7: Fold 1.0 * n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFMul %double %double_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 8: Fold n / 1.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFDiv %double %3 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 9: Fold n * 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFMul %double %3 %105\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, DOUBLE_0_ID),
// Test case 10: Fold 0.0 * n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFMul %double %105 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, DOUBLE_0_ID),
// Test case 11: Fold 0.0 / n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFDiv %double %105 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, DOUBLE_0_ID),
// Test case 12: Don't fold mix(a, b, 2.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_double Function\n" +
"%b = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %a\n" +
"%4 = OpLoad %double %b\n" +
"%2 = OpExtInst %double %1 FMix %3 %4 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 13: Fold mix(a, b, 0.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_double Function\n" +
"%b = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %a\n" +
"%4 = OpLoad %double %b\n" +
"%2 = OpExtInst %double %1 FMix %3 %4 %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 14: Fold mix(a, b, 1.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%a = OpVariable %_ptr_double Function\n" +
"%b = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %a\n" +
"%4 = OpLoad %double %b\n" +
"%2 = OpExtInst %double %1 FMix %3 %4 %double_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 4)
));
INSTANTIATE_TEST_SUITE_P(FloatVectorRedundantFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't fold a * vec4(0.0, 0.0, 0.0, 1.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%3 = OpLoad %v4float %n\n" +
"%2 = OpFMul %v4float %3 %v4float_0_0_0_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Fold a * vec4(0.0, 0.0, 0.0, 0.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%3 = OpLoad %v4float %n\n" +
"%2 = OpFMul %v4float %3 %106\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, VEC4_0_ID),
// Test case 2: Fold a * vec4(1.0, 1.0, 1.0, 1.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%3 = OpLoad %v4float %n\n" +
"%2 = OpFMul %v4float %3 %v4float_1_1_1_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3)
));
INSTANTIATE_TEST_SUITE_P(DoubleVectorRedundantFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't fold a * vec4(0.0, 0.0, 0.0, 1.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%3 = OpLoad %v4double %n\n" +
"%2 = OpFMul %v4double %3 %v4double_0_0_0_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Fold a * vec4(0.0, 0.0, 0.0, 0.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%3 = OpLoad %v4double %n\n" +
"%2 = OpFMul %v4double %3 %106\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, DVEC4_0_ID),
// Test case 2: Fold a * vec4(1.0, 1.0, 1.0, 1.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%3 = OpLoad %v4double %n\n" +
"%2 = OpFMul %v4double %3 %v4double_1_1_1_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3)
));
INSTANTIATE_TEST_SUITE_P(IntegerRedundantFoldingTest, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't fold n + 1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%3 = OpLoad %uint %n\n" +
"%2 = OpIAdd %uint %3 %uint_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Don't fold 1 + n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%3 = OpLoad %uint %n\n" +
"%2 = OpIAdd %uint %uint_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 2: Fold n + 0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%3 = OpLoad %uint %n\n" +
"%2 = OpIAdd %uint %3 %uint_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 3: Fold 0 + n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_uint Function\n" +
"%3 = OpLoad %uint %n\n" +
"%2 = OpIAdd %uint %uint_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 4: Don't fold n + (1,0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%3 = OpLoad %v2int %n\n" +
"%2 = OpIAdd %v2int %3 %v2int_1_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 5: Don't fold (1,0) + n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%3 = OpLoad %v2int %n\n" +
"%2 = OpIAdd %v2int %v2int_1_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 6: Fold n + (0,0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%3 = OpLoad %v2int %n\n" +
"%2 = OpIAdd %v2int %3 %v2int_0_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 7: Fold (0,0) + n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%3 = OpLoad %v2int %n\n" +
"%2 = OpIAdd %v2int %v2int_0_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3)
));
INSTANTIATE_TEST_SUITE_P(ClampAndCmpLHS, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't Fold 0.0 < clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Don't Fold 0.0 < clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 2: Don't Fold 0.0 <= clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordLessThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: Don't Fold 0.0 <= clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdLessThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 4: Don't Fold 0.0 > clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 5: Don't Fold 0.0 > clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 6: Don't Fold 0.0 >= clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordGreaterThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 7: Don't Fold 0.0 >= clamp(-1, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdGreaterThanEqual %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 8: Don't Fold 0.0 < clamp(0, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFUnordLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 9: Don't Fold 0.0 < clamp(0, 1)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFOrdLessThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 10: Don't Fold 0.0 > clamp(-1, 0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFUnordGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 11: Don't Fold 0.0 > clamp(-1, 0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFOrdGreaterThan %bool %float_0 %clamp\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0)
));
INSTANTIATE_TEST_SUITE_P(ClampAndCmpRHS, GeneralInstructionFoldingTest,
::testing::Values(
// Test case 0: Don't Fold clamp(-1, 1) < 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordLessThan %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Don't Fold clamp(-1, 1) < 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdLessThan %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 2: Don't Fold clamp(-1, 1) <= 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordLessThanEqual %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: Don't Fold clamp(-1, 1) <= 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdLessThanEqual %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 4: Don't Fold clamp(-1, 1) > 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordGreaterThan %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 5: Don't Fold clamp(-1, 1) > 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdGreaterThan %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 6: Don't Fold clamp(-1, 1) >= 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFUnordGreaterThanEqual %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 7: Don't Fold clamp(-1, 1) >= 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_1\n" +
"%2 = OpFOrdGreaterThanEqual %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 8: Don't Fold clamp(-1, 0) < 0.0
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFUnordLessThan %bool %clamp %float_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 9: Don't Fold clamp(0, 1) < 1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_0 %float_1\n" +
"%2 = OpFOrdLessThan %bool %clamp %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 10: Don't Fold clamp(-1, 0) > -1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFUnordGreaterThan %bool %clamp %float_n1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 11: Don't Fold clamp(-1, 0) > -1
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%ld = OpLoad %float %n\n" +
"%clamp = OpExtInst %float %1 FClamp %ld %float_n1 %float_0\n" +
"%2 = OpFOrdGreaterThan %bool %clamp %float_n1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0)
));
INSTANTIATE_TEST_SUITE_P(FToIConstantFoldingTest, IntegerInstructionFoldingTest,
::testing::Values(
// Test case 0: Fold int(3.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpConvertFToS %int %float_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 1: Fold uint(3.0)
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpConvertFToU %int %float_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3)
));
INSTANTIATE_TEST_SUITE_P(IToFConstantFoldingTest, FloatInstructionFoldingTest,
::testing::Values(
// Test case 0: Fold float(3)
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpConvertSToF %float %int_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3.0),
// Test case 1: Fold float(3u)
InstructionFoldingCase<float>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpConvertUToF %float %uint_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3.0)
));
// clang-format on
using ToNegateFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<uint32_t>>;
TEST_P(ToNegateFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
std::unique_ptr<Instruction> original_inst(inst->Clone(context.get()));
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
// Make sure the instruction folded as expected.
EXPECT_EQ(inst->result_id(), original_inst->result_id());
EXPECT_EQ(inst->type_id(), original_inst->type_id());
EXPECT_TRUE((!succeeded) == (tc.expected_result == 0));
if (succeeded) {
EXPECT_EQ(inst->opcode(), SpvOpFNegate);
EXPECT_EQ(inst->GetSingleWordInOperand(0), tc.expected_result);
} else {
EXPECT_EQ(inst->NumInOperands(), original_inst->NumInOperands());
for (uint32_t i = 0; i < inst->NumInOperands(); ++i) {
EXPECT_EQ(inst->GetOperand(i), original_inst->GetOperand(i));
}
}
}
// clang-format off
INSTANTIATE_TEST_SUITE_P(FloatRedundantSubFoldingTest, ToNegateFoldingTest,
::testing::Values(
// Test case 0: Don't fold 1.0 - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFSub %float %float_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Fold 0.0 - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %n\n" +
"%2 = OpFSub %float %float_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 2: Don't fold (0,0,0,1) - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%3 = OpLoad %v4float %n\n" +
"%2 = OpFSub %v4float %v4float_0_0_0_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: Fold (0,0,0,0) - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%3 = OpLoad %v4float %n\n" +
"%2 = OpFSub %v4float %v4float_0_0_0_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3)
));
INSTANTIATE_TEST_SUITE_P(DoubleRedundantSubFoldingTest, ToNegateFoldingTest,
::testing::Values(
// Test case 0: Don't fold 1.0 - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFSub %double %double_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 1: Fold 0.0 - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%3 = OpLoad %double %n\n" +
"%2 = OpFSub %double %double_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3),
// Test case 2: Don't fold (0,0,0,1) - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%3 = OpLoad %v4double %n\n" +
"%2 = OpFSub %v4double %v4double_0_0_0_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 0),
// Test case 3: Fold (0,0,0,0) - n
InstructionFoldingCase<uint32_t>(
Header() + "%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%3 = OpLoad %v4double %n\n" +
"%2 = OpFSub %v4double %v4double_0_0_0_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, 3)
));
using MatchingInstructionFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<bool>>;
TEST_P(MatchingInstructionFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
std::unique_ptr<Instruction> original_inst(inst->Clone(context.get()));
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
EXPECT_EQ(succeeded, tc.expected_result);
if (succeeded) {
Match(tc.test_body, context.get());
}
}
INSTANTIATE_TEST_SUITE_P(RedundantIntegerMatching, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: Fold 0 + n (change sign)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[uint:%\\w+]] = OpTypeInt 32 0\n" +
"; CHECK: %2 = OpBitcast [[uint]] %3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%3 = OpLoad %uint %n\n" +
"%2 = OpIAdd %uint %int_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
2, true),
// Test case 0: Fold 0 + n (change sign)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: %2 = OpBitcast [[int]] %3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%3 = OpLoad %int %n\n" +
"%2 = OpIAdd %int %uint_0 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
2, true)
));
INSTANTIATE_TEST_SUITE_P(MergeNegateTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: fold consecutive fnegate
// -(-x) = x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float:%\\w+]]\n" +
"; CHECK: %4 = OpCopyObject [[float]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFNegate %float %2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 1: fold fnegate(fmul with const).
// -(x * 2.0) = x * -2.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n2:%\\w+]] = OpConstant [[float]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFMul [[float]] [[ld]] [[float_n2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFMul %float %2 %float_2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 2: fold fnegate(fmul with const).
// -(2.0 * x) = x * 2.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n2:%\\w+]] = OpConstant [[float]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFMul [[float]] [[ld]] [[float_n2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFMul %float %float_2 %2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 3: fold fnegate(fdiv with const).
// -(x / 2.0) = x * -0.5
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n0p5:%\\w+]] = OpConstant [[float]] -0.5\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFMul [[float]] [[ld]] [[float_n0p5]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %2 %float_2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 4: fold fnegate(fdiv with const).
// -(2.0 / x) = -2.0 / x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n2:%\\w+]] = OpConstant [[float]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFDiv [[float]] [[float_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %float_2 %2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 5: fold fnegate(fadd with const).
// -(2.0 + x) = -2.0 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n2:%\\w+]] = OpConstant [[float]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %float_2 %2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 6: fold fnegate(fadd with const).
// -(x + 2.0) = -2.0 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n2:%\\w+]] = OpConstant [[float]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %2 %float_2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 7: fold fnegate(fsub with const).
// -(2.0 - x) = x - 2.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[ld]] [[float_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %float_2 %2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 8: fold fnegate(fsub with const).
// -(x - 2.0) = 2.0 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %2 %float_2\n" +
"%4 = OpFNegate %float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 9: fold consecutive snegate
// -(-x) = x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int:%\\w+]]\n" +
"; CHECK: %4 = OpCopyObject [[int]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSNegate %int %2\n" +
"%4 = OpSNegate %int %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 10: fold consecutive vector negate
// -(-x) = x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v2float:%\\w+]]\n" +
"; CHECK: %4 = OpCopyObject [[v2float]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %var\n" +
"%3 = OpFNegate %v2float %2\n" +
"%4 = OpFNegate %v2float %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 11: fold snegate(iadd with const).
// -(2 + x) = -2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: OpConstant [[int]] -2147483648\n" +
"; CHECK: [[int_n2:%\\w+]] = OpConstant [[int]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpISub [[int]] [[int_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpIAdd %int %int_2 %2\n" +
"%4 = OpSNegate %int %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 12: fold snegate(iadd with const).
// -(x + 2) = -2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: OpConstant [[int]] -2147483648\n" +
"; CHECK: [[int_n2:%\\w+]] = OpConstant [[int]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpISub [[int]] [[int_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpIAdd %int %2 %int_2\n" +
"%4 = OpSNegate %int %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 13: fold snegate(isub with const).
// -(2 - x) = x - 2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int_2:%\\w+]] = OpConstant [[int]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpISub [[int]] [[ld]] [[int_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpISub %int %int_2 %2\n" +
"%4 = OpSNegate %int %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 14: fold snegate(isub with const).
// -(x - 2) = 2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int_2:%\\w+]] = OpConstant [[int]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpISub [[int]] [[int_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpISub %int %2 %int_2\n" +
"%4 = OpSNegate %int %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 15: fold snegate(iadd with const).
// -(x + 2) = -2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64 1\n" +
"; CHECK: [[long_n2:%\\w+]] = OpConstant [[long]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpISub [[long]] [[long_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpIAdd %long %2 %long_2\n" +
"%4 = OpSNegate %long %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 16: fold snegate(isub with const).
// -(2 - x) = x - 2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64 1\n" +
"; CHECK: [[long_2:%\\w+]] = OpConstant [[long]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpISub [[long]] [[ld]] [[long_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpISub %long %long_2 %2\n" +
"%4 = OpSNegate %long %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 17: fold snegate(isub with const).
// -(x - 2) = 2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64 1\n" +
"; CHECK: [[long_2:%\\w+]] = OpConstant [[long]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpISub [[long]] [[long_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpISub %long %2 %long_2\n" +
"%4 = OpSNegate %long %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 18: fold -vec4(-1.0, 2.0, 1.0, 3.0)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[v4float:%\\w+]] = OpTypeVector [[float]] 4{{[[:space:]]}}\n" +
"; CHECK: [[float_n1:%\\w+]] = OpConstant [[float]] -1{{[[:space:]]}}\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1{{[[:space:]]}}\n" +
"; CHECK: [[float_n2:%\\w+]] = OpConstant [[float]] -2{{[[:space:]]}}\n" +
"; CHECK: [[float_n3:%\\w+]] = OpConstant [[float]] -3{{[[:space:]]}}\n" +
"; CHECK: [[v4float_1_n2_n1_n3:%\\w+]] = OpConstantComposite [[v4float]] [[float_1]] [[float_n2]] [[float_n1]] [[float_n3]]\n" +
"; CHECK: %2 = OpCopyObject [[v4float]] [[v4float_1_n2_n1_n3]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFNegate %v4float %v4float_n1_2_1_3\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 19: fold vector fnegate with null
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v2double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: [[double_n0:%\\w+]] = OpConstant [[double]] -0\n" +
"; CHECK: [[v2double_0_0:%\\w+]] = OpConstantComposite [[v2double]] [[double_n0]] [[double_n0]]\n" +
"; CHECK: %2 = OpCopyObject [[v2double]] [[v2double_0_0]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpFNegate %v2double %v2double_null\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true)
));
INSTANTIATE_TEST_SUITE_P(ReciprocalFDivTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: scalar reicprocal
// x / 0.5 = x * 2.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %3 = OpFMul [[float]] [[ld]] [[float_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %2 %float_0p5\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
3, true),
// Test case 1: Unfoldable
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_0:%\\w+]] = OpConstant [[float]] 0\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %3 = OpFDiv [[float]] [[ld]] [[float_0]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %2 %104\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
3, false),
// Test case 2: Vector reciprocal
// x / {2.0, 0.5} = x * {0.5, 2.0}
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[v2float:%\\w+]] = OpTypeVector [[float]] 2\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[float_0p5:%\\w+]] = OpConstant [[float]] 0.5\n" +
"; CHECK: [[v2float_0p5_2:%\\w+]] = OpConstantComposite [[v2float]] [[float_0p5]] [[float_2]]\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v2float]]\n" +
"; CHECK: %3 = OpFMul [[v2float]] [[ld]] [[v2float_0p5_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %var\n" +
"%3 = OpFDiv %v2float %2 %v2float_2_0p5\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
3, true),
// Test case 3: double reciprocal
// x / 2.0 = x * 0.5
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[double_0p5:%\\w+]] = OpConstant [[double]] 0.5\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[double]]\n" +
"; CHECK: %3 = OpFMul [[double]] [[ld]] [[double_0p5]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_double Function\n" +
"%2 = OpLoad %double %var\n" +
"%3 = OpFDiv %double %2 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
3, true),
// Test case 4: don't fold x / 0.
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %var\n" +
"%3 = OpFDiv %v2float %2 %v2float_null\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
3, false)
));
INSTANTIATE_TEST_SUITE_P(MergeMulTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: fold consecutive fmuls
// (x * 3.0) * 2.0 = x * 6.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_6:%\\w+]] = OpConstant [[float]] 6\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFMul [[float]] [[ld]] [[float_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFMul %float %2 %float_3\n" +
"%4 = OpFMul %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 1: fold consecutive fmuls
// 2.0 * (x * 3.0) = x * 6.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_6:%\\w+]] = OpConstant [[float]] 6\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFMul [[float]] [[ld]] [[float_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFMul %float %2 %float_3\n" +
"%4 = OpFMul %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 2: fold consecutive fmuls
// (3.0 * x) * 2.0 = x * 6.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_6:%\\w+]] = OpConstant [[float]] 6\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFMul [[float]] [[ld]] [[float_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFMul %float %float_3 %2\n" +
"%4 = OpFMul %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 3: fold vector fmul
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[v2float:%\\w+]] = OpTypeVector [[float]] 2\n" +
"; CHECK: [[float_6:%\\w+]] = OpConstant [[float]] 6\n" +
"; CHECK: [[v2float_6_6:%\\w+]] = OpConstantComposite [[v2float]] [[float_6]] [[float_6]]\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v2float]]\n" +
"; CHECK: %4 = OpFMul [[v2float]] [[ld]] [[v2float_6_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %var\n" +
"%3 = OpFMul %v2float %2 %v2float_2_3\n" +
"%4 = OpFMul %v2float %3 %v2float_3_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 4: fold double fmuls
// (x * 3.0) * 2.0 = x * 6.0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[double_6:%\\w+]] = OpConstant [[double]] 6\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[double]]\n" +
"; CHECK: %4 = OpFMul [[double]] [[ld]] [[double_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_double Function\n" +
"%2 = OpLoad %double %var\n" +
"%3 = OpFMul %double %2 %double_3\n" +
"%4 = OpFMul %double %3 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 5: fold 32 bit imuls
// (x * 3) * 2 = x * 6
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int_6:%\\w+]] = OpConstant [[int]] 6\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpIMul [[int]] [[ld]] [[int_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpIMul %int %2 %int_3\n" +
"%4 = OpIMul %int %3 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 6: fold 64 bit imuls
// (x * 3) * 2 = x * 6
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64\n" +
"; CHECK: [[long_6:%\\w+]] = OpConstant [[long]] 6\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpIMul [[long]] [[ld]] [[long_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpIMul %long %2 %long_3\n" +
"%4 = OpIMul %long %3 %long_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 7: merge vector integer mults
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[v2int:%\\w+]] = OpTypeVector [[int]] 2\n" +
"; CHECK: [[int_6:%\\w+]] = OpConstant [[int]] 6\n" +
"; CHECK: [[v2int_6_6:%\\w+]] = OpConstantComposite [[v2int]] [[int_6]] [[int_6]]\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v2int]]\n" +
"; CHECK: %4 = OpIMul [[v2int]] [[ld]] [[v2int_6_6]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2int Function\n" +
"%2 = OpLoad %v2int %var\n" +
"%3 = OpIMul %v2int %2 %v2int_2_3\n" +
"%4 = OpIMul %v2int %3 %v2int_3_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 8: merge fmul of fdiv
// 2.0 * (2.0 / x) = 4.0 / x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_4:%\\w+]] = OpConstant [[float]] 4\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFDiv [[float]] [[float_4]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %float_2 %2\n" +
"%4 = OpFMul %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 9: merge fmul of fdiv
// (2.0 / x) * 2.0 = 4.0 / x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_4:%\\w+]] = OpConstant [[float]] 4\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFDiv [[float]] [[float_4]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %float_2 %2\n" +
"%4 = OpFMul %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 10: Do not merge imul of sdiv
// 4 * (x / 2)
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSDiv %int %2 %int_2\n" +
"%4 = OpIMul %int %int_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 11: Do not merge imul of sdiv
// (x / 2) * 4
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSDiv %int %2 %int_2\n" +
"%4 = OpIMul %int %3 %int_4\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 12: Do not merge imul of udiv
// 4 * (x / 2)
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_uint Function\n" +
"%2 = OpLoad %uint %var\n" +
"%3 = OpUDiv %uint %2 %uint_2\n" +
"%4 = OpIMul %uint %uint_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 13: Do not merge imul of udiv
// (x / 2) * 4
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_uint Function\n" +
"%2 = OpLoad %uint %var\n" +
"%3 = OpUDiv %uint %2 %uint_2\n" +
"%4 = OpIMul %uint %3 %uint_4\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 14: Don't fold
// (x / 3) * 4
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_uint Function\n" +
"%2 = OpLoad %uint %var\n" +
"%3 = OpUDiv %uint %2 %uint_3\n" +
"%4 = OpIMul %uint %3 %uint_4\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 15: merge vector fmul of fdiv
// (x / {2,2}) * {4,4} = x * {2,2}
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[v2float:%\\w+]] = OpTypeVector [[float]] 2\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[v2float_2_2:%\\w+]] = OpConstantComposite [[v2float]] [[float_2]] [[float_2]]\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v2float]]\n" +
"; CHECK: %4 = OpFMul [[v2float]] [[ld]] [[v2float_2_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %v2float %var\n" +
"%3 = OpFDiv %v2float %2 %v2float_2_2\n" +
"%4 = OpFMul %v2float %3 %v2float_4_4\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 16: merge vector imul of snegate
// (-x) * {2,2} = x * {-2,-2}
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[v2int:%\\w+]] = OpTypeVector [[int]] 2{{[[:space:]]}}\n" +
"; CHECK: OpConstant [[int]] -2147483648{{[[:space:]]}}\n" +
"; CHECK: [[int_n2:%\\w+]] = OpConstant [[int]] -2{{[[:space:]]}}\n" +
"; CHECK: [[v2int_n2_n2:%\\w+]] = OpConstantComposite [[v2int]] [[int_n2]] [[int_n2]]\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v2int]]\n" +
"; CHECK: %4 = OpIMul [[v2int]] [[ld]] [[v2int_n2_n2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2int Function\n" +
"%2 = OpLoad %v2int %var\n" +
"%3 = OpSNegate %v2int %2\n" +
"%4 = OpIMul %v2int %3 %v2int_2_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 17: merge vector imul of snegate
// {2,2} * (-x) = x * {-2,-2}
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[v2int:%\\w+]] = OpTypeVector [[int]] 2{{[[:space:]]}}\n" +
"; CHECK: OpConstant [[int]] -2147483648{{[[:space:]]}}\n" +
"; CHECK: [[int_n2:%\\w+]] = OpConstant [[int]] -2{{[[:space:]]}}\n" +
"; CHECK: [[v2int_n2_n2:%\\w+]] = OpConstantComposite [[v2int]] [[int_n2]] [[int_n2]]\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v2int]]\n" +
"; CHECK: %4 = OpIMul [[v2int]] [[ld]] [[v2int_n2_n2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2int Function\n" +
"%2 = OpLoad %v2int %var\n" +
"%3 = OpSNegate %v2int %2\n" +
"%4 = OpIMul %v2int %v2int_2_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 18: Fold OpVectorTimesScalar
// {4,4} = OpVectorTimesScalar v2float {2,2} 2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[v2float:%\\w+]] = OpTypeVector [[float]] 2\n" +
"; CHECK: [[float_4:%\\w+]] = OpConstant [[float]] 4\n" +
"; CHECK: [[v2float_4_4:%\\w+]] = OpConstantComposite [[v2float]] [[float_4]] [[float_4]]\n" +
"; CHECK: %2 = OpCopyObject [[v2float]] [[v2float_4_4]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVectorTimesScalar %v2float %v2float_2_2 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 19: Fold OpVectorTimesScalar
// {0,0} = OpVectorTimesScalar v2float v2float_null -1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[v2float:%\\w+]] = OpTypeVector [[float]] 2\n" +
"; CHECK: [[v2float_null:%\\w+]] = OpConstantNull [[v2float]]\n" +
"; CHECK: %2 = OpCopyObject [[v2float]] [[v2float_null]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVectorTimesScalar %v2float %v2float_null %float_n1\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 20: Fold OpVectorTimesScalar
// {4,4} = OpVectorTimesScalar v2double {2,2} 2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v2double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: [[double_4:%\\w+]] = OpConstant [[double]] 4\n" +
"; CHECK: [[v2double_4_4:%\\w+]] = OpConstantComposite [[v2double]] [[double_4]] [[double_4]]\n" +
"; CHECK: %2 = OpCopyObject [[v2double]] [[v2double_4_4]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVectorTimesScalar %v2double %v2double_2_2 %double_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 21: Fold OpVectorTimesScalar
// {0,0} = OpVectorTimesScalar v2double {0,0} n
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v2double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: {{%\\w+}} = OpConstant [[double]] 0\n" +
"; CHECK: [[double_0:%\\w+]] = OpConstant [[double]] 0\n" +
"; CHECK: [[v2double_0_0:%\\w+]] = OpConstantComposite [[v2double]] [[double_0]] [[double_0]]\n" +
"; CHECK: %2 = OpCopyObject [[v2double]] [[v2double_0_0]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_double Function\n" +
"%load = OpLoad %double %n\n" +
"%2 = OpVectorTimesScalar %v2double %v2double_0_0 %load\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 22: Fold OpVectorTimesScalar
// {0,0} = OpVectorTimesScalar v2double n 0
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v2double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: [[v2double_null:%\\w+]] = OpConstantNull [[v2double]]\n" +
"; CHECK: %2 = OpCopyObject [[v2double]] [[v2double_null]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2double Function\n" +
"%load = OpLoad %v2double %n\n" +
"%2 = OpVectorTimesScalar %v2double %load %double_0\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 23: merge fmul of fdiv
// x * (y / x) = y
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[ldx:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: [[ldy:%\\w+]] = OpLoad [[float]] [[y:%\\w+]]\n" +
"; CHECK: %5 = OpCopyObject [[float]] [[ldy]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%x = OpVariable %_ptr_float Function\n" +
"%y = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %x\n" +
"%3 = OpLoad %float %y\n" +
"%4 = OpFDiv %float %3 %2\n" +
"%5 = OpFMul %float %2 %4\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
5, true),
// Test case 24: merge fmul of fdiv
// (y / x) * x = y
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[ldx:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: [[ldy:%\\w+]] = OpLoad [[float]] [[y:%\\w+]]\n" +
"; CHECK: %5 = OpCopyObject [[float]] [[ldy]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%x = OpVariable %_ptr_float Function\n" +
"%y = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %x\n" +
"%3 = OpLoad %float %y\n" +
"%4 = OpFDiv %float %3 %2\n" +
"%5 = OpFMul %float %4 %2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
5, true)
));
INSTANTIATE_TEST_SUITE_P(MergeDivTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: merge consecutive fdiv
// 4.0 / (2.0 / x) = 2.0 * x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFMul [[float]] [[float_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %float_2 %2\n" +
"%4 = OpFDiv %float %float_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 1: merge consecutive fdiv
// 4.0 / (x / 2.0) = 8.0 / x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_8:%\\w+]] = OpConstant [[float]] 8\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFDiv [[float]] [[float_8]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %2 %float_2\n" +
"%4 = OpFDiv %float %float_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 2: merge consecutive fdiv
// (4.0 / x) / 2.0 = 2.0 / x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFDiv [[float]] [[float_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %float_4 %2\n" +
"%4 = OpFDiv %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 3: Do not merge consecutive sdiv
// 4 / (2 / x)
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSDiv %int %int_2 %2\n" +
"%4 = OpSDiv %int %int_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 4: Do not merge consecutive sdiv
// 4 / (x / 2)
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSDiv %int %2 %int_2\n" +
"%4 = OpSDiv %int %int_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 5: Do not merge consecutive sdiv
// (4 / x) / 2
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSDiv %int %int_4 %2\n" +
"%4 = OpSDiv %int %3 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 6: Do not merge consecutive sdiv
// (x / 4) / 2
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSDiv %int %2 %int_4\n" +
"%4 = OpSDiv %int %3 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 7: Do not merge sdiv of imul
// 4 / (2 * x)
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpIMul %int %int_2 %2\n" +
"%4 = OpSDiv %int %int_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 8: Do not merge sdiv of imul
// 4 / (x * 2)
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpIMul %int %2 %int_2\n" +
"%4 = OpSDiv %int %int_4 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 9: Do not merge sdiv of imul
// (4 * x) / 2
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpIMul %int %int_4 %2\n" +
"%4 = OpSDiv %int %3 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 10: Do not merge sdiv of imul
// (x * 4) / 2
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpIMul %int %2 %int_4\n" +
"%4 = OpSDiv %int %3 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 11: merge sdiv of snegate
// (-x) / 2 = x / -2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: OpConstant [[int]] -2147483648\n" +
"; CHECK: [[int_n2:%\\w+]] = OpConstant [[int]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpSDiv [[int]] [[ld]] [[int_n2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSNegate %int %2\n" +
"%4 = OpSDiv %int %3 %int_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 12: merge sdiv of snegate
// 2 / (-x) = -2 / x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: OpConstant [[int]] -2147483648\n" +
"; CHECK: [[int_n2:%\\w+]] = OpConstant [[int]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpSDiv [[int]] [[int_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpSNegate %int %2\n" +
"%4 = OpSDiv %int %int_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 13: Don't merge
// (x / {null}) / {null}
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_v2float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFDiv %float %2 %v2float_null\n" +
"%4 = OpFDiv %float %3 %v2float_null\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, false),
// Test case 14: merge fmul of fdiv
// (y * x) / x = y
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[ldx:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: [[ldy:%\\w+]] = OpLoad [[float]] [[y:%\\w+]]\n" +
"; CHECK: %5 = OpCopyObject [[float]] [[ldy]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%x = OpVariable %_ptr_float Function\n" +
"%y = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %x\n" +
"%3 = OpLoad %float %y\n" +
"%4 = OpFMul %float %3 %2\n" +
"%5 = OpFDiv %float %4 %2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
5, true),
// Test case 15: merge fmul of fdiv
// (x * y) / x = y
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[ldx:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: [[ldy:%\\w+]] = OpLoad [[float]] [[y:%\\w+]]\n" +
"; CHECK: %5 = OpCopyObject [[float]] [[ldy]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%x = OpVariable %_ptr_float Function\n" +
"%y = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %x\n" +
"%3 = OpLoad %float %y\n" +
"%4 = OpFMul %float %2 %3\n" +
"%5 = OpFDiv %float %4 %2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
5, true)
));
INSTANTIATE_TEST_SUITE_P(MergeAddTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: merge add of negate
// (-x) + 2 = 2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFNegate %float %2\n" +
"%4 = OpFAdd %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 1: merge add of negate
// 2 + (-x) = 2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpSNegate %float %2\n" +
"%4 = OpIAdd %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 2: merge add of negate
// (-x) + 2 = 2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64 1\n" +
"; CHECK: [[long_2:%\\w+]] = OpConstant [[long]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpISub [[long]] [[long_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpSNegate %long %2\n" +
"%4 = OpIAdd %long %3 %long_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 3: merge add of negate
// 2 + (-x) = 2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64 1\n" +
"; CHECK: [[long_2:%\\w+]] = OpConstant [[long]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpISub [[long]] [[long_2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpSNegate %long %2\n" +
"%4 = OpIAdd %long %long_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 4: merge add of subtract
// (x - 1) + 2 = x + 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_1]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %2 %float_1\n" +
"%4 = OpFAdd %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 5: merge add of subtract
// (1 - x) + 2 = 3 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_3]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %float_1 %2\n" +
"%4 = OpFAdd %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 6: merge add of subtract
// 2 + (x - 1) = x + 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_1]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %2 %float_1\n" +
"%4 = OpFAdd %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 7: merge add of subtract
// 2 + (1 - x) = 3 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_3]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %float_1 %2\n" +
"%4 = OpFAdd %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 8: merge add of add
// (x + 1) + 2 = x + 3
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_3]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %2 %float_1\n" +
"%4 = OpFAdd %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 9: merge add of add
// (1 + x) + 2 = 3 + x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_3]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %float_1 %2\n" +
"%4 = OpFAdd %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 10: merge add of add
// 2 + (x + 1) = x + 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_3]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %2 %float_1\n" +
"%4 = OpFAdd %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 11: merge add of add
// 2 + (1 + x) = 3 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_3]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %float_1 %2\n" +
"%4 = OpFAdd %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true)
));
INSTANTIATE_TEST_SUITE_P(MergeGenericAddSub, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: merge of add of sub
// (a - b) + b => a
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: %6 = OpCopyObject [[float]] %3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var0 = OpVariable %_ptr_float Function\n" +
"%var1 = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %var0\n" +
"%4 = OpLoad %float %var1\n" +
"%5 = OpFSub %float %3 %4\n" +
"%6 = OpFAdd %float %5 %4\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
6, true),
// Test case 1: merge of add of sub
// b + (a - b) => a
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: %6 = OpCopyObject [[float]] %3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var0 = OpVariable %_ptr_float Function\n" +
"%var1 = OpVariable %_ptr_float Function\n" +
"%3 = OpLoad %float %var0\n" +
"%4 = OpLoad %float %var1\n" +
"%5 = OpFSub %float %3 %4\n" +
"%6 = OpFAdd %float %4 %5\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
6, true)
));
INSTANTIATE_TEST_SUITE_P(FactorAddMul, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: factor of add of muls
// (a * b) + (a * c) => a * (b + c)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[newadd:%\\w+]] = OpFAdd [[float]] %4 %5\n" +
"; CHECK: %9 = OpFMul [[float]] %6 [[newadd]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var0 = OpVariable %_ptr_float Function\n" +
"%var1 = OpVariable %_ptr_float Function\n" +
"%var2 = OpVariable %_ptr_float Function\n" +
"%4 = OpLoad %float %var0\n" +
"%5 = OpLoad %float %var1\n" +
"%6 = OpLoad %float %var2\n" +
"%7 = OpFMul %float %6 %4\n" +
"%8 = OpFMul %float %6 %5\n" +
"%9 = OpFAdd %float %7 %8\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
9, true),
// Test case 1: factor of add of muls
// (b * a) + (a * c) => a * (b + c)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[newadd:%\\w+]] = OpFAdd [[float]] %4 %5\n" +
"; CHECK: %9 = OpFMul [[float]] %6 [[newadd]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var0 = OpVariable %_ptr_float Function\n" +
"%var1 = OpVariable %_ptr_float Function\n" +
"%var2 = OpVariable %_ptr_float Function\n" +
"%4 = OpLoad %float %var0\n" +
"%5 = OpLoad %float %var1\n" +
"%6 = OpLoad %float %var2\n" +
"%7 = OpFMul %float %4 %6\n" +
"%8 = OpFMul %float %6 %5\n" +
"%9 = OpFAdd %float %7 %8\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
9, true),
// Test case 2: factor of add of muls
// (a * b) + (c * a) => a * (b + c)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[newadd:%\\w+]] = OpFAdd [[float]] %4 %5\n" +
"; CHECK: %9 = OpFMul [[float]] %6 [[newadd]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var0 = OpVariable %_ptr_float Function\n" +
"%var1 = OpVariable %_ptr_float Function\n" +
"%var2 = OpVariable %_ptr_float Function\n" +
"%4 = OpLoad %float %var0\n" +
"%5 = OpLoad %float %var1\n" +
"%6 = OpLoad %float %var2\n" +
"%7 = OpFMul %float %6 %4\n" +
"%8 = OpFMul %float %5 %6\n" +
"%9 = OpFAdd %float %7 %8\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
9, true),
// Test case 3: factor of add of muls
// (b * a) + (c * a) => a * (b + c)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[newadd:%\\w+]] = OpFAdd [[float]] %4 %5\n" +
"; CHECK: %9 = OpFMul [[float]] %6 [[newadd]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var0 = OpVariable %_ptr_float Function\n" +
"%var1 = OpVariable %_ptr_float Function\n" +
"%var2 = OpVariable %_ptr_float Function\n" +
"%4 = OpLoad %float %var0\n" +
"%5 = OpLoad %float %var1\n" +
"%6 = OpLoad %float %var2\n" +
"%7 = OpFMul %float %4 %6\n" +
"%8 = OpFMul %float %5 %6\n" +
"%9 = OpFAdd %float %7 %8\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
9, true)
));
INSTANTIATE_TEST_SUITE_P(MergeSubTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: merge sub of negate
// (-x) - 2 = -2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n2:%\\w+]] = OpConstant [[float]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFNegate %float %2\n" +
"%4 = OpFSub %float %3 %float_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 1: merge sub of negate
// 2 - (-x) = x + 2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_2:%\\w+]] = OpConstant [[float]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFNegate %float %2\n" +
"%4 = OpFSub %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 2: merge sub of negate
// (-x) - 2 = -2 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64 1\n" +
"; CHECK: [[long_n2:%\\w+]] = OpConstant [[long]] -2{{[[:space:]]}}\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpISub [[long]] [[long_n2]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpSNegate %long %2\n" +
"%4 = OpISub %long %3 %long_2\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 3: merge sub of negate
// 2 - (-x) = x + 2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[long:%\\w+]] = OpTypeInt 64 1\n" +
"; CHECK: [[long_2:%\\w+]] = OpConstant [[long]] 2\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[long]]\n" +
"; CHECK: %4 = OpIAdd [[long]] [[ld]] [[long_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_long Function\n" +
"%2 = OpLoad %long %var\n" +
"%3 = OpSNegate %long %2\n" +
"%4 = OpISub %long %long_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 4: merge add of subtract
// (x + 2) - 1 = x + 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_1]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %2 %float_2\n" +
"%4 = OpFSub %float %3 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 5: merge add of subtract
// (2 + x) - 1 = x + 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_1]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %float_2 %2\n" +
"%4 = OpFSub %float %3 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 6: merge add of subtract
// 2 - (x + 1) = 1 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_1]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %2 %float_1\n" +
"%4 = OpFSub %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 7: merge add of subtract
// 2 - (1 + x) = 1 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_1]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFAdd %float %float_1 %2\n" +
"%4 = OpFSub %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 8: merge subtract of subtract
// (x - 2) - 1 = x - 3
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[ld]] [[float_3]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %2 %float_2\n" +
"%4 = OpFSub %float %3 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 9: merge subtract of subtract
// (2 - x) - 1 = 1 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_1]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %float_2 %2\n" +
"%4 = OpFSub %float %3 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 10: merge subtract of subtract
// 2 - (x - 1) = 3 - x
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_3:%\\w+]] = OpConstant [[float]] 3\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFSub [[float]] [[float_3]] [[ld]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %2 %float_1\n" +
"%4 = OpFSub %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 11: merge subtract of subtract
// 1 - (2 - x) = x + (-1)
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_n1:%\\w+]] = OpConstant [[float]] -1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_n1]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %float_2 %2\n" +
"%4 = OpFSub %float %float_1 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 12: merge subtract of subtract
// 2 - (1 - x) = x + 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: [[float_1:%\\w+]] = OpConstant [[float]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[float]]\n" +
"; CHECK: %4 = OpFAdd [[float]] [[ld]] [[float_1]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_float Function\n" +
"%2 = OpLoad %float %var\n" +
"%3 = OpFSub %float %float_1 %2\n" +
"%4 = OpFSub %float %float_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true),
// Test case 13: merge subtract of subtract with mixed types.
// 2 - (1 - x) = x + 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int_1:%\\w+]] = OpConstant [[int]] 1\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[int]]\n" +
"; CHECK: %4 = OpIAdd [[int]] [[ld]] [[int_1]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%var = OpVariable %_ptr_int Function\n" +
"%2 = OpLoad %int %var\n" +
"%3 = OpISub %int %uint_1 %2\n" +
"%4 = OpISub %int %int_2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
4, true)
));
INSTANTIATE_TEST_SUITE_P(SelectFoldingTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: Fold select with the same values for both sides
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int0:%\\w+]] = OpConstant [[int]] 0\n" +
"; CHECK: %2 = OpCopyObject [[int]] [[int0]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_bool Function\n" +
"%load = OpLoad %bool %n\n" +
"%2 = OpSelect %int %load %100 %100\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 1: Fold select true to left side
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int0:%\\w+]] = OpConstant [[int]] 0\n" +
"; CHECK: %2 = OpCopyObject [[int]] [[int0]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %bool %n\n" +
"%2 = OpSelect %int %true %100 %n\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 2: Fold select false to right side
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int0:%\\w+]] = OpConstant [[int]] 0\n" +
"; CHECK: %2 = OpCopyObject [[int]] [[int0]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %bool %n\n" +
"%2 = OpSelect %int %false %n %100\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 3: Fold select null to right side
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[int0:%\\w+]] = OpConstant [[int]] 0\n" +
"; CHECK: %2 = OpCopyObject [[int]] [[int0]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_int Function\n" +
"%load = OpLoad %int %n\n" +
"%2 = OpSelect %int %bool_null %load %100\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 4: vector null
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[v2int:%\\w+]] = OpTypeVector [[int]] 2\n" +
"; CHECK: [[int2:%\\w+]] = OpConstant [[int]] 2\n" +
"; CHECK: [[v2int2_2:%\\w+]] = OpConstantComposite [[v2int]] [[int2]] [[int2]]\n" +
"; CHECK: %2 = OpCopyObject [[v2int]] [[v2int2_2]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%load = OpLoad %v2int %n\n" +
"%2 = OpSelect %v2int %v2bool_null %load %v2int_2_2\n" +
"OpReturn\n" +
"OpFunctionEnd",
2, true),
// Test case 5: vector select
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[v2int:%\\w+]] = OpTypeVector [[int]] 2\n" +
"; CHECK: %4 = OpVectorShuffle [[v2int]] %2 %3 0 3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%m = OpVariable %_ptr_v2int Function\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%2 = OpLoad %v2int %n\n" +
"%3 = OpLoad %v2int %n\n" +
"%4 = OpSelect %v2int %v2bool_true_false %2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 6: vector select
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: [[v2int:%\\w+]] = OpTypeVector [[int]] 2\n" +
"; CHECK: %4 = OpVectorShuffle [[v2int]] %2 %3 2 1\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%m = OpVariable %_ptr_v2int Function\n" +
"%n = OpVariable %_ptr_v2int Function\n" +
"%2 = OpLoad %v2int %n\n" +
"%3 = OpLoad %v2int %n\n" +
"%4 = OpSelect %v2int %v2bool_false_true %2 %3\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true)
));
INSTANTIATE_TEST_SUITE_P(CompositeExtractMatchingTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: Extracting from result of consecutive shuffles of differing
// size.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: %5 = OpCompositeExtract [[int]] %2 2\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4int Function\n" +
"%2 = OpLoad %v4int %n\n" +
"%3 = OpVectorShuffle %v2int %2 %2 2 3\n" +
"%4 = OpVectorShuffle %v4int %2 %3 0 4 2 5\n" +
"%5 = OpCompositeExtract %int %4 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, true),
// Test case 1: Extracting from result of vector shuffle of differing
// input and result sizes.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: %4 = OpCompositeExtract [[int]] %2 2\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4int Function\n" +
"%2 = OpLoad %v4int %n\n" +
"%3 = OpVectorShuffle %v2int %2 %2 2 3\n" +
"%4 = OpCompositeExtract %int %3 0\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 2: Extracting from result of vector shuffle of differing
// input and result sizes.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: %4 = OpCompositeExtract [[int]] %2 3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4int Function\n" +
"%2 = OpLoad %v4int %n\n" +
"%3 = OpVectorShuffle %v2int %2 %2 2 3\n" +
"%4 = OpCompositeExtract %int %3 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true),
// Test case 3: Using fmix feeding extract with a 1 in the a position.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v4double:%\\w+]] = OpTypeVector [[double]] 4\n" +
"; CHECK: [[ptr_v4double:%\\w+]] = OpTypePointer Function [[v4double]]\n" +
"; CHECK: [[m:%\\w+]] = OpVariable [[ptr_v4double]] Function\n" +
"; CHECK: [[n:%\\w+]] = OpVariable [[ptr_v4double]] Function\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v4double]] [[n]]\n" +
"; CHECK: %5 = OpCompositeExtract [[double]] [[ld]] 1\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%m = OpVariable %_ptr_v4double Function\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%2 = OpLoad %v4double %m\n" +
"%3 = OpLoad %v4double %n\n" +
"%4 = OpExtInst %v4double %1 FMix %2 %3 %v4double_0_1_0_0\n" +
"%5 = OpCompositeExtract %double %4 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, true),
// Test case 4: Using fmix feeding extract with a 0 in the a position.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v4double:%\\w+]] = OpTypeVector [[double]] 4\n" +
"; CHECK: [[ptr_v4double:%\\w+]] = OpTypePointer Function [[v4double]]\n" +
"; CHECK: [[m:%\\w+]] = OpVariable [[ptr_v4double]] Function\n" +
"; CHECK: [[n:%\\w+]] = OpVariable [[ptr_v4double]] Function\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v4double]] [[m]]\n" +
"; CHECK: %5 = OpCompositeExtract [[double]] [[ld]] 2\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%m = OpVariable %_ptr_v4double Function\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%2 = OpLoad %v4double %m\n" +
"%3 = OpLoad %v4double %n\n" +
"%4 = OpExtInst %v4double %1 FMix %2 %3 %v4double_0_1_0_0\n" +
"%5 = OpCompositeExtract %double %4 2\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, true),
// Test case 5: Using fmix feeding extract with a null for the alpha
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v4double:%\\w+]] = OpTypeVector [[double]] 4\n" +
"; CHECK: [[ptr_v4double:%\\w+]] = OpTypePointer Function [[v4double]]\n" +
"; CHECK: [[m:%\\w+]] = OpVariable [[ptr_v4double]] Function\n" +
"; CHECK: [[n:%\\w+]] = OpVariable [[ptr_v4double]] Function\n" +
"; CHECK: [[ld:%\\w+]] = OpLoad [[v4double]] [[m]]\n" +
"; CHECK: %5 = OpCompositeExtract [[double]] [[ld]] 0\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%m = OpVariable %_ptr_v4double Function\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%2 = OpLoad %v4double %m\n" +
"%3 = OpLoad %v4double %n\n" +
"%4 = OpExtInst %v4double %1 FMix %2 %3 %v4double_null\n" +
"%5 = OpCompositeExtract %double %4 0\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, true),
// Test case 6: Don't fold: Using fmix feeding extract with 0.5 in the a
// position.
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%m = OpVariable %_ptr_v4double Function\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%2 = OpLoad %v4double %m\n" +
"%3 = OpLoad %v4double %n\n" +
"%4 = OpExtInst %v4double %1 FMix %2 %3 %v4double_1_1_1_0p5\n" +
"%5 = OpCompositeExtract %double %4 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
5, false),
// Test case 7: Extracting the undefined literal value from a vector
// shuffle.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[int:%\\w+]] = OpTypeInt 32 1\n" +
"; CHECK: %4 = OpUndef [[int]]\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4int Function\n" +
"%2 = OpLoad %v4int %n\n" +
"%3 = OpVectorShuffle %v2int %2 %2 2 4294967295\n" +
"%4 = OpCompositeExtract %int %3 1\n" +
"OpReturn\n" +
"OpFunctionEnd",
4, true)
));
INSTANTIATE_TEST_SUITE_P(DotProductMatchingTest, MatchingInstructionFoldingTest,
::testing::Values(
// Test case 0: Using OpDot to extract last element.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: %3 = OpCompositeExtract [[float]] %2 3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%2 = OpLoad %v4float %n\n" +
"%3 = OpDot %float %2 %v4float_0_0_0_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, true),
// Test case 1: Using OpDot to extract last element.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: %3 = OpCompositeExtract [[float]] %2 3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%2 = OpLoad %v4float %n\n" +
"%3 = OpDot %float %v4float_0_0_0_1 %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, true),
// Test case 2: Using OpDot to extract second element.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[float:%\\w+]] = OpTypeFloat 32\n" +
"; CHECK: %3 = OpCompositeExtract [[float]] %2 1\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4float Function\n" +
"%2 = OpLoad %v4float %n\n" +
"%3 = OpDot %float %v4float_0_1_0_0 %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, true),
// Test case 3: Using OpDot to extract last element.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: %3 = OpCompositeExtract [[double]] %2 3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%2 = OpLoad %v4double %n\n" +
"%3 = OpDot %double %2 %v4double_0_0_0_1\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, true),
// Test case 4: Using OpDot to extract last element.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: %3 = OpCompositeExtract [[double]] %2 3\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%2 = OpLoad %v4double %n\n" +
"%3 = OpDot %double %v4double_0_0_0_1 %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, true),
// Test case 5: Using OpDot to extract second element.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: %3 = OpCompositeExtract [[double]] %2 1\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%2 = OpLoad %v4double %n\n" +
"%3 = OpDot %double %v4double_0_1_0_0 %2\n" +
"OpReturn\n" +
"OpFunctionEnd",
3, true)
));
using MatchingInstructionWithNoResultFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<bool>>;
// Test folding instructions that do not have a result. The instruction
// that will be folded is the last instruction before the return. If there
// are multiple returns, there is not guarentee which one is used.
TEST_P(MatchingInstructionWithNoResultFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
Instruction* inst = nullptr;
Function* func = &*context->module()->begin();
for (auto& bb : *func) {
Instruction* terminator = bb.terminator();
if (terminator->IsReturnOrAbort()) {
inst = terminator->PreviousNode();
break;
}
}
assert(inst && "Invalid test. Could not find instruction to fold.");
std::unique_ptr<Instruction> original_inst(inst->Clone(context.get()));
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
EXPECT_EQ(succeeded, tc.expected_result);
if (succeeded) {
Match(tc.test_body, context.get());
}
}
INSTANTIATE_TEST_SUITE_P(StoreMatchingTest, MatchingInstructionWithNoResultFoldingTest,
::testing::Values(
// Test case 0: Remove store of undef.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpLabel\n" +
"; CHECK-NOT: OpStore\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%undef = OpUndef %v4double\n" +
"OpStore %n %undef\n" +
"OpReturn\n" +
"OpFunctionEnd",
0 /* OpStore */, true),
// Test case 1: Keep volatile store.
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%n = OpVariable %_ptr_v4double Function\n" +
"%undef = OpUndef %v4double\n" +
"OpStore %n %undef Volatile\n" +
"OpReturn\n" +
"OpFunctionEnd",
0 /* OpStore */, false)
));
INSTANTIATE_TEST_SUITE_P(VectorShuffleMatchingTest, MatchingInstructionWithNoResultFoldingTest,
::testing::Values(
// Test case 0: Basic test 1
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %7 %5 2 3 6 7\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %6 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %7 %8 2 3 4 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 1: Basic test 2
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %6 %7 0 1 4 5\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %6 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %8 %7 2 3 4 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 2: Basic test 3
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %5 %7 3 2 4 5\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %6 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %8 %7 1 0 4 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 3: Basic test 4
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %7 %6 2 3 5 4\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %6 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %7 %8 2 3 7 6\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 4: Don't fold, need both operands of the feeder.
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %6 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %7 %8 2 3 7 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, false),
// Test case 5: Don't fold, need both operands of the feeder.
InstructionFoldingCase<bool>(
Header() +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %6 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %8 %7 2 0 7 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, false),
// Test case 6: Fold, need both operands of the feeder, but they are the same.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %5 %7 0 2 7 5\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %5 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %8 %7 2 0 7 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 7: Fold, need both operands of the feeder, but they are the same.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %7 %5 2 0 5 7\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %5 2 3 4 5\n" +
"%9 = OpVectorShuffle %v4double %7 %8 2 0 7 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 8: Replace first operand with a smaller vector.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %5 %7 0 0 5 3\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v2double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v2double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v4double %5 %5 0 1 2 3\n" +
"%9 = OpVectorShuffle %v4double %8 %7 2 0 7 5\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 9: Replace first operand with a larger vector.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %5 %7 3 0 7 5\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v2double %5 %5 0 3\n" +
"%9 = OpVectorShuffle %v4double %8 %7 1 0 5 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 10: Replace unused operand with null.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v4double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: [[null:%\\w+]] = OpConstantNull [[v4double]]\n" +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} [[null]] %7 4 2 5 3\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v2double %5 %5 0 3\n" +
"%9 = OpVectorShuffle %v4double %8 %7 4 2 5 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 11: Replace unused operand with null.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v4double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: [[null:%\\w+]] = OpConstantNull [[v4double]]\n" +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} [[null]] %5 2 2 5 5\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%8 = OpVectorShuffle %v2double %5 %5 0 3\n" +
"%9 = OpVectorShuffle %v4double %8 %8 2 2 3 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 12: Replace unused operand with null.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v4double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: [[null:%\\w+]] = OpConstantNull [[v4double]]\n" +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %7 [[null]] 2 0 1 3\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v2double %5 %5 0 3\n" +
"%9 = OpVectorShuffle %v4double %7 %8 2 0 1 3\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true),
// Test case 13: Shuffle with undef literal.
InstructionFoldingCase<bool>(
Header() +
"; CHECK: [[double:%\\w+]] = OpTypeFloat 64\n" +
"; CHECK: [[v4double:%\\w+]] = OpTypeVector [[double]] 2\n" +
"; CHECK: OpVectorShuffle\n" +
"; CHECK: OpVectorShuffle {{%\\w+}} %7 {{%\\w+}} 2 0 1 4294967295\n" +
"; CHECK: OpReturn\n" +
"%main = OpFunction %void None %void_func\n" +
"%main_lab = OpLabel\n" +
"%2 = OpVariable %_ptr_v4double Function\n" +
"%3 = OpVariable %_ptr_v4double Function\n" +
"%4 = OpVariable %_ptr_v4double Function\n" +
"%5 = OpLoad %v4double %2\n" +
"%6 = OpLoad %v4double %3\n" +
"%7 = OpLoad %v4double %4\n" +
"%8 = OpVectorShuffle %v2double %5 %5 0 1\n" +
"%9 = OpVectorShuffle %v4double %7 %8 2 0 1 4294967295\n" +
"OpReturn\n" +
"OpFunctionEnd",
9, true)
));
using EntryPointFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<bool>>;
TEST_P(EntryPointFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
Instruction* inst = nullptr;
inst = &*context->module()->entry_points().begin();
assert(inst && "Invalid test. Could not find entry point instruction to fold.");
std::unique_ptr<Instruction> original_inst(inst->Clone(context.get()));
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
EXPECT_EQ(succeeded, tc.expected_result);
if (succeeded) {
Match(tc.test_body, context.get());
}
}
INSTANTIATE_TEST_SUITE_P(OpEntryPointFoldingTest, EntryPointFoldingTest,
::testing::Values(
// Test case 0: Basic test 1
InstructionFoldingCase<bool>(std::string() +
"; CHECK: OpEntryPoint Fragment %2 \"main\" %3\n" +
"OpCapability Shader\n" +
"%1 = OpExtInstImport \"GLSL.std.450\"\n" +
"OpMemoryModel Logical GLSL450\n" +
"OpEntryPoint Fragment %2 \"main\" %3 %3 %3\n" +
"OpExecutionMode %2 OriginUpperLeft\n" +
"OpSource GLSL 430\n" +
"OpDecorate %3 Location 0\n" +
"%void = OpTypeVoid\n" +
"%5 = OpTypeFunction %void\n" +
"%float = OpTypeFloat 32\n" +
"%v4float = OpTypeVector %float 4\n" +
"%_ptr_Output_v4float = OpTypePointer Output %v4float\n" +
"%3 = OpVariable %_ptr_Output_v4float Output\n" +
"%int = OpTypeInt 32 1\n" +
"%int_0 = OpConstant %int 0\n" +
"%_ptr_PushConstant_v4float = OpTypePointer PushConstant %v4float\n" +
"%2 = OpFunction %void None %5\n" +
"%12 = OpLabel\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
9, true),
InstructionFoldingCase<bool>(std::string() +
"; CHECK: OpEntryPoint Fragment %2 \"main\" %3 %4\n" +
"OpCapability Shader\n" +
"%1 = OpExtInstImport \"GLSL.std.450\"\n" +
"OpMemoryModel Logical GLSL450\n" +
"OpEntryPoint Fragment %2 \"main\" %3 %4 %3\n" +
"OpExecutionMode %2 OriginUpperLeft\n" +
"OpSource GLSL 430\n" +
"OpDecorate %3 Location 0\n" +
"%void = OpTypeVoid\n" +
"%5 = OpTypeFunction %void\n" +
"%float = OpTypeFloat 32\n" +
"%v4float = OpTypeVector %float 4\n" +
"%_ptr_Output_v4float = OpTypePointer Output %v4float\n" +
"%3 = OpVariable %_ptr_Output_v4float Output\n" +
"%4 = OpVariable %_ptr_Output_v4float Output\n" +
"%int = OpTypeInt 32 1\n" +
"%int_0 = OpConstant %int 0\n" +
"%_ptr_PushConstant_v4float = OpTypePointer PushConstant %v4float\n" +
"%2 = OpFunction %void None %5\n" +
"%12 = OpLabel\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
9, true),
InstructionFoldingCase<bool>(std::string() +
"; CHECK: OpEntryPoint Fragment %2 \"main\" %4 %3\n" +
"OpCapability Shader\n" +
"%1 = OpExtInstImport \"GLSL.std.450\"\n" +
"OpMemoryModel Logical GLSL450\n" +
"OpEntryPoint Fragment %2 \"main\" %4 %4 %3\n" +
"OpExecutionMode %2 OriginUpperLeft\n" +
"OpSource GLSL 430\n" +
"OpDecorate %3 Location 0\n" +
"%void = OpTypeVoid\n" +
"%5 = OpTypeFunction %void\n" +
"%float = OpTypeFloat 32\n" +
"%v4float = OpTypeVector %float 4\n" +
"%_ptr_Output_v4float = OpTypePointer Output %v4float\n" +
"%3 = OpVariable %_ptr_Output_v4float Output\n" +
"%4 = OpVariable %_ptr_Output_v4float Output\n" +
"%int = OpTypeInt 32 1\n" +
"%int_0 = OpConstant %int 0\n" +
"%_ptr_PushConstant_v4float = OpTypePointer PushConstant %v4float\n" +
"%2 = OpFunction %void None %5\n" +
"%12 = OpLabel\n" +
"OpReturn\n" +
"OpFunctionEnd\n",
9, true)
));
using SPV14FoldingTest =
::testing::TestWithParam<InstructionFoldingCase<bool>>;
TEST_P(SPV14FoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_4, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
std::unique_ptr<Instruction> original_inst(inst->Clone(context.get()));
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
EXPECT_EQ(succeeded, tc.expected_result);
if (succeeded) {
Match(tc.test_body, context.get());
}
}
INSTANTIATE_TEST_SUITE_P(SPV14FoldingTest, SPV14FoldingTest,
::testing::Values(
// Test case 0: select vectors with scalar condition.
InstructionFoldingCase<bool>(std::string() +
"; CHECK-NOT: OpSelect\n" +
"; CHECK: %3 = OpCopyObject {{%\\w+}} %1\n" +
"OpCapability Shader\n" +
"OpCapability Linkage\n" +
"%void = OpTypeVoid\n" +
"%bool = OpTypeBool\n" +
"%true = OpConstantTrue %bool\n" +
"%int = OpTypeInt 32 0\n" +
"%int4 = OpTypeVector %int 4\n" +
"%int_0 = OpConstant %int 0\n" +
"%int_1 = OpConstant %int 1\n" +
"%1 = OpUndef %int4\n" +
"%2 = OpUndef %int4\n" +
"%void_fn = OpTypeFunction %void\n" +
"%func = OpFunction %void None %void_fn\n" +
"%entry = OpLabel\n" +
"%3 = OpSelect %int4 %true %1 %2\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
3, true),
// Test case 1: select struct with scalar condition.
InstructionFoldingCase<bool>(std::string() +
"; CHECK-NOT: OpSelect\n" +
"; CHECK: %3 = OpCopyObject {{%\\w+}} %2\n" +
"OpCapability Shader\n" +
"OpCapability Linkage\n" +
"%void = OpTypeVoid\n" +
"%bool = OpTypeBool\n" +
"%true = OpConstantFalse %bool\n" +
"%int = OpTypeInt 32 0\n" +
"%struct = OpTypeStruct %int %int %int %int\n" +
"%int_0 = OpConstant %int 0\n" +
"%int_1 = OpConstant %int 1\n" +
"%1 = OpUndef %struct\n" +
"%2 = OpUndef %struct\n" +
"%void_fn = OpTypeFunction %void\n" +
"%func = OpFunction %void None %void_fn\n" +
"%entry = OpLabel\n" +
"%3 = OpSelect %struct %true %1 %2\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
3, true),
// Test case 1: select array with scalar condition.
InstructionFoldingCase<bool>(std::string() +
"; CHECK-NOT: OpSelect\n" +
"; CHECK: %3 = OpCopyObject {{%\\w+}} %2\n" +
"OpCapability Shader\n" +
"OpCapability Linkage\n" +
"%void = OpTypeVoid\n" +
"%bool = OpTypeBool\n" +
"%true = OpConstantFalse %bool\n" +
"%int = OpTypeInt 32 0\n" +
"%int_0 = OpConstant %int 0\n" +
"%int_1 = OpConstant %int 1\n" +
"%int_4 = OpConstant %int 4\n" +
"%array = OpTypeStruct %int %int %int %int\n" +
"%1 = OpUndef %array\n" +
"%2 = OpUndef %array\n" +
"%void_fn = OpTypeFunction %void\n" +
"%func = OpFunction %void None %void_fn\n" +
"%entry = OpLabel\n" +
"%3 = OpSelect %array %true %1 %2\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
3, true)
));
std::string FloatControlsHeader(const std::string& capabilities) {
std::string header = R"(
OpCapability Shader
)" + capabilities + R"(
%void = OpTypeVoid
%float = OpTypeFloat 32
%float_0 = OpConstant %float 0
%float_1 = OpConstant %float 1
%void_fn = OpTypeFunction %void
%func = OpFunction %void None %void_fn
%entry = OpLabel
)";
return header;
}
using FloatControlsFoldingTest =
::testing::TestWithParam<InstructionFoldingCase<bool>>;
TEST_P(FloatControlsFoldingTest, Case) {
const auto& tc = GetParam();
// Build module.
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_4, nullptr, tc.test_body,
SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
ASSERT_NE(nullptr, context);
// Fold the instruction to test.
analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold);
std::unique_ptr<Instruction> original_inst(inst->Clone(context.get()));
bool succeeded = context->get_instruction_folder().FoldInstruction(inst);
EXPECT_EQ(succeeded, tc.expected_result);
if (succeeded) {
Match(tc.test_body, context.get());
}
}
INSTANTIATE_TEST_SUITE_P(FloatControlsFoldingTest, FloatControlsFoldingTest,
::testing::Values(
// Test case 0: no folding with DenormPreserve
InstructionFoldingCase<bool>(FloatControlsHeader("OpCapability DenormPreserve") +
"%1 = OpFAdd %float %float_0 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
1, false),
// Test case 1: no folding with DenormFlushToZero
InstructionFoldingCase<bool>(FloatControlsHeader("OpCapability DenormFlushToZero") +
"%1 = OpFAdd %float %float_0 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
1, false),
// Test case 2: no folding with SignedZeroInfNanPreserve
InstructionFoldingCase<bool>(FloatControlsHeader("OpCapability SignedZeroInfNanPreserve") +
"%1 = OpFAdd %float %float_0 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
1, false),
// Test case 3: no folding with RoundingModeRTE
InstructionFoldingCase<bool>(FloatControlsHeader("OpCapability RoundingModeRTE") +
"%1 = OpFAdd %float %float_0 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
1, false),
// Test case 4: no folding with RoundingModeRTZ
InstructionFoldingCase<bool>(FloatControlsHeader("OpCapability RoundingModeRTZ") +
"%1 = OpFAdd %float %float_0 %float_1\n" +
"OpReturn\n" +
"OpFunctionEnd\n"
,
1, false)
));
std::string ImageOperandsTestBody(const std::string& image_instruction) {
std::string body = R"(
OpCapability Shader
OpCapability ImageGatherExtended
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpDecorate %Texture DescriptorSet 0
OpDecorate %Texture Binding 0
%int = OpTypeInt 32 1
%int_n1 = OpConstant %int -1
%5 = OpConstant %int 0
%float = OpTypeFloat 32
%float_0 = OpConstant %float 0
%type_2d_image = OpTypeImage %float 2D 2 0 0 1 Unknown
%type_sampled_image = OpTypeSampledImage %type_2d_image
%type_sampler = OpTypeSampler
%_ptr_UniformConstant_type_sampler = OpTypePointer UniformConstant %type_sampler
%_ptr_UniformConstant_type_2d_image = OpTypePointer UniformConstant %type_2d_image
%_ptr_int = OpTypePointer Function %int
%v2int = OpTypeVector %int 2
%10 = OpTypeVector %float 4
%void = OpTypeVoid
%22 = OpTypeFunction %void
%v2float = OpTypeVector %float 2
%v3int = OpTypeVector %int 3
%Texture = OpVariable %_ptr_UniformConstant_type_2d_image UniformConstant
%gSampler = OpVariable %_ptr_UniformConstant_type_sampler UniformConstant
%101 = OpConstantComposite %v2int %int_n1 %int_n1
%20 = OpConstantComposite %v2float %float_0 %float_0
%main = OpFunction %void None %22
%23 = OpLabel
%var = OpVariable %_ptr_int Function
%88 = OpLoad %type_2d_image %Texture
%val = OpLoad %int %var
%sampler = OpLoad %type_sampler %gSampler
%26 = OpSampledImage %type_sampled_image %88 %sampler
)" + image_instruction + R"(
OpReturn
OpFunctionEnd
)";
return body;
}
INSTANTIATE_TEST_SUITE_P(ImageOperandsBitmaskFoldingTest, MatchingInstructionWithNoResultFoldingTest,
::testing::Values(
// Test case 0: OpImageFetch without Offset
InstructionFoldingCase<bool>(ImageOperandsTestBody(
"%89 = OpImageFetch %10 %88 %101 Lod %5 \n")
, 89, false),
// Test case 1: OpImageFetch with non-const offset
InstructionFoldingCase<bool>(ImageOperandsTestBody(
"%89 = OpImageFetch %10 %88 %101 Lod|Offset %5 %val \n")
, 89, false),
// Test case 2: OpImageFetch with Lod and Offset
InstructionFoldingCase<bool>(ImageOperandsTestBody(
" %89 = OpImageFetch %10 %88 %101 Lod|Offset %5 %101 \n"
"; CHECK: %89 = OpImageFetch %10 %88 %101 Lod|ConstOffset %5 %101 \n")
, 89, true),
// Test case 3: OpImageFetch with Bias and Offset
InstructionFoldingCase<bool>(ImageOperandsTestBody(
" %89 = OpImageFetch %10 %88 %101 Bias|Offset %5 %101 \n"
"; CHECK: %89 = OpImageFetch %10 %88 %101 Bias|ConstOffset %5 %101 \n")
, 89, true),
// Test case 4: OpImageFetch with Grad and Offset.
// Grad adds 2 operands to the instruction.
InstructionFoldingCase<bool>(ImageOperandsTestBody(
" %89 = OpImageFetch %10 %88 %101 Grad|Offset %5 %5 %101 \n"
"; CHECK: %89 = OpImageFetch %10 %88 %101 Grad|ConstOffset %5 %5 %101 \n")
, 89, true),
// Test case 5: OpImageFetch with Offset and MinLod.
// This is an example of a case where the bitmask bit-offset is larger than
// that of the Offset.
InstructionFoldingCase<bool>(ImageOperandsTestBody(
" %89 = OpImageFetch %10 %88 %101 Offset|MinLod %101 %5 \n"
"; CHECK: %89 = OpImageFetch %10 %88 %101 ConstOffset|MinLod %101 %5 \n")
, 89, true),
// Test case 6: OpImageGather with constant Offset
InstructionFoldingCase<bool>(ImageOperandsTestBody(
" %89 = OpImageGather %10 %26 %20 %5 Offset %101 \n"
"; CHECK: %89 = OpImageGather %10 %26 %20 %5 ConstOffset %101 \n")
, 89, true),
// Test case 7: OpImageWrite with constant Offset
InstructionFoldingCase<bool>(ImageOperandsTestBody(
" OpImageWrite %88 %5 %101 Offset %101 \n"
"; CHECK: OpImageWrite %88 %5 %101 ConstOffset %101 \n")
, 0 /* No result-id */, true)
));
} // namespace
} // namespace opt
} // namespace spvtools
| endlessm/chromium-browser | third_party/swiftshader/third_party/SPIRV-Tools/test/opt/fold_test.cpp | C++ | bsd-3-clause | 295,349 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8TestSpecialOperations.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/UnionTypesCore.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8Node.h"
#include "bindings/core/v8/V8NodeList.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/NameNodeList.h"
#include "core/dom/NodeList.h"
#include "core/dom/StaticNodeList.h"
#include "core/html/LabelsNodeList.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
const WrapperTypeInfo V8TestSpecialOperations::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestSpecialOperations::domTemplate, V8TestSpecialOperations::refObject, V8TestSpecialOperations::derefObject, V8TestSpecialOperations::trace, 0, 0, 0, V8TestSpecialOperations::installConditionallyEnabledMethods, V8TestSpecialOperations::installConditionallyEnabledProperties, 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::Independent, WrapperTypeInfo::RefCountedObject };
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestSpecialOperations.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TestSpecialOperations::s_wrapperTypeInfo = V8TestSpecialOperations::wrapperTypeInfo;
namespace TestSpecialOperationsV8Internal {
static void namedItemMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "namedItem", "TestSpecialOperations", 1, info.Length()), info.GetIsolate());
return;
}
TestSpecialOperations* impl = V8TestSpecialOperations::toImpl(info.Holder());
V8StringResource<> name;
{
TOSTRING_VOID_INTERNAL(name, info[0]);
}
NodeOrNodeList result;
impl->getItem(name, result);
v8SetReturnValue(info, result);
}
static void namedItemMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
TestSpecialOperationsV8Internal::namedItemMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void namedPropertyGetter(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestSpecialOperations* impl = V8TestSpecialOperations::toImpl(info.Holder());
AtomicString propertyName = toCoreAtomicString(name);
NodeOrNodeList result;
impl->getItem(propertyName, result);
if (result.isNull())
return;
v8SetReturnValue(info, result);
}
static void namedPropertyGetterCallback(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMNamedProperty");
TestSpecialOperationsV8Internal::namedPropertyGetter(name, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void namedPropertySetter(v8::Local<v8::String> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestSpecialOperations* impl = V8TestSpecialOperations::toImpl(info.Holder());
TOSTRING_VOID(V8StringResource<>, propertyName, name);
Node* propertyValue = V8Node::toImplWithTypeCheck(info.GetIsolate(), v8Value);
bool result = impl->anonymousNamedSetter(propertyName, propertyValue);
if (!result)
return;
v8SetReturnValue(info, v8Value);
}
static void namedPropertySetterCallback(v8::Local<v8::String> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMNamedProperty");
TestSpecialOperationsV8Internal::namedPropertySetter(name, v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void namedPropertyQuery(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Integer>& info)
{
TestSpecialOperations* impl = V8TestSpecialOperations::toImpl(info.Holder());
AtomicString propertyName = toCoreAtomicString(name);
v8::String::Utf8Value namedProperty(name);
ExceptionState exceptionState(ExceptionState::GetterContext, *namedProperty, "TestSpecialOperations", info.Holder(), info.GetIsolate());
bool result = impl->namedPropertyQuery(propertyName, exceptionState);
if (exceptionState.throwIfNeeded())
return;
if (!result)
return;
v8SetReturnValueInt(info, v8::None);
}
static void namedPropertyQueryCallback(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Integer>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMNamedProperty");
TestSpecialOperationsV8Internal::namedPropertyQuery(name, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void namedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info)
{
TestSpecialOperations* impl = V8TestSpecialOperations::toImpl(info.Holder());
Vector<String> names;
ExceptionState exceptionState(ExceptionState::EnumerationContext, "TestSpecialOperations", info.Holder(), info.GetIsolate());
impl->namedPropertyEnumerator(names, exceptionState);
if (exceptionState.throwIfNeeded())
return;
v8::Handle<v8::Array> v8names = v8::Array::New(info.GetIsolate(), names.size());
for (size_t i = 0; i < names.size(); ++i)
v8names->Set(v8::Integer::New(info.GetIsolate(), i), v8String(info.GetIsolate(), names[i]));
v8SetReturnValue(info, v8names);
}
static void namedPropertyEnumeratorCallback(const v8::PropertyCallbackInfo<v8::Array>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMNamedProperty");
TestSpecialOperationsV8Internal::namedPropertyEnumerator(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace TestSpecialOperationsV8Internal
static const V8DOMConfiguration::MethodConfiguration V8TestSpecialOperationsMethods[] = {
{"namedItem", TestSpecialOperationsV8Internal::namedItemMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
};
static void installV8TestSpecialOperationsTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "TestSpecialOperations", v8::Local<v8::FunctionTemplate>(), V8TestSpecialOperations::internalFieldCount,
0, 0,
0, 0,
V8TestSpecialOperationsMethods, WTF_ARRAY_LENGTH(V8TestSpecialOperationsMethods),
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
functionTemplate->InstanceTemplate()->SetNamedPropertyHandler(TestSpecialOperationsV8Internal::namedPropertyGetterCallback, TestSpecialOperationsV8Internal::namedPropertySetterCallback, TestSpecialOperationsV8Internal::namedPropertyQueryCallback, 0, TestSpecialOperationsV8Internal::namedPropertyEnumeratorCallback);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8TestSpecialOperations::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TestSpecialOperationsTemplate);
}
bool V8TestSpecialOperations::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8TestSpecialOperations::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TestSpecialOperations* V8TestSpecialOperations::toImplWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? blink::toScriptWrappableBase(v8::Handle<v8::Object>::Cast(value))->toImpl<TestSpecialOperations>() : 0;
}
void V8TestSpecialOperations::refObject(ScriptWrappableBase* scriptWrappableBase)
{
scriptWrappableBase->toImpl<TestSpecialOperations>()->ref();
}
void V8TestSpecialOperations::derefObject(ScriptWrappableBase* scriptWrappableBase)
{
scriptWrappableBase->toImpl<TestSpecialOperations>()->deref();
}
template<>
v8::Handle<v8::Value> toV8NoInline(TestSpecialOperations* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace blink
| smilusingjavascript/blink | Source/bindings/tests/results/core/V8TestSpecialOperations.cpp | C++ | bsd-3-clause | 9,221 |
/*============================================================================*
* *
* This file is part of the Zoto Software suite. *
* *
* Copyright (C) 2004 Zoto, Inc. 123 South Hudson, OKC, OK 73102 *
* *
* Original algorithms taken from RFC 1321 *
* Copyright (C) 1990-2, RSA Data Security, Inc. *
* *
*============================================================================*/
#include <Python.h>
#include "ZTypes.h"
#include "ZGlobals.h"
extern void initialize_zsp_header(PyObject *m);
extern void initialize_zsp_auth(PyObject *m);
extern void initialize_zsp_auth_resp(PyObject *m);
extern void initialize_zsp_version(PyObject *m);
extern void initialize_zsp_version_resp(PyObject *m);
extern void initialize_zsp_flag(PyObject *m);
extern void initialize_zsp_flag_resp(PyObject *m);
extern void initialize_zsp_file(PyObject *m);
extern void initialize_zsp_file_resp(PyObject *m);
extern void initialize_zsp_done(PyObject *m);
extern void initialize_zsp_done_resp(PyObject *m);
extern void initialize_zsp_error(PyObject *m);
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif
static PyMethodDef module_methods[] = {
{NULL} /* Sentinel */
};
PyMODINIT_FUNC
initzsp_packets(void)
{
PyObject *m;
m = Py_InitModule3("zsp_packets", module_methods,
"Authorization packet.");
if (m == NULL)
return;
PyModule_AddIntConstant(m, "ZSP_NONE", ZSP_NONE);
PyModule_AddIntConstant(m, "ZSP_QUIT", ZSP_QUIT);
PyModule_AddIntConstant(m, "ZSP_AUTH", ZSP_AUTH);
PyModule_AddIntConstant(m, "ZSP_VERSION", ZSP_VERSION);
PyModule_AddIntConstant(m, "ZSP_FLAG", ZSP_FLAG);
PyModule_AddIntConstant(m, "ZSP_FILE", ZSP_FILE);
PyModule_AddIntConstant(m, "ZSP_DONE", ZSP_DONE);
PyModule_AddIntConstant(m, "ZSP_QUIT_RESP", ZSP_QUIT_RESP);
PyModule_AddIntConstant(m, "ZSP_AUTH_RESP", ZSP_AUTH_RESP);
PyModule_AddIntConstant(m, "ZSP_VERSION_RESP", ZSP_VERSION_RESP);
PyModule_AddIntConstant(m, "ZSP_FLAG_RESP", ZSP_FLAG_RESP);
PyModule_AddIntConstant(m, "ZSP_FILE_RESP", ZSP_FILE_RESP);
PyModule_AddIntConstant(m, "ZSP_DONE_RESP", ZSP_DONE_RESP);
PyModule_AddIntConstant(m, "ZSP_ERROR", ZSP_ERROR);
PyModule_AddIntConstant(m, "ZSP_JPEG", ZSP_JPEG);
PyModule_AddIntConstant(m, "ZSP_PNG", ZSP_PNG);
PyModule_AddIntConstant(m, "ZSP_GIF", ZSP_GIF);
PyModule_AddIntConstant(m, "ZSP_BMP", ZSP_BMP);
PyModule_AddIntConstant(m, "ZSP_TIFF", ZSP_TIFF);
PyModule_AddIntConstant(m, "ZSP_TARGA", ZSP_TARGA);
// Return codes
PyModule_AddIntConstant(m, "ZSP_AUTH_OK", ZSP_AUTH_OK);
PyModule_AddIntConstant(m, "ZSP_AUTH_BAD", ZSP_AUTH_BAD);
PyModule_AddIntConstant(m, "ZSP_VERS_GOOD", ZSP_VERS_GOOD);
PyModule_AddIntConstant(m, "ZSP_VERS_OLD", ZSP_VERS_OLD);
PyModule_AddIntConstant(m, "ZSP_VERS_BAD", ZSP_VERS_BAD);
PyModule_AddIntConstant(m, "ZSP_FILE_OK", ZSP_FILE_OK);
PyModule_AddIntConstant(m, "ZSP_FILE_NO_FLAG", ZSP_FILE_NO_FLAG);
PyModule_AddIntConstant(m, "ZSP_FILE_BAD", ZSP_FILE_BAD);
PyModule_AddIntConstant(m, "ZSP_DONE_OK", ZSP_DONE_OK);
PyModule_AddIntConstant(m, "ZSP_DONE_BAD_SUM", ZSP_DONE_BAD_SUM);
PyModule_AddIntConstant(m, "ZSP_DONE_BAD_SYNC", ZSP_DONE_BAD_SYNC);
PyModule_AddIntConstant(m, "ZSP_DONE_BAD_SYNC2", ZSP_DONE_BAD_SYNC2);
PyModule_AddIntConstant(m, "ZSP_DONE_CORRUPT", ZSP_DONE_CORRUPT);
PyModule_AddIntConstant(m, "ZSP_DONE_BAD_WRITE", ZSP_DONE_BAD_WRITE);
initialize_zsp_header(m);
initialize_zsp_auth(m);
initialize_zsp_auth_resp(m);
initialize_zsp_version(m);
initialize_zsp_version_resp(m);
initialize_zsp_flag(m);
initialize_zsp_flag_resp(m);
initialize_zsp_file(m);
initialize_zsp_file_resp(m);
initialize_zsp_done(m);
initialize_zsp_done_resp(m);
initialize_zsp_error(m);
}
| kordless/zoto-server | zulu-2.0/python_module/zsp_packets.c | C | bsd-3-clause | 3,830 |
/*
* $Id$
*/
/*
Copyright (c) 2000-2004 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.mail;
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.oro.text.regex.*;
import javax.mail.*;
import javax.mail.internet.*;
// import javax.activation.*;
import org.lockss.test.*;
import org.lockss.mail.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
public class TestMimeMessage extends LockssTestCase {
// The generated message is checked against these patterns, in a way that
// is too brittle (order dependent, etc.). If the format of the message
// changes innocuously the patterns and/or tests may have to be changed
static final String PAT_MESSAGE_ID = "^Message-ID: ";
static final String PAT_MIME_VERSION = "^MIME-Version: 1.0";
static final String PAT_CONTENT_TYPE = "^Content-Type: ";
static final String PAT_FROM = "^From: ";
static final String PAT_TO = "^To: ";
static final String PAT_BOUNDARY = "^------=_Part";
static final String PAT_CONTENT_TRANSFER_ENCODING =
"^Content-Transfer-Encoding: ";
static final String PAT_CONTENT_DISPOSITION = "^Content-Disposition: ";
String toString(MailMessage msg) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream out = new BufferedOutputStream(baos);
msg.writeData(out);
out.flush();
return baos.toString();
} catch (IOException e) {
throw new RuntimeException("Error converting MimeMessage to string", e);
}
}
/** Return the header part (lines preceding first blank line) */
String getHeader(String body) {
List lst = StringUtil.breakAt(body, "\r\n\r\n");
if (lst.size() < 1) return null;
return (String)lst.get(0);
}
/** Return the header part (lines preceding first blank line) */
String getHeader(MimeMessage msg) {
return getHeader(toString(msg));
}
/** Return the body part (lines following first blank line) */
String getBody(String body) {
int pos = body.indexOf("\r\n\r\n");
if (pos < 0) return null;
return body.substring(pos+4);
}
/** Return the body part (lines following first blank line) */
String getBody(MimeMessage msg) {
return getBody(toString(msg));
}
/** Break a string at <crlf>s into an array of lines */
String[] getLines(String body) {
List lst = StringUtil.breakAt(body, "\r\n");
return (String[])lst.toArray(new String[0]);
}
String[] getHeaderLines(MimeMessage msg) {
return getLines(getHeader(msg));
}
String[] getBodyLines(MimeMessage msg) {
return getLines(getBody(msg));
}
/** assert that the pattern exists in the string, interpreting the string
* as having multiple lines */
void assertHeaderLine(String expPat, String hdr) {
Pattern pat = RegexpUtil.uncheckedCompile(expPat,
Perl5Compiler.MULTILINE_MASK);
assertMatchesRE(pat, hdr);
}
/** assert that the message starts with the expected header */
void assertHeader(MimeMessage msg) {
assertHeader(null, null, msg);
}
/** assert that the message starts with the expected header */
void assertHeader(String expFrom, String expTo, MimeMessage msg) {
String hdr = getHeader(msg);
assertHeaderLine(PAT_MESSAGE_ID, hdr);
assertHeaderLine(PAT_MIME_VERSION, hdr);
assertHeaderLine(PAT_CONTENT_TYPE, hdr);
if (expFrom != null) {
assertHeaderLine(PAT_FROM + expFrom, hdr);
}
if (expTo != null) {
assertHeaderLine(PAT_TO + expTo, hdr);
}
}
/** assert that the array of lines is a MIME text-part with the expected
* text */
void assertTextPart(String expText, String[]lines, int idx) {
assertMatchesRE(PAT_BOUNDARY, lines[idx + 0]);
assertMatchesRE(PAT_CONTENT_TYPE + "text/plain; charset=us-ascii",
lines[idx + 1]);
assertMatchesRE(PAT_CONTENT_TRANSFER_ENCODING + "7bit",
lines[idx + 2]);
assertEquals("", lines[idx + 3]);
assertEquals(expText, lines[idx + 4]);
assertMatchesRE(PAT_BOUNDARY, lines[idx + 5]);
}
public void testNull() throws IOException {
MimeMessage msg = new MimeMessage();
assertHeader(msg);
assertEquals(2, getBodyLines(msg).length);
assertMatchesRE(PAT_BOUNDARY, getBody(msg));
assertEquals("", getBodyLines(msg)[1]);
}
public void testGetHeader() throws IOException {
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "me");
msg.addHeader("To", "you");
msg.addHeader("To", "and you");
assertEquals("me", msg.getHeader("From"));
assertEquals("you, and you", msg.getHeader("To"));
assertEquals(null, msg.getHeader("xxxx"));
}
public void testText() throws IOException {
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "me");
msg.addHeader("To", "you");
msg.addHeader("Subject", "topic");
msg.addTextPart("Message\ntext");
assertHeader("me", "you", msg);
String[] blines = getBodyLines(msg);
log.debug2("msg: " + StringUtil.separatedString(blines, ", "));
assertTextPart("Message\ntext", blines, 0);
}
public void testDot() throws IOException {
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "me");
msg.addHeader("To", "you");
msg.addTextPart("one\n.\ntwo\n");
assertHeader("me", "you", msg);
String[] blines = getBodyLines(msg);
log.debug2("msg: " + StringUtil.separatedString(blines, ", "));
assertTextPart("one\n.\ntwo\n", blines, 0);
}
public void testTextAndFile() throws IOException {
File file = FileTestUtil.writeTempFile("XXX",
"\000\001\254\255this is a test");
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "us");
msg.addHeader("To", "them");
msg.addHeader("Subject", "object");
msg.addTextPart("Explanatory text");
msg.addFile(file, "file.foo");
assertHeader("us", "them", msg);
String[] blines = getBodyLines(msg);
log.debug2("msg: " + StringUtil.separatedString(blines, ", "));
assertTextPart("Explanatory text", blines, 0);
assertMatchesRE(PAT_CONTENT_TYPE +
"application/octet-stream; name=file.foo", blines[6]);
assertMatchesRE(PAT_CONTENT_TRANSFER_ENCODING + "base64", blines[7]);
assertMatchesRE(PAT_CONTENT_DISPOSITION, blines[8]);
assertEquals("", blines[9]);
assertEquals("AAGsrXRoaXMgaXMgYSB0ZXN0", blines[10]);
assertMatchesRE(PAT_BOUNDARY, blines[11]);
assertTrue(file.exists());
msg.delete(true);
assertTrue(file.exists());
}
public void testGetParts() throws Exception {
File file = FileTestUtil.writeTempFile("XXX",
"\000\001\254\255this is a test");
MimeMessage msg = new MimeMessage();
msg.addTextPart("foo text");
msg.addFile(file, "file.foo");
MimeBodyPart[] parts = msg.getParts();
assertEquals(2, parts.length);
assertEquals("foo text", parts[0].getContent());
assertEquals("file.foo", parts[1].getFileName());
}
public void testTmpFile() throws IOException {
File file = FileTestUtil.writeTempFile("XXX",
"\000\001\254\255this is a test");
MimeMessage msg = new MimeMessage();
msg.addTmpFile(file, "file.foo");
assertTrue(file.exists());
msg.delete(true);
assertFalse(file.exists());
}
}
| edina/lockss-daemon | test/src/org/lockss/mail/TestMimeMessage.java | Java | bsd-3-clause | 8,543 |
# - Find LevelDB
#
# LEVELDB_INCLUDE_DIRS - List of LevelDB includes.
# LEVELDB_LIBRARIES - List of libraries when using LevelDB.
# LEVELDB_FOUND - True if LevelDB found
# Look for the header of file.
find_path(LEVELDB_INCLUDE NAMES leveldb/db.h
PATHS $ENV{LEVELDB_ROOT}/include /opt/local/include /usr/local/include /usr/include
DOC "Path in which the file leveldb/db.h is located.")
# Look for the library.
find_library(LEVELDB_LIBRARY NAMES leveldb
PATHS $ENV{LEVELDB_ROOT}/lib /usr/local/lib /usr/lib
DOC "Path to leveldb library.")
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(LevelDB DEFAULT_MSG LEVELDB_INCLUDE LEVELDB_LIBRARY)
if(LEVELDB_FOUND)
set(LEVELDB_INCLUDE_DIRS ${LEVELDB_INCLUDE})
set(LEVELDB_LIBRARIES ${LEVELDB_LIBRARY})
mark_as_advanced(LEVELDB_INCLUDE LEVELDB_LIBRARY)
message(STATUS "Found LevelDB (include: ${LEVELDB_INCLUDE_DIRS}, library: ${LEVELDB_LIBRARIES})")
endif()
| QiumingLu/saber | cmake/Modules/FindLevelDB.cmake | CMake | bsd-3-clause | 1,061 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31.c
Label Definition File: CWE90_LDAP_Injection__w32.label.xml
Template File: sources-sink-31.tmpl.c
*/
/*
* @description
* CWE: 90 LDAP Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Use a fixed string
* Sinks:
* BadSink : data concatenated into LDAP search, which could result in LDAP Injection
* Flow Variant: 31 Data flow using a copy of data within the same function
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#include <Winldap.h>
#pragma comment(lib, "wldap32")
#ifndef OMITBAD
void CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_bad()
{
wchar_t * data;
wchar_t dataBuffer[256] = L"";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (256 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
{
wchar_t * dataCopy = data;
wchar_t * data = dataCopy;
{
LDAP* pLdapConnection = NULL;
ULONG connectSuccess = 0L;
ULONG searchSuccess = 0L;
LDAPMessage *pMessage = NULL;
wchar_t filter[256];
/* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
_snwprintf(filter, 256-1, L"(cn=%s)", data);
pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
if (pLdapConnection == NULL)
{
printLine("Initialization failed");
exit(1);
}
connectSuccess = ldap_connect(pLdapConnection, NULL);
if (connectSuccess != LDAP_SUCCESS)
{
printLine("Connection failed");
exit(1);
}
searchSuccess = ldap_search_ext_sW(
pLdapConnection,
L"base",
LDAP_SCOPE_SUBTREE,
filter,
NULL,
0,
NULL,
NULL,
LDAP_NO_LIMIT,
LDAP_NO_LIMIT,
&pMessage);
if (searchSuccess != LDAP_SUCCESS)
{
printLine("Search failed");
if (pMessage != NULL)
{
ldap_msgfree(pMessage);
}
exit(1);
}
/* Typically you would do something with the search results, but this is a test case and we can ignore them */
/* Free the results to avoid incidentals */
if (pMessage != NULL)
{
ldap_msgfree(pMessage);
}
/* Close the connection */
ldap_unbind(pLdapConnection);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[256] = L"";
data = dataBuffer;
/* FIX: Use a fixed file name */
wcscat(data, L"Doe, XXXXX");
{
wchar_t * dataCopy = data;
wchar_t * data = dataCopy;
{
LDAP* pLdapConnection = NULL;
ULONG connectSuccess = 0L;
ULONG searchSuccess = 0L;
LDAPMessage *pMessage = NULL;
wchar_t filter[256];
/* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
_snwprintf(filter, 256-1, L"(cn=%s)", data);
pLdapConnection = ldap_initW(L"localhost", LDAP_PORT);
if (pLdapConnection == NULL)
{
printLine("Initialization failed");
exit(1);
}
connectSuccess = ldap_connect(pLdapConnection, NULL);
if (connectSuccess != LDAP_SUCCESS)
{
printLine("Connection failed");
exit(1);
}
searchSuccess = ldap_search_ext_sW(
pLdapConnection,
L"base",
LDAP_SCOPE_SUBTREE,
filter,
NULL,
0,
NULL,
NULL,
LDAP_NO_LIMIT,
LDAP_NO_LIMIT,
&pMessage);
if (searchSuccess != LDAP_SUCCESS)
{
printLine("Search failed");
if (pMessage != NULL)
{
ldap_msgfree(pMessage);
}
exit(1);
}
/* Typically you would do something with the search results, but this is a test case and we can ignore them */
/* Free the results to avoid incidentals */
if (pMessage != NULL)
{
ldap_msgfree(pMessage);
}
/* Close the connection */
ldap_unbind(pLdapConnection);
}
}
}
void CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE90_LDAP_Injection/CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31.c | C | bsd-3-clause | 8,856 |
/*
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007 MobileRobots Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
MobileRobots Inc, 19 Columbia Drive, Amherst, NH 03031; 800-639-9481
*/
#ifndef ARACTIONGOTOSTRAIGHT_H
#define ARACTIONGOTOSTRAIGHT_H
#include "ariaTypedefs.h"
#include "ariaUtil.h"
#include "ArAction.h"
/// This action goes to a given ArPose very naively
/**
This action naively drives straight towards a given ArPose. The
action stops the robot when it has travelled the distance that that
pose is away. It travels at 'speed' mm/sec.
You can give it a new goal pose with setGoal(), cancel its movement
with cancelGoal(), and see if it got there with haveAchievedGoal().
For arguments to the goals and encoder goals you can tell it to go
backwards by calling them with the backwards parameter true. If
you set the justDistance to true it will only really care about
having driven the distance, if false it'll try to get to the spot
you wanted within close distance.
This doesn't avoid obstacles or anything, you could add have an obstacle
avoidance ArAction at a higher priority to try to do this. (For
truly intelligent navigation, see ActivMedia's ARNL software.)
**/
class ArActionGotoStraight : public ArAction
{
public:
AREXPORT ArActionGotoStraight(const char *name = "goto",
double speed = 400);
AREXPORT virtual ~ArActionGotoStraight();
/// Sees if the goal has been achieved
AREXPORT bool haveAchievedGoal(void);
/// Cancels the goal the robot has
AREXPORT void cancelGoal(void);
/// Sets a new goal and sets the action to go there
AREXPORT void setGoal(ArPose goal, bool backwards = false,
bool justDistance = true);
/// Sets the goal in a relative way
AREXPORT void setGoalRel(double dist, double deltaHeading,
bool backwards = false, bool justDistance = true);
/// Gets the goal the action has
ArPose getGoal(void) { return myGoal; }
/// Gets whether we're using the encoder goal or the normal goal
bool usingEncoderGoal(void) { return myUseEncoderGoal; }
/// Sets a new goal and sets the action to go there
AREXPORT void setEncoderGoal(ArPose encoderGoal, bool backwards = false,
bool justDistance = true);
/// Sets the goal in a relative way
AREXPORT void setEncoderGoalRel(double dist, double deltaHeading,
bool backwards = false,
bool justDistance = true);
/// Gets the goal the action has
ArPose getEncoderGoal(void) { return myEncoderGoal; }
/// Sets the speed the action will travel to the goal at (mm/sec)
void setSpeed(double speed) { mySpeed = speed; }
/// Gets the speed the action will travel to the goal at (mm/sec)
double getSpeed(void) { return mySpeed; }
/// Sets how close we have to get if we're not in just distance mode
void setCloseDist(double closeDist = 100) { myCloseDist = closeDist; }
/// Gets how close we have to get if we're not in just distance mode
double getCloseDist(void) { return myCloseDist; }
/// Sets whether we're backing up there or not (set in the setGoals)
bool getBacking(void) { return myBacking; }
AREXPORT virtual ArActionDesired *fire(ArActionDesired currentDesired);
/*AREXPORT*/ virtual ArActionDesired *getDesired(void) { return &myDesired; }
#ifndef SWIG
/*AREXPORT*/ virtual const ArActionDesired *getDesired(void) const
{ return &myDesired; }
#endif
protected:
ArPose myGoal;
bool myUseEncoderGoal;
ArPose myEncoderGoal;
double mySpeed;
bool myBacking;
ArActionDesired myDesired;
bool myPrinting;
double myDist;
double myCloseDist;
bool myJustDist;
double myDistTravelled;
ArPose myLastPose;
enum State
{
STATE_NO_GOAL,
STATE_ACHIEVED_GOAL,
STATE_GOING_TO_GOAL
};
State myState;
};
#endif // ARACTIONGOTO
| bigjun/mrpt | libs/hwdrivers/src/aria/include/ArActionGotoStraight.h | C | bsd-3-clause | 4,790 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_MEDIA_WEBRTC_SAME_ORIGIN_OBSERVER_H_
#define CHROME_BROWSER_MEDIA_WEBRTC_SAME_ORIGIN_OBSERVER_H_
#include "base/callback.h"
#include "content/public/browser/web_contents_observer.h"
#include "url/gurl.h"
namespace content {
class WebContents;
}
// This observer class will trigger the provided callback whenever the observed
// WebContents's origin either now or no longer matches the provided origin.
// This will not trigger the callback until the navigation has been committed,
// so that WebContents::GetLastCommittedURL will return the new origin, and thus
// allow for easier code re-use. Note that that Loading hasn't actually started
// yet, so this is still suitable for listening to for i.e. terminating tab
// capture when a site is no longer the same origin.
class SameOriginObserver : public content::WebContentsObserver {
public:
SameOriginObserver(content::WebContents* observed_contents,
const GURL& reference_origin,
base::RepeatingCallback<void(content::WebContents*)>
on_same_origin_state_changed);
~SameOriginObserver() override;
// WebContentsObserver
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
private:
content::WebContents* const observed_contents_;
const GURL reference_origin_;
base::RepeatingCallback<void(content::WebContents*)>
on_same_origin_state_changed_;
bool is_same_origin_ = false;
};
#endif // CHROME_BROWSER_MEDIA_WEBRTC_SAME_ORIGIN_OBSERVER_H_
| scheib/chromium | chrome/browser/media/webrtc/same_origin_observer.h | C | bsd-3-clause | 1,714 |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
<title>LeapVector Class Reference</title>
<meta id="xcode-display" name="xcode-display" content="render"/>
<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
<meta name="generator" content="appledoc 2.1 (build 858)" />
</head>
<body>
<header id="top_header">
<div id="library" class="hideInXcode">
<h1><a id="libraryTitle" href="../index.html">Leap Motion API </a></h1>
<a id="developerHome" href="../index.html">Leap Motion</a>
</div>
<div id="title" role="banner">
<h1 class="hideInXcode">LeapVector Class Reference</h1>
</div>
<ul id="headerButtons" role="toolbar">
<li id="toc_button">
<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents"><span class="disclosure"></span>Table of Contents</button>
</li>
<li id="jumpto_button" role="navigation">
<select id="jumpTo">
<option value="top">Jump To…</option>
<option value="overview">Overview</option>
<option value="tasks">Tasks</option>
<option value="properties">Properties</option>
<option value="//api/name/x"> x</option>
<option value="//api/name/y"> y</option>
<option value="//api/name/z"> z</option>
<option value="class_methods">Class Methods</option>
<option value="//api/name/backward"> + backward</option>
<option value="//api/name/down"> + down</option>
<option value="//api/name/forward"> + forward</option>
<option value="//api/name/left"> + left</option>
<option value="//api/name/right"> + right</option>
<option value="//api/name/up"> + up</option>
<option value="//api/name/xAxis"> + xAxis</option>
<option value="//api/name/yAxis"> + yAxis</option>
<option value="//api/name/zAxis"> + zAxis</option>
<option value="//api/name/zero"> + zero</option>
<option value="instance_methods">Instance Methods</option>
<option value="//api/name/angleTo:"> - angleTo:</option>
<option value="//api/name/cross:"> - cross:</option>
<option value="//api/name/distanceTo:"> - distanceTo:</option>
<option value="//api/name/divide:"> - divide:</option>
<option value="//api/name/dot:"> - dot:</option>
<option value="//api/name/equals:"> - equals:</option>
<option value="//api/name/initWithVector:"> - initWithVector:</option>
<option value="//api/name/initWithX:y:z:"> - initWithX:y:z:</option>
<option value="//api/name/magnitude"> - magnitude</option>
<option value="//api/name/magnitudeSquared"> - magnitudeSquared</option>
<option value="//api/name/minus:"> - minus:</option>
<option value="//api/name/negate"> - negate</option>
<option value="//api/name/normalized"> - normalized</option>
<option value="//api/name/pitch"> - pitch</option>
<option value="//api/name/plus:"> - plus:</option>
<option value="//api/name/roll"> - roll</option>
<option value="//api/name/times:"> - times:</option>
<option value="//api/name/toFloatPointer"> - toFloatPointer</option>
<option value="//api/name/toNSArray"> - toNSArray</option>
<option value="//api/name/yaw"> - yaw</option>
</select>
</li>
</ul>
</header>
<nav id="tocContainer" class="isShowingTOC">
<ul id="toc" role="tree">
<li role="treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#overview">Overview</a></span></li>
<li role="treeitem" id="task_treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#tasks">Tasks</a></span><ul>
</ul></li>
<li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#properties">Properties</a></span><ul>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/x">x</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/y">y</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/z">z</a></span></li>
</ul></li>
<li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#class_methods">Class Methods</a></span><ul>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/backward">backward</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/down">down</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/forward">forward</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/left">left</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/right">right</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/up">up</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/xAxis">xAxis</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/yAxis">yAxis</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/zAxis">zAxis</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/zero">zero</a></span></li>
</ul></li>
<li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#instance_methods">Instance Methods</a></span><ul>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/angleTo:">angleTo:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/cross:">cross:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/distanceTo:">distanceTo:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/divide:">divide:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/dot:">dot:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/equals:">equals:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/initWithVector:">initWithVector:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/initWithX:y:z:">initWithX:y:z:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/magnitude">magnitude</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/magnitudeSquared">magnitudeSquared</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/minus:">minus:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/negate">negate</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/normalized">normalized</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/pitch">pitch</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/plus:">plus:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/roll">roll</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/times:">times:</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/toFloatPointer">toFloatPointer</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/toNSArray">toNSArray</a></span></li>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/yaw">yaw</a></span></li>
</ul></li>
</ul>
</nav>
<article>
<div id="contents" class="isShowingTOC" role="main">
<a title="LeapVector Class Reference" name="top"></a>
<div class="main-navigation navigation-top">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="header">
<div class="section-header">
<h1 class="title title-header">LeapVector Class Reference</h1>
</div>
</div>
<div id="container">
<div class="section section-specification"><table cellspacing="0"><tbody>
<tr>
<td class="specification-title">Inherits from</td>
<td class="specification-value">NSObject</td>
</tr><tr>
<td class="specification-title">Declared in</td>
<td class="specification-value">LeapObjectiveC.h</td>
</tr>
</tbody></table></div>
<div class="section section-overview">
<a title="Overview" name="overview"></a>
<h2 class="subtitle subtitle-overview">Overview</h2>
<p>The LeapVector class represents a three-component mathematical vector or point<br/>
such as a direction or position in three-dimensional space.</p>
<p>The Leap software employs a right-handed Cartesian coordinate system.<br/>
Values given are in units of real-world millimeters. The origin is centered<br/>
at the center of the Leap device. The x- and z-axes lie in the horizontal<br/>
plane, with the x-axis running parallel to the long edge of the device.<br/>
The y-axis is vertical, with positive values increasing upwards (in contrast<br/>
to the downward orientation of most computer graphics coordinate systems).<br/>
The z-axis has positive values increasing away from the computer screen.</p>
<p><img src="../docs/images/Leap_Axes.png"/></p>
</div>
<div class="section section-tasks">
<a title="Tasks" name="tasks"></a>
<h2 class="subtitle subtitle-tasks">Tasks</h2>
<ul class="task-list">
<li>
<span class="tooltip">
<code><a href="#//api/name/initWithX:y:z:">– initWithX:y:z:</a></code>
<span class="tooltip"><p>Creates a new LeapVector with the specified component values.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/initWithVector:">– initWithVector:</a></code>
<span class="tooltip"><p>Copies the specified LeapVector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/magnitude">– magnitude</a></code>
<span class="tooltip"><p>The magnitude, or length, of this vector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/magnitudeSquared">– magnitudeSquared</a></code>
<span class="tooltip"><p>The square of the magnitude, or length, of this vector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/distanceTo:">– distanceTo:</a></code>
<span class="tooltip"><p>The distance between the point represented by this LeapVector<br/>
object and a point represented by the specified LeapVector object.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/angleTo:">– angleTo:</a></code>
<span class="tooltip"><p>The angle between this vector and the specified vector in radians.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/pitch">– pitch</a></code>
<span class="tooltip"><p>The pitch angle in radians.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/roll">– roll</a></code>
<span class="tooltip"><p>The roll angle in radians.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/yaw">– yaw</a></code>
<span class="tooltip"><p>The yaw angle in radians.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/plus:">– plus:</a></code>
<span class="tooltip"><p>Adds two vectors.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/minus:">– minus:</a></code>
<span class="tooltip"><p>Subtract a vector from this vector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/negate">– negate</a></code>
<span class="tooltip"><p>Negate this vector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/times:">– times:</a></code>
<span class="tooltip"><p>Multiply this vector by a number.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/divide:">– divide:</a></code>
<span class="tooltip"><p>Divide this vector by a number.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/equals:">– equals:</a></code>
<span class="tooltip"><p>Checks LeapVector equality.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/dot:">– dot:</a></code>
<span class="tooltip"><p>The dot product of this vector with another vector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/cross:">– cross:</a></code>
<span class="tooltip"><p>The cross product of this vector and the specified vector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/normalized">– normalized</a></code>
<span class="tooltip"><p>A normalized copy of this vector.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/toNSArray">– toNSArray</a></code>
<span class="tooltip"><p>Returns an NSArray object containing the vector components in the<br/>
order: x, y, z.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/toFloatPointer">– toFloatPointer</a></code>
<span class="tooltip"><p>Returns an NSMutableData object containing the vector components as<br/>
consecutive floating point values.</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/zero">+ zero</a></code>
<span class="tooltip"><p>The zero vector: (0, 0, 0)</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/xAxis">+ xAxis</a></code>
<span class="tooltip"><p>The x-axis unit vector: (1, 0, 0).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/yAxis">+ yAxis</a></code>
<span class="tooltip"><p>The y-axis unit vector: (0, 1, 0).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/zAxis">+ zAxis</a></code>
<span class="tooltip"><p>The z-axis unit vector: (0, 0, 1).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/left">+ left</a></code>
<span class="tooltip"><p>The unit vector pointing left along the negative x-axis: (-1, 0, 0).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/right">+ right</a></code>
<span class="tooltip"><p>The unit vector pointing right along the positive x-axis: (1, 0, 0).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/down">+ down</a></code>
<span class="tooltip"><p>The unit vector pointing down along the negative y-axis: (0, -1, 0).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/up">+ up</a></code>
<span class="tooltip"><p>The unit vector pointing up along the positive y-axis: (0, 1, 0).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/forward">+ forward</a></code>
<span class="tooltip"><p>The unit vector pointing forward along the negative z-axis: (0, 0, -1).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/backward">+ backward</a></code>
<span class="tooltip"><p>The unit vector pointing backward along the positive z-axis: (0, 0, 1).</p></span>
</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/x"> x</a></code>
<span class="tooltip"><p>The horizontal component.</p></span>
</span>
<span class="task-item-suffix">property</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/y"> y</a></code>
<span class="tooltip"><p>The vertical component.</p></span>
</span>
<span class="task-item-suffix">property</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/z"> z</a></code>
<span class="tooltip"><p>The depth component.</p></span>
</span>
<span class="task-item-suffix">property</span>
</li>
</ul>
</div>
<div class="section section-methods">
<a title="Properties" name="properties"></a>
<h2 class="subtitle subtitle-methods">Properties</h2>
<div class="section-method">
<a name="//api/name/x" title="x"></a>
<h3 class="subsubtitle method-title">x</h3>
<div class="method-subsection brief-description">
<p>The horizontal component.</p>
</div>
<div class="method-subsection method-declaration"><code>@property (nonatomic, assign, readonly) float x</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The horizontal component.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/y" title="y"></a>
<h3 class="subsubtitle method-title">y</h3>
<div class="method-subsection brief-description">
<p>The vertical component.</p>
</div>
<div class="method-subsection method-declaration"><code>@property (nonatomic, assign, readonly) float y</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The vertical component.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/z" title="z"></a>
<h3 class="subsubtitle method-title">z</h3>
<div class="method-subsection brief-description">
<p>The depth component.</p>
</div>
<div class="method-subsection method-declaration"><code>@property (nonatomic, assign, readonly) float z</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The depth component.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
</div>
<div class="section section-methods">
<a title="Class Methods" name="class_methods"></a>
<h2 class="subtitle subtitle-methods">Class Methods</h2>
<div class="section-method">
<a name="//api/name/backward" title="backward"></a>
<h3 class="subsubtitle method-title">backward</h3>
<div class="method-subsection brief-description">
<p>The unit vector pointing backward along the positive z-axis: (0, 0, 1).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)backward</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The unit vector pointing backward along the positive z-axis: (0, 0, 1).</p>
<pre><code> LeapVector *backwardVector = [LeapVector backward];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/down" title="down"></a>
<h3 class="subsubtitle method-title">down</h3>
<div class="method-subsection brief-description">
<p>The unit vector pointing down along the negative y-axis: (0, -1, 0).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)down</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The unit vector pointing down along the negative y-axis: (0, -1, 0).</p>
<pre><code> LeapVector *downVector = [LeapVector down];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/forward" title="forward"></a>
<h3 class="subsubtitle method-title">forward</h3>
<div class="method-subsection brief-description">
<p>The unit vector pointing forward along the negative z-axis: (0, 0, -1).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)forward</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The unit vector pointing forward along the negative z-axis: (0, 0, -1).</p>
<pre><code> LeapVector *forwardVector = [LeapVector forward];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/left" title="left"></a>
<h3 class="subsubtitle method-title">left</h3>
<div class="method-subsection brief-description">
<p>The unit vector pointing left along the negative x-axis: (-1, 0, 0).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)left</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The unit vector pointing left along the negative x-axis: (-1, 0, 0).</p>
<pre><code> LeapVector *leftVector = [LeapVector left];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/right" title="right"></a>
<h3 class="subsubtitle method-title">right</h3>
<div class="method-subsection brief-description">
<p>The unit vector pointing right along the positive x-axis: (1, 0, 0).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)right</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The unit vector pointing right along the positive x-axis: (1, 0, 0).</p>
<pre><code> LeapVector *rightVector = [LeapVector right];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/up" title="up"></a>
<h3 class="subsubtitle method-title">up</h3>
<div class="method-subsection brief-description">
<p>The unit vector pointing up along the positive y-axis: (0, 1, 0).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)up</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The unit vector pointing up along the positive y-axis: (0, 1, 0).</p>
<pre><code> LeapVector *upVector = [LeapVector up];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/xAxis" title="xAxis"></a>
<h3 class="subsubtitle method-title">xAxis</h3>
<div class="method-subsection brief-description">
<p>The x-axis unit vector: (1, 0, 0).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)xAxis</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The x-axis unit vector: (1, 0, 0).</p>
<pre><code> LeapVector *xAxisVector = [LeapVector xAxis];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/yAxis" title="yAxis"></a>
<h3 class="subsubtitle method-title">yAxis</h3>
<div class="method-subsection brief-description">
<p>The y-axis unit vector: (0, 1, 0).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)yAxis</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The y-axis unit vector: (0, 1, 0).</p>
<pre><code> LeapVector *yAxisVector = [LeapVector yAxis];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/zAxis" title="zAxis"></a>
<h3 class="subsubtitle method-title">zAxis</h3>
<div class="method-subsection brief-description">
<p>The z-axis unit vector: (0, 0, 1).</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)zAxis</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The z-axis unit vector: (0, 0, 1).</p>
<pre><code> LeapVector *zAxisVector = [LeapVector zAxis];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/zero" title="zero"></a>
<h3 class="subsubtitle method-title">zero</h3>
<div class="method-subsection brief-description">
<p>The zero vector: (0, 0, 0)</p>
</div>
<div class="method-subsection method-declaration"><code>+ (LeapVector *)zero</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The zero vector: (0, 0, 0)</p>
<pre><code> LeapVector *zeroVector = [LeapVector zero];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
</div>
<div class="section section-methods">
<a title="Instance Methods" name="instance_methods"></a>
<h2 class="subtitle subtitle-methods">Instance Methods</h2>
<div class="section-method">
<a name="//api/name/angleTo:" title="angleTo:"></a>
<h3 class="subsubtitle method-title">angleTo:</h3>
<div class="method-subsection brief-description">
<p>The angle between this vector and the specified vector in radians.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)angleTo:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>A LeapVector object.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The angle between this vector and the specified vector in radians.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The angle between this vector and the specified vector in radians.</p>
<pre><code> float angleInRadians = [[LeapVector xAxis] angleTo:[LeapVector yAxis]];
// angleInRadians = PI/2 (90 degrees)
</code></pre>
<p>The angle is measured in the plane formed by the two vectors. The<br/>
angle returned is always the smaller of the two conjugate angles.<br/>
Thus <code>[A angleTo:B] == [B angleTo:A]</code> and is always a positive<br/>
value less than or equal to pi radians (180 degrees).</p>
<p>If either vector has zero length, then this function returns zero.</p>
<p><img src="../docs/images/Math_AngleTo.png"/></p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/cross:" title="cross:"></a>
<h3 class="subsubtitle method-title">cross:</h3>
<div class="method-subsection brief-description">
<p>The cross product of this vector and the specified vector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (LeapVector *)cross:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>A LeapVector object.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The cross product of this vector and the specified vector.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The cross product of this vector and the specified vector.</p>
<pre><code> LeapVector *crossProduct = [thisVector cross:thatVector];
</code></pre>
<p>The cross product is a vector orthogonal to both original vectors.<br/>
It has a magnitude equal to the area of a parallelogram having the<br/>
two vectors as sides. The direction of the returned vector is<br/>
determined by the right-hand rule. Thus <code>[A cross:B] ==
[[B negate] cross:A]</code>.</p>
<p><img src="../docs/images/Math_Cross.png"/></p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/distanceTo:" title="distanceTo:"></a>
<h3 class="subsubtitle method-title">distanceTo:</h3>
<div class="method-subsection brief-description">
<p>The distance between the point represented by this LeapVector<br/>
object and a point represented by the specified LeapVector object.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)distanceTo:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>A LeapVector object.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The distance from this point to the specified point.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The distance between the point represented by this LeapVector<br/>
object and a point represented by the specified LeapVector object.</p>
<pre><code> LeapVector *aPoint = [[LeapVector alloc] initWithX:10 y:0 z:0];
LeapVector *origin = [LeapVector zero];
float distance = [origin distanceTo:aPoint]; // distance = 10
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/divide:" title="divide:"></a>
<h3 class="subsubtitle method-title">divide:</h3>
<div class="method-subsection brief-description">
<p>Divide this vector by a number.</p>
</div>
<div class="method-subsection method-declaration"><code>- (LeapVector *)divide:(float)<em>scalar</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>scalar</em></dt>
<dd><p>The scalar divisor;</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The dividend of this LeapVector divided by a scalar.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Divide this vector by a number.</p>
<pre><code> LeapVector *quotient = [thisVector divide:2.5];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/dot:" title="dot:"></a>
<h3 class="subsubtitle method-title">dot:</h3>
<div class="method-subsection brief-description">
<p>The dot product of this vector with another vector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)dot:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>A LeapVector object.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The dot product of this vector and the specified vector.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The dot product of this vector with another vector.</p>
<pre><code> float dotProduct = [thisVector dot:thatVector];
</code></pre>
<p>The dot product is the magnitude of the projection of this vector<br/>
onto the specified vector.</p>
<p><img src="../docs/images/Math_Dot.png"/></p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/equals:" title="equals:"></a>
<h3 class="subsubtitle method-title">equals:</h3>
<div class="method-subsection brief-description">
<p>Checks LeapVector equality.</p>
</div>
<div class="method-subsection method-declaration"><code>- (BOOL)equals:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>The LeapVector to compare.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>YES, if the LeapVectors are equal.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Checks LeapVector equality.</p>
<pre><code> bool vectorsAreEqual = [thisVector equals:thatVector];
</code></pre>
<p>Vectors are equal if each corresponding component is equal.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/initWithVector:" title="initWithVector:"></a>
<h3 class="subsubtitle method-title">initWithVector:</h3>
<div class="method-subsection brief-description">
<p>Copies the specified LeapVector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (id)initWithVector:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>The LeapVector to copy.</p></dd>
</dl>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Copies the specified LeapVector.</p>
<pre><code> LeapVector *copiedVector = [[LeapVector alloc] initWithVector:otherVector];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/initWithX:y:z:" title="initWithX:y:z:"></a>
<h3 class="subsubtitle method-title">initWithX:y:z:</h3>
<div class="method-subsection brief-description">
<p>Creates a new LeapVector with the specified component values.</p>
</div>
<div class="method-subsection method-declaration"><code>- (id)initWithX:(float)<em>x</em> y:(float)<em>y</em> z:(float)<em>z</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>x</em></dt>
<dd><p>The horizontal component.</p></dd>
</dl>
<dl class="argument-def parameter-def">
<dt><em>y</em></dt>
<dd><p>The vertical component.</p></dd>
</dl>
<dl class="argument-def parameter-def">
<dt><em>z</em></dt>
<dd><p>The depth component.</p></dd>
</dl>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Creates a new LeapVector with the specified component values.</p>
<pre><code> LeapVector *newVector = [[LeapVector alloc] initWithX:0.5 y:200.3 z:67];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/magnitude" title="magnitude"></a>
<h3 class="subsubtitle method-title">magnitude</h3>
<div class="method-subsection brief-description">
<p>The magnitude, or length, of this vector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)magnitude</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The length of this vector.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The magnitude, or length, of this vector.</p>
<pre><code> float length = thisVector.magnitude;
</code></pre>
<p>The magnitude is the L2 norm, or Euclidean distance between the origin and<br/>
the point represented by the (x, y, z) components of this LeapVector object.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/magnitudeSquared" title="magnitudeSquared"></a>
<h3 class="subsubtitle method-title">magnitudeSquared</h3>
<div class="method-subsection brief-description">
<p>The square of the magnitude, or length, of this vector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)magnitudeSquared</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The square of the length of this vector.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The square of the magnitude, or length, of this vector.</p>
<pre><code> float lengthSquared = thisVector.magnitudeSquared;
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/minus:" title="minus:"></a>
<h3 class="subsubtitle method-title">minus:</h3>
<div class="method-subsection brief-description">
<p>Subtract a vector from this vector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (LeapVector *)minus:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>the LeapVector subtrahend.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>the difference between the two LeapVectors.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Subtract a vector from this vector.</p>
<pre><code> LeapVector *difference = [thisVector minus:thatVector];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/negate" title="negate"></a>
<h3 class="subsubtitle method-title">negate</h3>
<div class="method-subsection brief-description">
<p>Negate this vector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (LeapVector *)negate</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The negation of this LeapVector.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Negate this vector.</p>
<pre><code> LeapVector *negation = thisVector.negate;
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/normalized" title="normalized"></a>
<h3 class="subsubtitle method-title">normalized</h3>
<div class="method-subsection brief-description">
<p>A normalized copy of this vector.</p>
</div>
<div class="method-subsection method-declaration"><code>- (LeapVector *)normalized</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>A LeapVector object with a length of one, pointing in the same<br/>
direction as this Vector object.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>A normalized copy of this vector.</p>
<pre><code> LeapVector *normalizedVector = otherVector.normalized;
</code></pre>
<p>A normalized vector has the same direction as the original vector,<br/>
but with a length of one.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/pitch" title="pitch"></a>
<h3 class="subsubtitle method-title">pitch</h3>
<div class="method-subsection brief-description">
<p>The pitch angle in radians.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)pitch</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The angle of this vector above or below the horizon (x-z plane).</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The pitch angle in radians.</p>
<pre><code> float pitchInRadians = thisVector.pitch;
</code></pre>
<p>Pitch is the angle between the negative z-axis and the projection of<br/>
the vector onto the y-z plane. In other words, pitch represents rotation<br/>
around the x-axis.<br/>
If the vector points upward, the returned angle is between 0 and pi radians<br/>
(180 degrees); if it points downward, the angle is between 0 and -pi radians.</p>
<p><img src="../docs/images/Math_Pitch_Angle.png"/></p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/plus:" title="plus:"></a>
<h3 class="subsubtitle method-title">plus:</h3>
<div class="method-subsection brief-description">
<p>Adds two vectors.</p>
</div>
<div class="method-subsection method-declaration"><code>- (LeapVector *)plus:(const LeapVector *)<em>vector</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>vector</em></dt>
<dd><p>The LeapVector addend.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The sum of the two LeapVectors.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Adds two vectors.</p>
<pre><code> LeapVector *sum = [thisVector plus:thatVector];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/roll" title="roll"></a>
<h3 class="subsubtitle method-title">roll</h3>
<div class="method-subsection brief-description">
<p>The roll angle in radians.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)roll</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The angle of this vector to the right or left of the y-axis.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The roll angle in radians.</p>
<pre><code> float rollInRadians = thatVector.roll;
</code></pre>
<p>Roll is the angle between the y-axis and the projection of<br/>
the vector onto the x-y plane. In other words, roll represents rotation<br/>
around the z-axis. If the vector points to the left of the y-axis,<br/>
then the returned angle is between 0 and pi radians (180 degrees);<br/>
if it points to the right, the angle is between 0 and -pi radians.</p>
<p><img src="../docs/images/Math_Roll_Angle.png"/></p>
<p>Use this function to get roll angle of the plane to which this vector is a<br/>
normal. For example, if this vector represents the normal to the palm,<br/>
then this function returns the tilt or roll of the palm plane compared<br/>
to the horizontal (x-z) plane.</p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/times:" title="times:"></a>
<h3 class="subsubtitle method-title">times:</h3>
<div class="method-subsection brief-description">
<p>Multiply this vector by a number.</p>
</div>
<div class="method-subsection method-declaration"><code>- (LeapVector *)times:(float)<em>scalar</em></code></div>
<div class="method-subsection arguments-section parameters">
<h4 class="method-subtitle parameter-title">Parameters</h4>
<dl class="argument-def parameter-def">
<dt><em>scalar</em></dt>
<dd><p>The scalar factor.</p></dd>
</dl>
</div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The product of this LeapVector and a scalar.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Multiply this vector by a number.</p>
<pre><code> LeapVector *product = [thisVector times:5.0];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/toFloatPointer" title="toFloatPointer"></a>
<h3 class="subsubtitle method-title">toFloatPointer</h3>
<div class="method-subsection brief-description">
<p>Returns an NSMutableData object containing the vector components as<br/>
consecutive floating point values.</p>
</div>
<div class="method-subsection method-declaration"><code>- (NSMutableData *)toFloatPointer</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Returns an NSMutableData object containing the vector components as<br/>
consecutive floating point values.</p>
<pre><code> NSData *vectorData = thisVector.toFloatPointer;
float x, y, z;
[vectorData getBytes:&x length:sizeof(float)];
[vectorData getBytes:&y length:sizeof(float)];
[vectorData getBytes:&z length:sizeof(float)];
//Or access as an array of float:
float array[3];
[vectorData getBytes:&array length:sizeof(float) * 3];
x = array[0];
y = array[1];
z = array[2];
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/toNSArray" title="toNSArray"></a>
<h3 class="subsubtitle method-title">toNSArray</h3>
<div class="method-subsection brief-description">
<p>Returns an NSArray object containing the vector components in the<br/>
order: x, y, z.</p>
</div>
<div class="method-subsection method-declaration"><code>- (NSArray *)toNSArray</code></div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>Returns an NSArray object containing the vector components in the<br/>
order: x, y, z.</p>
<pre><code> NSArray *vectorArray = thisVector.toNSArray;
</code></pre>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
<div class="section-method">
<a name="//api/name/yaw" title="yaw"></a>
<h3 class="subsubtitle method-title">yaw</h3>
<div class="method-subsection brief-description">
<p>The yaw angle in radians.</p>
</div>
<div class="method-subsection method-declaration"><code>- (float)yaw</code></div>
<div class="method-subsection return">
<h4 class="method-subtitle parameter-title">Return Value</h4>
<p>The angle of this vector to the right or left of the negative z-axis.</p>
</div>
<div class="method-subsection availability">
<h4 class="method-subtitle parameter-title">Availability</h4>
<p>Since 1.0</p>
</div>
<div class="method-subsection discussion-section">
<h4 class="method-subtitle">Discussion</h4>
<p>The yaw angle in radians.</p>
<pre><code> float yawInRadians = thisVector.yaw;
</code></pre>
<p>Yaw is the angle between the negative z-axis and the projection of<br/>
the vector onto the x-z plane. In other words, yaw represents rotation<br/>
around the y-axis. If the vector points to the right of the negative z-axis,<br/>
then the returned angle is between 0 and pi radians (180 degrees);<br/>
if it points to the left, the angle is between 0 and -pi radians.</p>
<p><img src="../docs/images/Math_Yaw_Angle.png"/></p>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<code class="declared-in-ref">LeapObjectiveC.h</code><br />
</div>
</div>
</div>
</div>
<div class="main-navigation navigation-bottom">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="footer">
<hr />
<div class="footer-copyright">
<p><span class="copyright">© 2013 Leap Motion. All rights reserved. (Last updated: 2013-07-19)</span><br />
<span class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.1 (build 858)</a>.</span></p>
</div>
</div>
</div>
</article>
<script type="text/javascript">
function jumpToChange()
{
window.location.hash = this.options[this.selectedIndex].value;
}
function toggleTOC()
{
var contents = document.getElementById('contents');
var tocContainer = document.getElementById('tocContainer');
if (this.getAttribute('class') == 'open')
{
this.setAttribute('class', '');
contents.setAttribute('class', '');
tocContainer.setAttribute('class', '');
window.name = "hideTOC";
}
else
{
this.setAttribute('class', 'open');
contents.setAttribute('class', 'isShowingTOC');
tocContainer.setAttribute('class', 'isShowingTOC');
window.name = "";
}
return false;
}
function toggleTOCEntryChildren(e)
{
e.stopPropagation();
var currentClass = this.getAttribute('class');
if (currentClass == 'children') {
this.setAttribute('class', 'children open');
}
else if (currentClass == 'children open') {
this.setAttribute('class', 'children');
}
return false;
}
function tocEntryClick(e)
{
e.stopPropagation();
return true;
}
function init()
{
var selectElement = document.getElementById('jumpTo');
selectElement.addEventListener('change', jumpToChange, false);
var tocButton = document.getElementById('table_of_contents');
tocButton.addEventListener('click', toggleTOC, false);
var taskTreeItem = document.getElementById('task_treeitem');
if (taskTreeItem.getElementsByTagName('li').length > 0)
{
taskTreeItem.setAttribute('class', 'children');
taskTreeItem.firstChild.setAttribute('class', 'disclosure');
}
var tocList = document.getElementById('toc');
var tocEntries = tocList.getElementsByTagName('li');
for (var i = 0; i < tocEntries.length; i++) {
tocEntries[i].addEventListener('click', toggleTOCEntryChildren, false);
}
var tocLinks = tocList.getElementsByTagName('a');
for (var i = 0; i < tocLinks.length; i++) {
tocLinks[i].addEventListener('click', tocEntryClick, false);
}
if (window.name == "hideTOC") {
toggleTOC.call(tocButton);
}
}
window.onload = init;
// If showing in Xcode, hide the TOC and Header
if (navigator.userAgent.match(/xcode/i)) {
document.getElementById("contents").className = "hideInXcode"
document.getElementById("tocContainer").className = "hideInXcode"
document.getElementById("top_header").className = "hideInXcode"
}
</script>
</body>
</html> | nakajimakou1/cvdrone-master_leap_FaceDetect | src/3rdparty/LeapSDK/docs/Languages/ObjectiveC/html/Classes/LeapVector.html | HTML | bsd-3-clause | 62,836 |
package org.lemurproject.galago.core.util;
import org.lemurproject.galago.core.retrieval.iterator.BaseIterator;
import org.lemurproject.galago.core.retrieval.traversal.Traversal;
import org.lemurproject.galago.utility.Parameters;
import java.util.ArrayList;
import java.util.List;
/**
* @author jfoley.
*/
public class IterUtils {
/**
* Adds an operator into a Retrieval's parameters for usage.
* @param p the parameters object
* @param name the name of the operator, e.g. "combine" for #combine
* @param iterClass the operator to register
*/
public static void addToParameters(Parameters p, String name, Class<? extends BaseIterator> iterClass) {
if(!p.containsKey("operators")) {
p.put("operators", Parameters.create());
}
p.getMap("operators").put(name, iterClass.getName());
}
/**
* Adds a traversal into a Retrieval's parameters for usage.
* @param argp the parameters object
* @param traversalClass the traversal to register
*/
public static void addToParameters(Parameters argp, Class<? extends Traversal> traversalClass) {
if(!argp.isList("traversals")) {
argp.put("traversals", new ArrayList<>());
}
List<Parameters> traversals = argp.getList("traversals", Parameters.class);
traversals.add(Parameters.parseArray(
"name", traversalClass.getName(),
"order", "before"
));
argp.put("traversals", traversals);
}
}
| hzhao/galago-git | core/src/main/java/org/lemurproject/galago/core/util/IterUtils.java | Java | bsd-3-clause | 1,424 |
from pybrain.rl.environments.timeseries.maximizereturntask import DifferentialSharpeRatioTask
from pybrain.rl.environments.timeseries.timeseries import AR1Environment, SnPEnvironment
from pybrain.rl.learners.valuebased.linearfa import Q_LinFA
from pybrain.rl.agents.linearfa import LinearFA_Agent
from pybrain.rl.experiments import ContinuousExperiment
from matplotlib import pyplot
"""
This script aims to create a trading model that trades on a simple AR(1) process
"""
env=AR1Environment(2000)
task=DifferentialSharpeRatioTask(env)
learner = Q_LinFA(2,1)
agent = LinearFA_Agent(learner)
exp = ContinuousExperiment(task,agent)
from decimal import Decimal
ts=env.ts.tolist()
exp.doInteractionsAndLearn(1999)
actionHist=env.actionHistory
pyplot.plot(ts[0])
pyplot.plot(actionHist)
pyplot.show()
#snp_rets=env.importSnP().tolist()[0]
#print(snp_rets.tolist()[0])
#pyplot.plot(snp_rets)
#pyplot.show()
#cumret= cumsum(multiply(ts,actionHist))
#exp.doInteractions(200)
| samstern/MSc-Project | pybrain/rl/environments/timeseries/test programs/ar1TestScript.py | Python | bsd-3-clause | 976 |
using Basic.Azure.Storage.Communications.Core;
using Basic.Azure.Storage.Communications.Core.Interfaces;
using Basic.Azure.Storage.Communications.TableService.Interfaces;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Basic.Azure.Storage.Communications.TableService.EntityOperations
{
public class DeleteEntityRequest : RequestBase<EmptyResponsePayload>,
ISendAdditionalRequiredHeaders
{
private string _tableName;
private string _partitionKey;
private string _rowKey;
private string _etag;
public DeleteEntityRequest(StorageAccountSettings settings, string tableName, string partitionKey, string rowKey, string etag)
: base(settings)
{
_tableName = tableName;
_partitionKey = partitionKey;
_rowKey = rowKey;
if (string.IsNullOrEmpty(etag))
_etag = "*";
else
_etag = etag;
}
protected override string HttpMethod { get { return "DELETE"; } }
protected override StorageServiceType ServiceType { get { return StorageServiceType.TableService; } }
protected override RequestUriBuilder GetUriBase()
{
var builder = new RequestUriBuilder(Settings.TableEndpoint);
builder.AddSegment(String.Format("{0}(PartitionKey='{1}',RowKey='{2}')", _tableName, _partitionKey, _rowKey));
return builder;
}
public void ApplyAdditionalRequiredHeaders(System.Net.WebRequest request)
{
request.ContentType = "application/json;charset=utf-8";
if (request is HttpWebRequest)
{
((HttpWebRequest)request).Accept = "application/json";
}
else
{
request.Headers.Add(ProtocolConstants.Headers.Accept, "application/json");
}
request.Headers.Add(ProtocolConstants.Headers.IfMatch, _etag);
}
}
}
| tarwn/BasicAzureStorageSDK | Basic.Azure.Storage/Communications/TableService/EntityOperations/DeleteEntityRequest.cs | C# | bsd-3-clause | 2,132 |
/****************************************************************/
/* 1. BACKGROUND AND TEXT COLOURS */
/****************************************************************/
/* 1.1 Default background colour and text colour */
body{text-align:center;background : url(../img/back.gif);}
/* �������� ����� */
.djangobb {COLOR: #333}
DIV.box, #adminconsole FIELDSET TH, .rowodd, .roweven {BACKGROUND-COLOR: #f8f8f8}
.djangobb BLOCKQUOTE, DIV.code {BACKGROUND-COLOR: #f1f1f1}
#adminconsole TD, #adminconsole TH {BORDER-COLOR: #eeeeee} /*<<<<<<<<<<<neizvestno*/
/* 1. 2 Darker background colours */
TD.tc2, TD.tc3, TD.tcmod, #postpreview, #viewprofile DD, DIV.forminfo,
#adminconsole FIELDSET TD, DIV.blockmenu DIV.box, #adstats DD {BACKGROUND-COLOR: #f5f5f5}
TH.tc3 {width: 70px}
/* 1.3 Main headers and navigation bar background and text colour */
.djangobb H2, #brdmenu {BACKGROUND: url(../img/fon111.gif); COLOR: #FFF; font-weight: bold; height: 16px;}
.djangobb H2 {font-weight: bold;BACKGROUND: #46586a url(../img/fon111.gif);border-top: 1px solid #46586a;border-left: 1px solid #46586a;border-right: 1px solid #46586a; height: 16px;}
.djangobb H2 a.toggle {
float: right;
BACKGROUND: url(../img/cat_minimize.png);
display:block;
height:17px;
line-height:1px;
outline-color:-moz-use-text-color;
outline-style:none;
outline-width:0;
text-indent:-3000em;
width:28px;
}
.djangobb H2.collapsed a.toggle {
background-image:url(../img/cat_maximize.png);
}
/* 1.4 Table header rows */
.djangobb TH {BACKGROUND-COLOR: #eeeeee;}
/* 1.5 Fieldset legend text colour */
.djangobb LEGEND {COLOR: #5A799D}
/* 1.6 Highlighted text for various items */
.djangobb DIV.blockmenu LI.isactive A, #posterror LI STRONG {COLOR: #46586a}
/****************************************************************/
/* 2. POST BACKGROUNDS AND TEXT */
/****************************************************************/
/* 2.1 This is the setup for posts. */
DIV.blockpost DIV.box, DIV.postright, DIV.postfootright {BACKGROUND-COLOR: #f8f8f8}
DIV.postright, DIV.postfootright {BORDER-LEFT-COLOR: #f1f1f1}
DIV.postleft, DIV.postfootleft, DIV.blockpost LABEL {BACKGROUND-COLOR: #f1f1f1}
/* 2.2 Background for post headers and text colour for post numbers in viewtopic */
DIV.blockpost H2 {BACKGROUND-COLOR: #46586a}
DIV.blockpost H2 SPAN.conr {COLOR: #CCC}
/* 2.3 This is the line above the signature in posts. Colour and background should be the same */
.djangobb HR {BACKGROUND-COLOR: #35567C; COLOR: #35567C}
/****************************************************************/
/* 3. BORDER COLOURS */
/****************************************************************/
/* 3.1 All external borders */
DIV.box {BORDER-COLOR: #46586a}
/* 3.2 Makes the top border of posts match the colour used for post headers */
/*DIV.blockpost DIV.box {BORDER-COLOR: #686E80 #686E80 #686E80}*/
DIV.blockpost DIV.box {BORDER: 1px solid #46586a;BORDER-TOP: 1px solid #46586a;}
/* 3.3 Table internal borders. By default TH is same as background so border is invisible */
.djangobb TD {BORDER-COLOR: #d6e1f1}
.djangobb TH {BORDER-COLOR: #d6e1f1}
/* 3.4 Creates the inset border for quote boxes, code boxes and form info boxes */
.djangobb BLOCKQUOTE, DIV.code, DIV.forminfo, DIV.blockpost LABEL {BORDER-COLOR: #46586a #46586a #46586a #46586a}
/* 3.5 Gecko's default fieldset borders are really nasty so this gives them a colour
without interferring with IE's rather nice default */
/****************************************************************/
/* 4. LINK COLOURS */
/****************************************************************/
/* 4.1 This is the default for all links */
.djangobb A:link, .djangobb A:visited {COLOR: #46586a;}
.djangobb A:hover {COLOR: #B42000; }
/* 4.2 This is the colour for links in header rows and the navigation bar */
.djangobb H2 A:link, .djangobb H2 A:visited, #brdmenu A:link, #brdmenu A:visited {COLOR: #FFF;text-decoration : underline; }
.djangobb H2 A:hover, #brdmenu A:hover {COLOR: #35567C;}
/* 4.3 This is for closed topics and "hot" links */
LI.postreport A:link, LI.postreport A:visited, TR.iclosed TD.tcl A:link, TR.iclosed TD.tcl A:visited {COLOR: #888}
LI.postreport A:hover, TR.iclosed TD.tcl A:hover {COLOR: #AAA}
LI.maintenancelink A:link, LI.maintenancelink A:visited {COLOR: #B42000}
LI.maintenancelink A:hover {COLOR: #B42000}
/****************************************************************/
/* 5. POST STATUS INDICATORS */
/****************************************************************/
/* These are the post status indicators which appear at the left of some tables.
.inew = new posts, .iredirect = redirect forums, .iclosed = closed topics and
.isticky = sticky topics. The default is "icon". By default only .inew is different.*/
DIV.forum_icon {background:url(../img/active_forum.gif)}
DIV.icon {background:url(../img/inactive_topic.gif)}
DIV.inew {background:url(../img/active_topic.gif)}
DIV.sticky {background:url(../img/sticky_topic.gif)}
DIV.closed {background:url(../img/closed_topic.gif)}
TR.inew DIV.icon {background:url(../img/active_topic.gif)}
TR.isticky DIV.inew {background:url(../img/active_topic.gif)}
TR.iclosed DIV.icon {background:url(../img/closed.png)}
DIV.iredirect {background:url(../img/link.png)}
/****************************************************************/
/* 6. EXTRAS */
/****************************************************************/
#brdmenu {BACKGROUND: url(../img/fon111.gif); border-top: 1px solid #46586a;border-bottom: 1px solid #46586a; BACKGROUND-COLOR: #46586a;}
/* header logo */
.djangobb H1 span
{
color: #3A3B3C;
font-size: 16px; /*bylo 12*/
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
}
.djangobb h2 span {
background:transparent url(../img/category.gif) no-repeat scroll left center;
}
.djangobb h2 span.conr {
background-image:none;
}
/* board stats icon */
#djangobbindex #brdstats div.box div.inbox dl.conl,
#djangobbforum #brdstats div.box div.inbox dl.conl
{
background: transparent url(../img/stats.gif) no-repeat 0% 50%;
padding-left: 38px;
}
| aldenjenkins/foobargamingwebsite | djangobb_forum/static/djangobb_forum/themes/default/css/default_cs.css | CSS | bsd-3-clause | 6,110 |
#pragma once
#include <deque>
#include <functional>
#include <pthread.h>
#include "basetypes.h"
#include "misc.h"
#define Pthread_spin_init(l, pshared) verify(pthread_spin_init(l, (pshared)) == 0)
#define Pthread_spin_lock(l) verify(pthread_spin_lock(l) == 0)
#define Pthread_spin_unlock(l) verify(pthread_spin_unlock(l) == 0)
#define Pthread_spin_destroy(l) verify(pthread_spin_destroy(l) == 0)
#define Pthread_mutex_init(m, attr) verify(pthread_mutex_init(m, attr) == 0)
#define Pthread_mutex_lock(m) verify(pthread_mutex_lock(m) == 0)
#define Pthread_mutex_unlock(m) verify(pthread_mutex_unlock(m) == 0)
#define Pthread_mutex_destroy(m) verify(pthread_mutex_destroy(m) == 0)
#define Pthread_cond_init(c, attr) verify(pthread_cond_init(c, attr) == 0)
#define Pthread_cond_destroy(c) verify(pthread_cond_destroy(c) == 0)
#define Pthread_cond_signal(c) verify(pthread_cond_signal(c) == 0)
#define Pthread_cond_broadcast(c) verify(pthread_cond_broadcast(c) == 0)
#define Pthread_cond_wait(c, m) verify(pthread_cond_wait(c, m) == 0)
#define Pthread_create(th, attr, func, arg) verify(pthread_create(th, attr, func, arg) == 0)
#define Pthread_join(th, attr) verify(pthread_join(th, attr) == 0)
namespace base {
class Lockable: public NoCopy {
public:
virtual void lock() = 0;
virtual void unlock() = 0;
};
class SpinLock: public Lockable {
public:
SpinLock(): locked_(false) { }
void lock();
void unlock() {
__sync_lock_release(&locked_);
}
private:
volatile bool locked_ __attribute__((aligned (64)));
};
class Mutex: public Lockable {
public:
Mutex() {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
Pthread_mutex_init(&m_, &attr);
}
~Mutex() {
Pthread_mutex_destroy(&m_);
}
void lock() {
Pthread_mutex_lock(&m_);
}
void unlock() {
Pthread_mutex_unlock(&m_);
}
private:
friend class CondVar;
pthread_mutex_t m_;
};
// choice between spinlock & mutex:
// * when n_thread > n_core, use mutex
// * on virtual machines, use mutex
class ScopedLock: public NoCopy {
public:
explicit ScopedLock(Lockable* lock): m_(lock) { m_->lock(); }
explicit ScopedLock(Lockable& lock): m_(&lock) { m_->lock(); }
~ScopedLock() { m_->unlock(); }
private:
Lockable* m_;
};
class CondVar: public NoCopy {
public:
CondVar() {
Pthread_cond_init(&cv_, nullptr);
}
~CondVar() {
Pthread_cond_destroy(&cv_);
}
void wait(Mutex& m) {
Pthread_cond_wait(&cv_, &m.m_);
}
void signal() {
Pthread_cond_signal(&cv_);
}
void bcast() {
Pthread_cond_broadcast(&cv_);
}
int timed_wait(Mutex& m, double sec);
private:
pthread_cond_t cv_;
};
/**
* Thread safe queue.
*/
template<class T>
class Queue: public NoCopy {
std::deque<T> q_;
pthread_cond_t not_empty_;
pthread_mutex_t m_;
public:
Queue() {
Pthread_mutex_init(&m_, nullptr);
Pthread_cond_init(¬_empty_, nullptr);
}
~Queue() {
Pthread_cond_destroy(¬_empty_);
Pthread_mutex_destroy(&m_);
}
void push(const T& e) {
Pthread_mutex_lock(&m_);
q_.push_back(e);
Pthread_cond_signal(¬_empty_);
Pthread_mutex_unlock(&m_);
}
bool try_pop(T* t) {
bool ret = false;
Pthread_mutex_lock(&m_);
if (!q_.empty()) {
ret = true;
*t = q_.front();
q_.pop_front();
}
Pthread_mutex_unlock(&m_);
return ret;
}
bool try_pop_but_ignore(T* t, const T& ignore) {
bool ret = false;
Pthread_mutex_lock(&m_);
if (!q_.empty() && q_.front() != ignore) {
ret = true;
*t = q_.front();
q_.pop_front();
}
Pthread_mutex_unlock(&m_);
return ret;
}
T pop() {
Pthread_mutex_lock(&m_);
while (q_.empty()) {
Pthread_cond_wait(¬_empty_, &m_);
}
T e = q_.front();
q_.pop_front();
Pthread_mutex_unlock(&m_);
return e;
}
};
class ThreadPool: public RefCounted {
int n_;
Counter round_robin_;
pthread_t* th_;
Queue<std::function<void()>*>* q_;
bool should_stop_;
static void* start_thread_pool(void*);
void run_thread(int id_in_pool);
protected:
~ThreadPool();
public:
ThreadPool(int n = get_ncpu() * 2);
// return 0 when queuing ok, otherwise EPERM
int run_async(const std::function<void()>&, int queuing_channel = -1);
};
class RunLater: public RefCounted {
typedef std::pair<double, std::function<void()>*> job_t;
pthread_t th_;
pthread_mutex_t m_;
pthread_cond_t cv_;
bool should_stop_;
SpinLock latest_l_;
double latest_;
std::priority_queue<job_t, std::vector<job_t>, std::greater<job_t>> jobs_;
static void* start_run_later(void*);
void run_later_loop();
void try_one_job();
public:
RunLater();
// return 0 when queuing ok, otherwise EPERM
int run_later(double sec, const std::function<void()>&);
double max_wait() const;
protected:
~RunLater();
};
} // namespace base
| santazhang/simple-rpc | base/threading.h | C | bsd-3-clause | 5,266 |
<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<script>
(function() {
'use strict';
var wrap = Polymer.DomApi.wrap;
// detect native touch action support
var HAS_NATIVE_TA = typeof document.head.style.touchAction === 'string';
var GESTURE_KEY = '__polymerGestures';
var HANDLED_OBJ = '__polymerGesturesHandled';
var TOUCH_ACTION = '__polymerGesturesTouchAction';
// radius for tap and track
var TAP_DISTANCE = 25;
var TRACK_DISTANCE = 5;
// number of last N track positions to keep
var TRACK_LENGTH = 2;
// Disabling "mouse" handlers for 2500ms is enough
var MOUSE_TIMEOUT = 2500;
var MOUSE_EVENTS = ['mousedown', 'mousemove', 'mouseup', 'click'];
// an array of bitmask values for mapping MouseEvent.which to MouseEvent.buttons
var MOUSE_WHICH_TO_BUTTONS = [0, 1, 4, 2];
var MOUSE_HAS_BUTTONS = (function() {
try {
return new MouseEvent('test', {buttons: 1}).buttons === 1;
} catch (e) {
return false;
}
})();
// Check for touch-only devices
var IS_TOUCH_ONLY = navigator.userAgent.match(/iP(?:[oa]d|hone)|Android/);
// touch will make synthetic mouse events
// `preventDefault` on touchend will cancel them,
// but this breaks `<input>` focus and link clicks
// disable mouse handlers for MOUSE_TIMEOUT ms after
// a touchend to ignore synthetic mouse events
var mouseCanceller = function(mouseEvent) {
// Check for sourceCapabilities, used to distinguish synthetic events
// if mouseEvent did not come from a device that fires touch events,
// it was made by a real mouse and should be counted
// http://wicg.github.io/InputDeviceCapabilities/#dom-inputdevicecapabilities-firestouchevents
var sc = mouseEvent.sourceCapabilities;
if (sc && !sc.firesTouchEvents) {
return;
}
// skip synthetic mouse events
mouseEvent[HANDLED_OBJ] = {skip: true};
// disable "ghost clicks"
if (mouseEvent.type === 'click') {
var path = Polymer.dom(mouseEvent).path;
for (var i = 0; i < path.length; i++) {
if (path[i] === POINTERSTATE.mouse.target) {
return;
}
}
mouseEvent.preventDefault();
mouseEvent.stopPropagation();
}
};
function setupTeardownMouseCanceller(setup) {
for (var i = 0, en; i < MOUSE_EVENTS.length; i++) {
en = MOUSE_EVENTS[i];
if (setup) {
document.addEventListener(en, mouseCanceller, true);
} else {
document.removeEventListener(en, mouseCanceller, true);
}
}
}
function ignoreMouse() {
if (IS_TOUCH_ONLY) {
return;
}
if (!POINTERSTATE.mouse.mouseIgnoreJob) {
setupTeardownMouseCanceller(true);
}
var unset = function() {
setupTeardownMouseCanceller();
POINTERSTATE.mouse.target = null;
POINTERSTATE.mouse.mouseIgnoreJob = null;
};
POINTERSTATE.mouse.mouseIgnoreJob =
Polymer.Debounce(POINTERSTATE.mouse.mouseIgnoreJob, unset, MOUSE_TIMEOUT);
}
function hasLeftMouseButton(ev) {
var type = ev.type;
// exit early if the event is not a mouse event
if (MOUSE_EVENTS.indexOf(type) === -1) {
return false;
}
// ev.button is not reliable for mousemove (0 is overloaded as both left button and no buttons)
// instead we use ev.buttons (bitmask of buttons) or fall back to ev.which (deprecated, 0 for no buttons, 1 for left button)
if (type === 'mousemove') {
// allow undefined for testing events
var buttons = ev.buttons === undefined ? 1 : ev.buttons;
if ((ev instanceof window.MouseEvent) && !MOUSE_HAS_BUTTONS) {
buttons = MOUSE_WHICH_TO_BUTTONS[ev.which] || 0;
}
// buttons is a bitmask, check that the left button bit is set (1)
return Boolean(buttons & 1);
} else {
// allow undefined for testing events
var button = ev.button === undefined ? 0 : ev.button;
// ev.button is 0 in mousedown/mouseup/click for left button activation
return button === 0;
}
}
function isSyntheticClick(ev) {
if (ev.type === 'click') {
// ev.detail is 0 for HTMLElement.click in most browsers
if (ev.detail === 0) {
return true;
}
// in the worst case, check that the x/y position of the click is within
// the bounding box of the target of the event
// Thanks IE 10 >:(
var t = Gestures.findOriginalTarget(ev);
var bcr = t.getBoundingClientRect();
// use page x/y to account for scrolling
var x = ev.pageX, y = ev.pageY;
// ev is a synthetic click if the position is outside the bounding box of the target
return !((x >= bcr.left && x <= bcr.right) && (y >= bcr.top && y <= bcr.bottom));
}
return false;
}
var POINTERSTATE = {
mouse: {
target: null,
mouseIgnoreJob: null
},
touch: {
x: 0,
y: 0,
id: -1,
scrollDecided: false
}
};
function firstTouchAction(ev) {
var path = Polymer.dom(ev).path;
var ta = 'auto';
for (var i = 0, n; i < path.length; i++) {
n = path[i];
if (n[TOUCH_ACTION]) {
ta = n[TOUCH_ACTION];
break;
}
}
return ta;
}
function trackDocument(stateObj, movefn, upfn) {
stateObj.movefn = movefn;
stateObj.upfn = upfn;
document.addEventListener('mousemove', movefn);
document.addEventListener('mouseup', upfn);
}
function untrackDocument(stateObj) {
document.removeEventListener('mousemove', stateObj.movefn);
document.removeEventListener('mouseup', stateObj.upfn);
stateObj.movefn = null;
stateObj.upfn = null;
}
var Gestures = {
gestures: {},
recognizers: [],
deepTargetFind: function(x, y) {
var node = document.elementFromPoint(x, y);
var next = node;
// this code path is only taken when native ShadowDOM is used
// if there is a shadowroot, it may have a node at x/y
// if there is not a shadowroot, exit the loop
while (next && next.shadowRoot) {
// if there is a node at x/y in the shadowroot, look deeper
next = next.shadowRoot.elementFromPoint(x, y);
if (next) {
node = next;
}
}
return node;
},
// a cheaper check than Polymer.dom(ev).path[0];
findOriginalTarget: function(ev) {
// shadowdom
if (ev.path) {
return ev.path[0];
}
// shadydom
return ev.target;
},
handleNative: function(ev) {
var handled;
var type = ev.type;
var node = wrap(ev.currentTarget);
var gobj = node[GESTURE_KEY];
if (!gobj) {
return;
}
var gs = gobj[type];
if (!gs) {
return;
}
if (!ev[HANDLED_OBJ]) {
ev[HANDLED_OBJ] = {};
if (type.slice(0, 5) === 'touch') {
var t = ev.changedTouches[0];
if (type === 'touchstart') {
// only handle the first finger
if (ev.touches.length === 1) {
POINTERSTATE.touch.id = t.identifier;
}
}
if (POINTERSTATE.touch.id !== t.identifier) {
return;
}
if (!HAS_NATIVE_TA) {
if (type === 'touchstart' || type === 'touchmove') {
Gestures.handleTouchAction(ev);
}
}
// disable synth mouse events, unless this event is itself simulated
if (type === 'touchend') {
POINTERSTATE.mouse.target = Polymer.dom(ev).rootTarget;
// ignore syntethic mouse events after a touch
ignoreMouse();
}
}
}
handled = ev[HANDLED_OBJ];
// used to ignore synthetic mouse events
if (handled.skip) {
return;
}
var recognizers = Gestures.recognizers;
// reset recognizer state
for (var i = 0, r; i < recognizers.length; i++) {
r = recognizers[i];
if (gs[r.name] && !handled[r.name]) {
if (r.flow && r.flow.start.indexOf(ev.type) > -1 && r.reset) {
r.reset();
}
}
}
// enforce gesture recognizer order
for (i = 0, r; i < recognizers.length; i++) {
r = recognizers[i];
if (gs[r.name] && !handled[r.name]) {
handled[r.name] = true;
r[type](ev);
}
}
},
handleTouchAction: function(ev) {
var t = ev.changedTouches[0];
var type = ev.type;
if (type === 'touchstart') {
POINTERSTATE.touch.x = t.clientX;
POINTERSTATE.touch.y = t.clientY;
POINTERSTATE.touch.scrollDecided = false;
} else if (type === 'touchmove') {
if (POINTERSTATE.touch.scrollDecided) {
return;
}
POINTERSTATE.touch.scrollDecided = true;
var ta = firstTouchAction(ev);
var prevent = false;
var dx = Math.abs(POINTERSTATE.touch.x - t.clientX);
var dy = Math.abs(POINTERSTATE.touch.y - t.clientY);
if (!ev.cancelable) {
// scrolling is happening
} else if (ta === 'none') {
prevent = true;
} else if (ta === 'pan-x') {
prevent = dy > dx;
} else if (ta === 'pan-y') {
prevent = dx > dy;
}
if (prevent) {
ev.preventDefault();
} else {
Gestures.prevent('track');
}
}
},
// automate the event listeners for the native events
add: function(node, evType, handler) {
// SD polyfill: handle case where `node` is unwrapped, like `document`
node = wrap(node);
var recognizer = this.gestures[evType];
var deps = recognizer.deps;
var name = recognizer.name;
var gobj = node[GESTURE_KEY];
if (!gobj) {
node[GESTURE_KEY] = gobj = {};
}
for (var i = 0, dep, gd; i < deps.length; i++) {
dep = deps[i];
// don't add mouse handlers on iOS because they cause gray selection overlays
if (IS_TOUCH_ONLY && MOUSE_EVENTS.indexOf(dep) > -1) {
continue;
}
gd = gobj[dep];
if (!gd) {
gobj[dep] = gd = {_count: 0};
}
if (gd._count === 0) {
node.addEventListener(dep, this.handleNative);
}
gd[name] = (gd[name] || 0) + 1;
gd._count = (gd._count || 0) + 1;
}
node.addEventListener(evType, handler);
if (recognizer.touchAction) {
this.setTouchAction(node, recognizer.touchAction);
}
},
// automate event listener removal for native events
remove: function(node, evType, handler) {
// SD polyfill: handle case where `node` is unwrapped, like `document`
node = wrap(node);
var recognizer = this.gestures[evType];
var deps = recognizer.deps;
var name = recognizer.name;
var gobj = node[GESTURE_KEY];
if (gobj) {
for (var i = 0, dep, gd; i < deps.length; i++) {
dep = deps[i];
gd = gobj[dep];
if (gd && gd[name]) {
gd[name] = (gd[name] || 1) - 1;
gd._count = (gd._count || 1) - 1;
if (gd._count === 0) {
node.removeEventListener(dep, this.handleNative);
}
}
}
}
node.removeEventListener(evType, handler);
},
register: function(recog) {
this.recognizers.push(recog);
for (var i = 0; i < recog.emits.length; i++) {
this.gestures[recog.emits[i]] = recog;
}
},
findRecognizerByEvent: function(evName) {
for (var i = 0, r; i < this.recognizers.length; i++) {
r = this.recognizers[i];
for (var j = 0, n; j < r.emits.length; j++) {
n = r.emits[j];
if (n === evName) {
return r;
}
}
}
return null;
},
// set scrolling direction on node to check later on first move
// must call this before adding event listeners!
setTouchAction: function(node, value) {
if (HAS_NATIVE_TA) {
node.style.touchAction = value;
}
node[TOUCH_ACTION] = value;
},
fire: function(target, type, detail) {
var ev = Polymer.Base.fire(type, detail, {
node: target,
bubbles: true,
cancelable: true
});
// forward `preventDefault` in a clean way
if (ev.defaultPrevented) {
var preventer = detail.preventer || detail.sourceEvent;
if (preventer && preventer.preventDefault) {
preventer.preventDefault();
}
}
},
prevent: function(evName) {
var recognizer = this.findRecognizerByEvent(evName);
if (recognizer.info) {
recognizer.info.prevent = true;
}
},
/**
* Reset the 2500ms timeout on processing mouse input after detecting touch input.
*
* Touch inputs create synthesized mouse inputs anywhere from 0 to 2000ms after the touch.
* This method should only be called during testing with simulated touch inputs.
* Calling this method in production may cause duplicate taps or other gestures.
*
* @method resetMouseCanceller
*/
resetMouseCanceller: function() {
if (POINTERSTATE.mouse.mouseIgnoreJob) {
POINTERSTATE.mouse.mouseIgnoreJob.complete();
}
}
};
Gestures.register({
name: 'downup',
deps: ['mousedown', 'touchstart', 'touchend'],
flow: {
start: ['mousedown', 'touchstart'],
end: ['mouseup', 'touchend']
},
emits: ['down', 'up'],
info: {
movefn: null,
upfn: null
},
reset: function() {
untrackDocument(this.info);
},
mousedown: function(e) {
if (!hasLeftMouseButton(e)) {
return;
}
var t = Gestures.findOriginalTarget(e);
var self = this;
var movefn = function movefn(e) {
if (!hasLeftMouseButton(e)) {
self.fire('up', t, e);
untrackDocument(self.info);
}
};
var upfn = function upfn(e) {
if (hasLeftMouseButton(e)) {
self.fire('up', t, e);
}
untrackDocument(self.info);
};
trackDocument(this.info, movefn, upfn);
this.fire('down', t, e);
},
touchstart: function(e) {
this.fire('down', Gestures.findOriginalTarget(e), e.changedTouches[0], e);
},
touchend: function(e) {
this.fire('up', Gestures.findOriginalTarget(e), e.changedTouches[0], e);
},
fire: function(type, target, event, preventer) {
Gestures.fire(target, type, {
x: event.clientX,
y: event.clientY,
sourceEvent: event,
preventer: preventer,
prevent: function(e) {
return Gestures.prevent(e);
}
});
}
});
Gestures.register({
name: 'track',
touchAction: 'none',
deps: ['mousedown', 'touchstart', 'touchmove', 'touchend'],
flow: {
start: ['mousedown', 'touchstart'],
end: ['mouseup', 'touchend']
},
emits: ['track'],
info: {
x: 0,
y: 0,
state: 'start',
started: false,
moves: [],
addMove: function(move) {
if (this.moves.length > TRACK_LENGTH) {
this.moves.shift();
}
this.moves.push(move);
},
movefn: null,
upfn: null,
prevent: false
},
reset: function() {
this.info.state = 'start';
this.info.started = false;
this.info.moves = [];
this.info.x = 0;
this.info.y = 0;
this.info.prevent = false;
untrackDocument(this.info);
},
hasMovedEnough: function(x, y) {
if (this.info.prevent) {
return false;
}
if (this.info.started) {
return true;
}
var dx = Math.abs(this.info.x - x);
var dy = Math.abs(this.info.y - y);
return (dx >= TRACK_DISTANCE || dy >= TRACK_DISTANCE);
},
mousedown: function(e) {
if (!hasLeftMouseButton(e)) {
return;
}
var t = Gestures.findOriginalTarget(e);
var self = this;
var movefn = function movefn(e) {
var x = e.clientX, y = e.clientY;
if (self.hasMovedEnough(x, y)) {
// first move is 'start', subsequent moves are 'move', mouseup is 'end'
self.info.state = self.info.started ? (e.type === 'mouseup' ? 'end' : 'track') : 'start';
if (self.info.state === 'start') {
// if and only if tracking, always prevent tap
Gestures.prevent('tap');
}
self.info.addMove({x: x, y: y});
if (!hasLeftMouseButton(e)) {
// always fire "end"
self.info.state = 'end';
untrackDocument(self.info);
}
self.fire(t, e);
self.info.started = true;
}
};
var upfn = function upfn(e) {
if (self.info.started) {
movefn(e);
}
// remove the temporary listeners
untrackDocument(self.info);
};
// add temporary document listeners as mouse retargets
trackDocument(this.info, movefn, upfn);
this.info.x = e.clientX;
this.info.y = e.clientY;
},
touchstart: function(e) {
var ct = e.changedTouches[0];
this.info.x = ct.clientX;
this.info.y = ct.clientY;
},
touchmove: function(e) {
var t = Gestures.findOriginalTarget(e);
var ct = e.changedTouches[0];
var x = ct.clientX, y = ct.clientY;
if (this.hasMovedEnough(x, y)) {
if (this.info.state === 'start') {
// if and only if tracking, always prevent tap
Gestures.prevent('tap');
}
this.info.addMove({x: x, y: y});
this.fire(t, ct);
this.info.state = 'track';
this.info.started = true;
}
},
touchend: function(e) {
var t = Gestures.findOriginalTarget(e);
var ct = e.changedTouches[0];
// only trackend if track was started and not aborted
if (this.info.started) {
// reset started state on up
this.info.state = 'end';
this.info.addMove({x: ct.clientX, y: ct.clientY});
this.fire(t, ct, e);
}
},
fire: function(target, touch, preventer) {
var secondlast = this.info.moves[this.info.moves.length - 2];
var lastmove = this.info.moves[this.info.moves.length - 1];
var dx = lastmove.x - this.info.x;
var dy = lastmove.y - this.info.y;
var ddx, ddy = 0;
if (secondlast) {
ddx = lastmove.x - secondlast.x;
ddy = lastmove.y - secondlast.y;
}
return Gestures.fire(target, 'track', {
state: this.info.state,
x: touch.clientX,
y: touch.clientY,
dx: dx,
dy: dy,
ddx: ddx,
ddy: ddy,
sourceEvent: touch,
preventer: preventer,
hover: function() {
return Gestures.deepTargetFind(touch.clientX, touch.clientY);
}
});
}
});
Gestures.register({
name: 'tap',
deps: ['mousedown', 'click', 'touchstart', 'touchend'],
flow: {
start: ['mousedown', 'touchstart'],
end: ['click', 'touchend']
},
emits: ['tap'],
info: {
x: NaN,
y: NaN,
prevent: false
},
reset: function() {
this.info.x = NaN;
this.info.y = NaN;
this.info.prevent = false;
},
save: function(e) {
this.info.x = e.clientX;
this.info.y = e.clientY;
},
mousedown: function(e) {
if (hasLeftMouseButton(e)) {
this.save(e);
}
},
click: function(e) {
if (hasLeftMouseButton(e)) {
this.forward(e);
}
},
touchstart: function(e) {
this.save(e.changedTouches[0], e);
},
touchend: function(e) {
this.forward(e.changedTouches[0], e);
},
forward: function(e, preventer) {
var dx = Math.abs(e.clientX - this.info.x);
var dy = Math.abs(e.clientY - this.info.y);
var t = Gestures.findOriginalTarget(e);
// dx,dy can be NaN if `click` has been simulated and there was no `down` for `start`
if (isNaN(dx) || isNaN(dy) || (dx <= TAP_DISTANCE && dy <= TAP_DISTANCE) || isSyntheticClick(e)) {
// prevent taps from being generated if an event has canceled them
if (!this.info.prevent) {
Gestures.fire(t, 'tap', {
x: e.clientX,
y: e.clientY,
sourceEvent: e,
preventer: preventer
});
}
}
}
});
var DIRECTION_MAP = {
x: 'pan-x',
y: 'pan-y',
none: 'none',
all: 'auto'
};
Polymer.Base._addFeature({
_setupGestures: function() {
this.__polymerGestures = null;
},
// override _listen to handle gestures
_listen: function(node, eventName, handler) {
if (Gestures.gestures[eventName]) {
Gestures.add(node, eventName, handler);
} else {
node.addEventListener(eventName, handler);
}
},
// override _unlisten to handle gestures
_unlisten: function(node, eventName, handler) {
if (Gestures.gestures[eventName]) {
Gestures.remove(node, eventName, handler);
} else {
node.removeEventListener(eventName, handler);
}
},
/**
* Override scrolling behavior to all direction, one direction, or none.
*
* Valid scroll directions:
* - 'all': scroll in any direction
* - 'x': scroll only in the 'x' direction
* - 'y': scroll only in the 'y' direction
* - 'none': disable scrolling for this node
*
* @method setScrollDirection
* @param {String=} direction Direction to allow scrolling
* Defaults to `all`.
* @param {HTMLElement=} node Element to apply scroll direction setting.
* Defaults to `this`.
*/
setScrollDirection: function(direction, node) {
node = node || this;
Gestures.setTouchAction(node, DIRECTION_MAP[direction] || 'auto');
}
});
// export
Polymer.Gestures = Gestures;
})();
</script>
| mgiuffrida/polymer | src/standard/gestures.html | HTML | bsd-3-clause | 22,385 |
require 'rubygems'
# The helper class exists to do string manipulation and heavy lifting
def url_escape_hash(hash)
hash.each do |k,v|
v = CGI::escapeHTML(v)
if v
# convert bullets
v = v.gsub("*-","<bullet>")
v = v.gsub("-*","</bullet>")
#convert h4
v = v.gsub("[==","<h4>")
v = v.gsub("==]","</h4>")
#convert indent text
v = v.gsub("[--","<indented>")
v = v.gsub("--]","</indented>")
#convert indent text
v = v.gsub("[~~","<italics>")
v = v.gsub("~~]","</italics>")
end
# replace linebreaks with paragraph xml elements
if v =~ /\r\n/
new_v = ""
brs = v.split("\r\n")
brs.each do |br|
new_v << "<paragraph>"
new_v << br
new_v << "</paragraph>"
end
v = new_v
elsif k == "remediation" or k == "overview" or k == "poc" or k == "affected_hosts"
new_v = "<paragraph>#{v}</paragraph>"
v = new_v
end
hash[k] = v
end
return hash
end
def meta_markup(text)
new_text = text.gsub("<paragraph>","
").gsub("</paragraph>","")
new_text = new_text.gsub("<bullet>","*-").gsub("</bullet>","-*")
new_text = new_text.gsub("<h4>","[==").gsub("</h4>","==]")
new_text = new_text.gsub("<code>","[[[").gsub("</code>","]]]")
new_text = new_text.gsub("<indented>","[--").gsub("</indented>","--]")
new_text = new_text.gsub("<italics>","[~~").gsub("</italics>","~~]")
end
# URL escaping messes up the inserted XML, this method switches it back to XML elements
def meta_markup_unencode(findings_xml, customer_name)
# code tags get added in later
findings_xml = findings_xml.gsub("[[[","<code>")
findings_xml = findings_xml.gsub("]]]","</code>")
# creates paragraphs
findings_xml = findings_xml.gsub("<paragraph>","<paragraph>")
findings_xml = findings_xml.gsub("</paragraph>","</paragraph>")
# same for the bullets
findings_xml = findings_xml.gsub("<bullet>","<bullet>")
findings_xml = findings_xml.gsub("</bullet>","</bullet>")
# same for the h4
findings_xml = findings_xml.gsub("<h4>","<h4>")
findings_xml = findings_xml.gsub("</h4>","</h4>")
# same for the code markings
findings_xml = findings_xml.gsub("<code>","<code>")
findings_xml = findings_xml.gsub("</code>","</code>")
# same for the indented text
findings_xml = findings_xml.gsub("<indented>","<indented>")
findings_xml = findings_xml.gsub("</indented>","</indented>")
# same for the indented text
findings_xml = findings_xml.gsub("<italics>","<italics>")
findings_xml = findings_xml.gsub("</italics>","</italics>")
# changes the <<CUSTOMER>> marks
if customer_name
findings_xml = findings_xml.gsub("&lt;&lt;CUSTOMER&gt;&gt;","#{customer_name}")
end
#this is for re-upping the comment fields
findings_xml = findings_xml.gsub("<modified>","<modified>")
findings_xml = findings_xml.gsub("</modified>","</modified>")
findings_xml = findings_xml.gsub("<new_finding>","<new_finding>")
findings_xml = findings_xml.gsub("</new_finding>","</new_finding>")
# these are for beautification
findings_xml = findings_xml.gsub("&quot;","\"")
findings_xml = findings_xml.gsub("&","&")
findings_xml = findings_xml.gsub("&lt;","<").gsub("&gt;",">")
return findings_xml
end
def compare_text(new_text, orig_text)
if orig_text == nil
# there is no master finding, must be new
t = ""
t << "<new_finding></new_finding>#{new_text}"
return t
end
if new_text == orig_text
return new_text
else
n_t = ""
n_t << "<modified></modified>#{new_text}"
return n_t
end
end
# CVSS helper, there is a lot of hardcoded stuff
def cvss(data)
av = data["av"].downcase
ac = data["ac"].downcase
au = data["au"].downcase
c = data["c"].downcase
i = data["i"].downcase
a = data["a"].downcase
e = data["e"].downcase
rl = data["rl"].downcase
rc = data["rc"].downcase
cdp = data["cdp"].downcase
td = data["td"].downcase
cr = data["cr"].downcase
ir = data["ir"].downcase
ar = data["ar"].downcase
if ac == "high"
cvss_ac = 0.35
elsif ac == "medium"
cvss_ac = 0.61
else
cvss_ac = 0.71
end
if au == "none"
cvss_au = 0.704
elsif au == "single"
cvss_au = 0.56
else
cvss_au = 0.45
end
if av == "local"
cvss_av = 0.395
elsif av == "local network"
cvss_av = 0.646
else
cvss_av = 1
end
if c == "none"
cvss_c = 0
elsif c == "partial"
cvss_c = 0.275
else
cvss_c = 0.660
end
if i == "none"
cvss_i = 00
elsif i == "partial"
cvss_i = 0.275
else
cvss_i = 0.660
end
if a == "none"
cvss_a = 0
elsif a == "partial"
cvss_a = 0.275
else
cvss_a = 0.660
end
# temporal score calculations
if e == "unproven exploit exists"
cvss_e = 0.85
elsif e == "proof-of-concept code"
cvss_e = 0.90
elsif e == "functional exploit exists"
cvss_e = 0.95
else
cvss_e = 1
end
if rl == "official fix"
cvss_rl = 0.87
elsif rl == "temporary fix"
cvss_rl = 0.90
elsif rl == "workaround"
cvss_rl = 0.95
else
cvss_rl = 1
end
if rc == "unconfirmed"
cvss_rc = 0.90
elsif rc == "uncorroborated"
cvss_rc = 0.95
else
cvss_rc = 1
end
#environemental
if cdp == "low"
cvss_cdp = 0.1
elsif cdp == "low-medium"
cvss_cdp = 0.3
elsif cdp == "medium-high"
cvss_cdp = 0.4
elsif cdp == "high"
cvss_cdp = 0.5
else
cvss_cdp = 0
end
if td == "none"
cvss_td = 0
elsif td == "low"
cvss_td = 0.25
elsif td == "medium"
cvss_td = 0.75
else
cvss_td = 1
end
if cr == "low"
cvss_cr = 0.5
elsif cr == "high"
cvss_cr = 1.51
else
cvss_cr = 1
end
if ir == "low"
cvss_ir = 0.5
elsif ir == "high"
cvss_ir = 1.51
else
cvss_ir = 1
end
if ar == "low"
cvss_ar = 0.5
elsif ar == "high"
cvss_ar = 1.51
else
cvss_ar = 1
end
cvss_impact = 10.41 * (1 - (1 - cvss_c) * (1 - cvss_i) * (1 - cvss_a))
cvss_exploitability = 20 * cvss_ac * cvss_au * cvss_av
if cvss_impact == 0
cvss_impact_f = 0
else
cvss_impact_f = 1.176
end
cvss_base = (0.6*cvss_impact + 0.4*cvss_exploitability-1.5)*cvss_impact_f
cvss_temporal = cvss_base * cvss_e * cvss_rl * cvss_rc
cvss_modified_impact = [10, 10.41 * (1 - (1 - cvss_c * cvss_cr) * (1 - cvss_i * cvss_ir) * (1 - cvss_a * cvss_ar))].min
if cvss_modified_impact == 0
cvss_modified_impact_f = 0
else
cvss_modified_impact_f = 1.176
end
cvss_modified_base = (0.6*cvss_modified_impact + 0.4*cvss_exploitability-1.5)*cvss_modified_impact_f
cvss_adjusted_temporal = cvss_modified_base * cvss_e * cvss_rl * cvss_rc
cvss_environmental = (cvss_adjusted_temporal + (10 - cvss_adjusted_temporal) * cvss_cdp) * cvss_td
if cvss_environmental
cvss_total = cvss_environmental
elsif cvss_temporal
cvss_total = cvss_temporal
else
cvss_total = cvss_base
end
data["cvss_base"] = sprintf("%0.1f" % cvss_base)
data["cvss_impact"] = sprintf("%0.1f" % cvss_impact)
data["cvss_exploitability"] = sprintf("%0.1f" % cvss_exploitability)
data["cvss_temporal"] = sprintf("%0.1f" % cvss_temporal)
data["cvss_environmental"] = sprintf("%0.1f" % cvss_environmental)
data["cvss_modified_impact"] = sprintf("%0.1f" % cvss_modified_impact)
data["cvss_total"] = sprintf("%0.1f" % cvss_total)
return data
end
# there are three scoring types; risk, dread and cvss
# this sets a score for all three in case the user switches later
def convert_score(finding)
if(finding.cvss_total == nil)
puts "|!| No CVSS score exists"
finding.cvss_total = 0
end
if(finding.dread_total == nil)
puts "|!| No CVSS score exists"
finding.dread_total = 0
end
if(finding.risk == nil)
puts "|!| No CVSS score exists"
finding.risk = 0
end
return finding
end
| ccammilleri/Serpico | helpers/helper.rb | Ruby | bsd-3-clause | 7,803 |
/*
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/svg/SVGFEDropShadowElement.h"
#include "SVGNames.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/SVGRenderStyle.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
namespace WebCore {
// Animated property definitions
DEFINE_ANIMATED_STRING(SVGFEDropShadowElement, SVGNames::inAttr, In1, in1)
DEFINE_ANIMATED_NUMBER(SVGFEDropShadowElement, SVGNames::dxAttr, Dx, dx)
DEFINE_ANIMATED_NUMBER(SVGFEDropShadowElement, SVGNames::dyAttr, Dy, dy)
DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEDropShadowElement, SVGNames::stdDeviationAttr, stdDeviationXIdentifier(), StdDeviationX, stdDeviationX)
DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFEDropShadowElement, SVGNames::stdDeviationAttr, stdDeviationYIdentifier(), StdDeviationY, stdDeviationY)
BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEDropShadowElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
REGISTER_LOCAL_ANIMATED_PROPERTY(dx)
REGISTER_LOCAL_ANIMATED_PROPERTY(dy)
REGISTER_LOCAL_ANIMATED_PROPERTY(stdDeviationX)
REGISTER_LOCAL_ANIMATED_PROPERTY(stdDeviationY)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
inline SVGFEDropShadowElement::SVGFEDropShadowElement(const QualifiedName& tagName, Document* document)
: SVGFilterPrimitiveStandardAttributes(tagName, document)
, m_dx(2)
, m_dy(2)
, m_stdDeviationX(2)
, m_stdDeviationY(2)
{
ASSERT(hasTagName(SVGNames::feDropShadowTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEDropShadowElement();
}
PassRefPtr<SVGFEDropShadowElement> SVGFEDropShadowElement::create(const QualifiedName& tagName, Document* document)
{
return adoptRef(new SVGFEDropShadowElement(tagName, document));
}
const AtomicString& SVGFEDropShadowElement::stdDeviationXIdentifier()
{
DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGStdDeviationX", AtomicString::ConstructFromLiteral));
return s_identifier;
}
const AtomicString& SVGFEDropShadowElement::stdDeviationYIdentifier()
{
DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGStdDeviationY", AtomicString::ConstructFromLiteral));
return s_identifier;
}
void SVGFEDropShadowElement::setStdDeviation(float x, float y)
{
setStdDeviationXBaseValue(x);
setStdDeviationYBaseValue(y);
invalidate();
}
bool SVGFEDropShadowElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
supportedAttributes.add(SVGNames::inAttr);
supportedAttributes.add(SVGNames::dxAttr);
supportedAttributes.add(SVGNames::dyAttr);
supportedAttributes.add(SVGNames::stdDeviationAttr);
}
return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}
void SVGFEDropShadowElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (!isSupportedAttribute(name)) {
SVGFilterPrimitiveStandardAttributes::parseAttribute(name, value);
return;
}
if (name == SVGNames::stdDeviationAttr) {
float x, y;
if (parseNumberOptionalNumber(value, x, y)) {
setStdDeviationXBaseValue(x);
setStdDeviationYBaseValue(y);
}
return;
}
if (name == SVGNames::inAttr) {
setIn1BaseValue(value);
return;
}
if (name == SVGNames::dxAttr) {
setDxBaseValue(value.toFloat());
return;
}
if (name == SVGNames::dyAttr) {
setDyBaseValue(value.toFloat());
return;
}
ASSERT_NOT_REACHED();
}
void SVGFEDropShadowElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
SVGFilterPrimitiveStandardAttributes::svgAttributeChanged(attrName);
return;
}
SVGElementInstance::InvalidationGuard invalidationGuard(this);
if (attrName == SVGNames::inAttr
|| attrName == SVGNames::stdDeviationAttr
|| attrName == SVGNames::dxAttr
|| attrName == SVGNames::dyAttr) {
invalidate();
return;
}
ASSERT_NOT_REACHED();
}
PassRefPtr<FilterEffect> SVGFEDropShadowElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
{
RenderObject* renderer = this->renderer();
if (!renderer)
return 0;
if (stdDeviationX() < 0 || stdDeviationY() < 0)
return 0;
ASSERT(renderer->style());
const SVGRenderStyle* svgStyle = renderer->style()->svgStyle();
Color color = svgStyle->floodColor();
float opacity = svgStyle->floodOpacity();
FilterEffect* input1 = filterBuilder->getEffectById(in1());
if (!input1)
return 0;
RefPtr<FilterEffect> effect = FEDropShadow::create(filter, stdDeviationX(), stdDeviationY(), dx(), dy(), color, opacity);
effect->inputEffects().append(input1);
return effect.release();
}
}
| espadrine/opera | chromium/src/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.cpp | C++ | bsd-3-clause | 5,902 |
<?php
namespace modules\translations\controllers\console;
use modules\lang\models\Lang;
use modules\translations\models\MessageCategory;
use Yii;
use yii\console\Controller;
use yii\console\Exception;
use yii\helpers\FileHelper;
use modules\translations\models\Message;
use modules\translations\models\SourceMessage;
class I18nController extends Controller
{
/**
* @param string $sourcePath
* @throws Exception
*/
public function actionImport($sourcePath = null)
{
if (!$sourcePath) {
$sourcePath = $this->prompt('Enter a source path');
}
$sourcePath = realpath(Yii::getAlias($sourcePath));
if (!is_dir($sourcePath)) {
throw new Exception('The source path ' . $sourcePath . ' is not a valid directory.');
}
$translationsFiles = FileHelper::findFiles($sourcePath, ['only' => ['*.php']]);
foreach ($translationsFiles as $translationsFile) {
$relativePath = trim(str_replace([$sourcePath, '.php'], '', $translationsFile), '/,\\');
$relativePath = FileHelper::normalizePath($relativePath, '/');
$relativePath = explode('/', $relativePath, 2);
if (count($relativePath) > 1) {
$language = $this->prompt('Enter language.', ['default' => $relativePath[0]]);
$category = $this->prompt('Enter category.', ['default' => $relativePath[1]]);
$categoryId = $this->addCategory($category);
$translations = require_once $translationsFile;
if (is_array($translations)) {
foreach ($translations as $sourceMessage => $translation) {
if (!empty($translation)) {
$sourceMessage = $this->getSourceMessage($categoryId, $sourceMessage);
$this->setTranslation($sourceMessage, $language, $translation);
}
}
}
}
}
echo PHP_EOL . 'Done.' . PHP_EOL;
}
private function addCategory($category){
$catModel = MessageCategory::find()->where(['name'=>$category])->one();
if(!$catModel){
$catModel = new MessageCategory();
$catModel->name = $category;
$catModel->save();
}
return $catModel->id;
}
/**
* @param string $category
* @param string $message
* @return SourceMessage
*/
private function getSourceMessage($category, $message)
{
$params = [
'category_id' => $category,
'message' => $message
];
$sourceMessage = SourceMessage::find()
->where($params)
->with('messages')
->one();
if (!$sourceMessage) {
$sourceMessage = new SourceMessage;
$sourceMessage->setAttributes($params, false);
$sourceMessage->save(false);
}
return $sourceMessage;
}
/**
* @param SourceMessage $sourceMessage
* @param string $language
* @param string $translation
*/
private function setTranslation($sourceMessage, $language, $translation)
{
/** @var Message[] $messages */
$messages = $sourceMessage->messages;
$lang = Lang::find()->where(['url'=>$language])->one();
if(!$lang)
return;
$langId = $lang->id;
if (isset($messages[$langId]) /*&& $messages[$langId]->translation === null*/) {
$messages[$langId]->translation = $translation;
$messages[$langId]->save(false);
} elseif (!isset($messages[$langId])) {
$message = new Message;
$message->setAttributes([
'lang_id' => $langId,
'translation' => $translation
], false);
$sourceMessage->link('messages', $message);
}
}
public function actionFlush()
{
$tableNames = [
Message::tableName(),
SourceMessage::tableName()
];
$db = Yii::$app->getDb();
foreach ($tableNames as $tableName) {
$db->createCommand()
->delete($tableName)
->execute();
}
echo PHP_EOL . 'Done.' . PHP_EOL;
}
} | zserg84/tender | modules/translations/controllers/console/I18nController.php | PHP | bsd-3-clause | 4,308 |
#include <CGAL/Epick_d.h>
#include <CGAL/point_generators_d.h>
#include <CGAL/Manhattan_distance_iso_box_point.h>
#include <CGAL/K_neighbor_search.h>
#include <CGAL/Search_traits_d.h>
typedef CGAL::Epick_d<CGAL::Dimension_tag<4> > Kernel;
typedef Kernel::Point_d Point_d;
typedef CGAL::Random_points_in_cube_d<Point_d> Random_points_iterator;
typedef Kernel::Iso_box_d Iso_box_d;
typedef Kernel TreeTraits;
typedef CGAL::Manhattan_distance_iso_box_point<TreeTraits> Distance;
typedef CGAL::K_neighbor_search<TreeTraits, Distance> Neighbor_search;
typedef Neighbor_search::Tree Tree;
int main() {
const int N = 1000;
const unsigned int K = 10;
Tree tree;
Random_points_iterator rpit(4,1000.0);
for(int i = 0; i < N; i++){
tree.insert(*rpit++);
}
Point_d pp(0.1,0.1,0.1,0.1);
Point_d qq(0.2,0.2,0.2,0.2);
Iso_box_d query(pp,qq);
Distance tr_dist;
Neighbor_search N1(tree, query, 5, 10.0, false); // eps=10.0, nearest=false
std::cout << "For query rectangle = [0.1, 0.2]^4 " << std::endl
<< "the " << K << " approximate furthest neighbors are: " << std::endl;
for (Neighbor_search::iterator it = N1.begin();it != N1.end();it++) {
std::cout << " Point " << it->first << " at distance " << tr_dist.inverse_of_transformed_distance(it->second) << std::endl;
}
return 0;
}
| hlzz/dotfiles | graphics/cgal/Spatial_searching/examples/Spatial_searching/general_neighbor_searching.cpp | C++ | bsd-3-clause | 1,316 |
/*L
* Copyright RTI International
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/webgenome/LICENSE.txt for details.
*/
/*
$Revision: 1.1 $
$Date: 2007-08-22 20:03:57 $
*/
package org.rti.webgenome.webui.struts.upload;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.rti.webgenome.util.SystemUtils;
import org.rti.webgenome.webui.struts.BaseForm;
/**
* Form for inputting the name of a rectangular file
* column that contains reporter names.
* @author dhall
*
*/
public class ReporterColumnNameForm extends BaseForm {
/** Serialized version ID. */
private static final long serialVersionUID =
SystemUtils.getLongApplicationProperty("serial.version.uid");
/** Name of column containing reporter names. */
private String reporterColumnName = null;
/**
* Get name of column containing reporter names.
* @return Column heading.
*/
public String getReporterColumnName() {
return reporterColumnName;
}
/**
* Set name of column containing reporter names.
* @param reporterColumnName Column heading.
*/
public void setReporterColumnName(final String reporterColumnName) {
this.reporterColumnName = reporterColumnName;
}
/**
* {@inheritDoc}
*/
@Override
public ActionErrors validate(final ActionMapping mapping,
final HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (this.reporterColumnName == null
|| this.reporterColumnName.length() < 1) {
errors.add("reporterColumnName", new ActionError("invalid.field"));
}
if (errors.size() > 0) {
errors.add("global", new ActionError("invalid.fields"));
}
return errors;
}
}
| NCIP/webgenome | tags/WEBGENOME_R3.2_6MAR2009_BUILD1/java/webui/src/org/rti/webgenome/webui/struts/upload/ReporterColumnNameForm.java | Java | bsd-3-clause | 1,844 |
//===-- Status.h - Renders a 96x32 Status Display ------------------ c++ --===//
//
// UWH Timer
//
// This file is distributed under the BSD 3-Clause License.
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef STATUS_H
#define STATUS_H
class UWHDCanvas;
void renderStatus(UWHDCanvas *C);
#endif
| jroelofs/uwh-display | include/uwhd/display/Status.h | C | bsd-3-clause | 436 |
from datetime import datetime, timedelta
from django import http
from django.conf import settings
from django.core.exceptions import PermissionDenied
import mock
import pytest
from olympia.amo.tests import BaseTestCase, TestCase
from olympia.amo import decorators, get_user, set_user
from olympia.amo.urlresolvers import reverse
from olympia.users.models import UserProfile
pytestmark = pytest.mark.django_db
def test_post_required():
def func(request):
return mock.sentinel.response
g = decorators.post_required(func)
request = mock.Mock()
request.method = 'GET'
assert isinstance(g(request), http.HttpResponseNotAllowed)
request.method = 'POST'
assert g(request) == mock.sentinel.response
def test_json_view():
"""Turns a Python object into a response."""
def func(request):
return {'x': 1}
response = decorators.json_view(func)(mock.Mock())
assert isinstance(response, http.HttpResponse)
assert response.content == '{"x": 1}'
assert response['Content-Type'] == 'application/json'
assert response.status_code == 200
def test_json_view_normal_response():
"""Normal responses get passed through."""
expected = http.HttpResponseForbidden()
def func(request):
return expected
response = decorators.json_view(func)(mock.Mock())
assert expected is response
assert response['Content-Type'] == 'text/html; charset=utf-8'
def test_json_view_error():
"""json_view.error returns 400 responses."""
response = decorators.json_view.error({'msg': 'error'})
assert isinstance(response, http.HttpResponseBadRequest)
assert response.content == '{"msg": "error"}'
assert response['Content-Type'] == 'application/json'
def test_json_view_status():
def func(request):
return {'x': 1}
response = decorators.json_view(func, status_code=202)(mock.Mock())
assert response.status_code == 202
def test_json_view_response_status():
response = decorators.json_response({'msg': 'error'}, status_code=202)
assert response.content == '{"msg": "error"}'
assert response['Content-Type'] == 'application/json'
assert response.status_code == 202
class TestTaskUser(TestCase):
fixtures = ['base/users']
def test_set_task_user(self):
@decorators.set_task_user
def some_func():
return get_user()
set_user(UserProfile.objects.get(username='regularuser'))
assert get_user().pk == 999
assert some_func().pk == int(settings.TASK_USER_ID)
assert get_user().pk == 999
class TestLoginRequired(BaseTestCase):
def setUp(self):
super(TestLoginRequired, self).setUp()
self.f = mock.Mock()
self.f.__name__ = 'function'
self.request = mock.Mock()
self.request.user.is_authenticated.return_value = False
self.request.get_full_path.return_value = 'path'
def test_normal(self):
func = decorators.login_required(self.f)
response = func(self.request)
assert not self.f.called
assert response.status_code == 302
assert response['Location'] == (
'%s?to=%s' % (reverse('users.login'), 'path'))
def test_no_redirect(self):
func = decorators.login_required(self.f, redirect=False)
response = func(self.request)
assert not self.f.called
assert response.status_code == 401
def test_decorator_syntax(self):
# @login_required(redirect=False)
func = decorators.login_required(redirect=False)(self.f)
response = func(self.request)
assert not self.f.called
assert response.status_code == 401
def test_no_redirect_success(self):
func = decorators.login_required(redirect=False)(self.f)
self.request.user.is_authenticated.return_value = True
func(self.request)
assert self.f.called
class TestSetModifiedOn(TestCase):
fixtures = ['base/users']
@decorators.set_modified_on
def some_method(self, worked):
return worked
def test_set_modified_on(self):
users = list(UserProfile.objects.all()[:3])
self.some_method(True, set_modified_on=users)
for user in users:
assert UserProfile.objects.get(pk=user.pk).modified.date() == (
datetime.today().date())
def test_not_set_modified_on(self):
yesterday = datetime.today() - timedelta(days=1)
qs = UserProfile.objects.all()
qs.update(modified=yesterday)
users = list(qs[:3])
self.some_method(False, set_modified_on=users)
for user in users:
date = UserProfile.objects.get(pk=user.pk).modified.date()
assert date < datetime.today().date()
class TestPermissionRequired(TestCase):
def setUp(self):
super(TestPermissionRequired, self).setUp()
self.f = mock.Mock()
self.f.__name__ = 'function'
self.request = mock.Mock()
@mock.patch('olympia.access.acl.action_allowed')
def test_permission_not_allowed(self, action_allowed):
action_allowed.return_value = False
func = decorators.permission_required('', '')(self.f)
with self.assertRaises(PermissionDenied):
func(self.request)
@mock.patch('olympia.access.acl.action_allowed')
def test_permission_allowed(self, action_allowed):
action_allowed.return_value = True
func = decorators.permission_required('', '')(self.f)
func(self.request)
assert self.f.called
@mock.patch('olympia.access.acl.action_allowed')
def test_permission_allowed_correctly(self, action_allowed):
func = decorators.permission_required('Admin', '%')(self.f)
func(self.request)
action_allowed.assert_called_with(self.request, 'Admin', '%')
| andymckay/addons-server | src/olympia/amo/tests/test_decorators.py | Python | bsd-3-clause | 5,822 |
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/requestid"
"github.com/kataras/golog"
)
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
app.Logger().SetFormat("json", " ")
// to register a custom Formatter:
// app.Logger().RegisterFormatter(golog.Formatter...)
// Also, see app.Logger().SetLevelOutput(level string, w io.Writer)
// to set a custom writer for a specific level.
app.Use(requestid.New())
/* Example Output:
{
"timestamp": 1591422944,
"level": "debug",
"message": "This is a message with data",
"fields": {
"username": "kataras"
},
"stacktrace": [
{
"function": "main.main",
"source": "C:/mygopath/src/github.com/kataras/iris/_examples/logging/json-logger/main.go:16"
}
]
}
*/
app.Logger().Debugf("This is a %s with data (debug prints the stacktrace too)", "message", golog.Fields{
"username": "kataras",
})
/* Example Output:
{
"timestamp": 1591422944,
"level": "info",
"message": "An info message",
"fields": {
"home": "https://iris-go.com"
}
}
*/
app.Logger().Infof("An info message", golog.Fields{"home": "https://iris-go.com"})
app.Get("/ping", ping)
// Navigate to http://localhost:8080/ping.
app.Listen(":8080" /*, iris.WithoutBanner*/)
}
func ping(ctx iris.Context) {
/* Example Output:
{
"timestamp": 1591423046,
"level": "debug",
"message": "Request path: /ping",
"fields": {
"request_id": "fc12d88a-a338-4bb9-aa5e-126f2104365c"
},
"stacktrace": [
{
"function": "main.ping",
"source": "C:/mygopath/src/github.com/kataras/iris/_examples/logging/json-logger/main.go:82"
},
...
]
}
*/
ctx.Application().Logger().Debugf("Request path: %s", ctx.Path(), golog.Fields{
"request_id": ctx.GetID(),
})
ctx.WriteString("pong")
}
| kataras/iris | _examples/logging/json-logger/main.go | GO | bsd-3-clause | 1,968 |
from django.core.management.base import BaseCommand
import amo
from mkt.webapps.models import AddonPremium
class Command(BaseCommand):
help = 'Clean up existing AddonPremium objects for free apps.'
def handle(self, *args, **options):
(AddonPremium.objects.filter(addon__premium_type__in=amo.ADDON_FREES)
.delete())
| andymckay/zamboni | mkt/developers/management/commands/cleanup_addon_premium.py | Python | bsd-3-clause | 364 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__char_file_ifstream_08.cpp
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-08.tmpl.cpp
*/
/*
* @description
* CWE: 23 Relative Path Traversal
* BadSource: file Read input from a file
* GoodSource: Use a fixed file name
* Sink: ifstream
* BadSink : Open the file named in data using ifstream::open()
* Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse())
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#define BASEPATH "c:\\temp\\"
#else
#include <wchar.h>
#define BASEPATH "/tmp/"
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#include <fstream>
using namespace std;
/* The two function below always return the same value, so a tool
should be able to identify that calls to the functions will always
return a fixed value. */
static int staticReturnsTrue()
{
return 1;
}
static int staticReturnsFalse()
{
return 0;
}
namespace CWE23_Relative_Path_Traversal__char_file_ifstream_08
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
if(staticReturnsTrue())
{
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (FILENAME_MAX-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
}
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */
static void goodG2B1()
{
char * data;
char dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
if(staticReturnsFalse())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a fixed file name */
strcat(data, "file.txt");
}
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
char * data;
char dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
if(staticReturnsTrue())
{
/* FIX: Use a fixed file name */
strcat(data, "file.txt");
}
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE23_Relative_Path_Traversal__char_file_ifstream_08; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE23_Relative_Path_Traversal/s02/CWE23_Relative_Path_Traversal__char_file_ifstream_08.cpp | C++ | bsd-3-clause | 4,569 |
% diagram A1-2
\verbatimlines
% inc
Incorporating new mail into inbox...
1+E02/28 0227-EST mrose test message <<ENCRYPTED MESSAGE: TTI
Incorporating encrypted mail into inbox...
1+ 02/28 0227-EST mrose test message <<mumble, mumble. >>
?endverbatim
| dscho/nmh | docs/historical/mh-6.8.5/papers/trusted/diagramA1-2.tex | TeX | bsd-3-clause | 285 |
package org.hisp.dhis.sms.listener;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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 java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramInstanceService;
import org.hisp.dhis.sms.command.SMSCommand;
import org.hisp.dhis.sms.command.SMSCommandService;
import org.hisp.dhis.sms.command.code.SMSCode;
import org.hisp.dhis.sms.incoming.IncomingSms;
import org.hisp.dhis.sms.incoming.SmsMessageStatus;
import org.hisp.dhis.sms.parse.ParserType;
import org.hisp.dhis.sms.parse.SMSParserException;
import org.hisp.dhis.system.util.SmsUtils;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.trackedentity.TrackedEntityTypeService;
import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class TrackedEntityRegistrationSMSListener
extends BaseSMSListener
{
private static final String SUCCESS_MESSAGE = "Tracked Entity Registered Successfully with uid. ";
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
@Autowired
private SMSCommandService smsCommandService;
@Autowired
private TrackedEntityTypeService trackedEntityTypeService;
@Autowired
private TrackedEntityInstanceService trackedEntityInstanceService;
@Autowired
private ProgramInstanceService programInstanceService;
// -------------------------------------------------------------------------
// IncomingSmsListener implementation
// -------------------------------------------------------------------------
@Override
protected void postProcess( IncomingSms sms, SMSCommand smsCommand, Map<String, String> parsedMessage )
{
String message = sms.getText();
Date date = SmsUtils.lookForDate( message );
String senderPhoneNumber = StringUtils.replace( sms.getOriginator(), "+", "" );
Collection<OrganisationUnit> orgUnits = getOrganisationUnits( sms );
Program program = smsCommand.getProgram();
OrganisationUnit orgUnit = SmsUtils.selectOrganisationUnit( orgUnits, parsedMessage, smsCommand );
if ( !program.hasOrganisationUnit( orgUnit ) )
{
sendFeedback( SMSCommand.NO_OU_FOR_PROGRAM, senderPhoneNumber, WARNING );
throw new SMSParserException( SMSCommand.NO_OU_FOR_PROGRAM );
}
TrackedEntityInstance trackedEntityInstance = new TrackedEntityInstance();
trackedEntityInstance.setOrganisationUnit( orgUnit );
trackedEntityInstance.setTrackedEntityType( trackedEntityTypeService.getTrackedEntityByName( smsCommand.getProgram().getTrackedEntityType().getName() ) );
Set<TrackedEntityAttributeValue> patientAttributeValues = new HashSet<>();
smsCommand.getCodes().stream()
.filter( code -> parsedMessage.containsKey( code.getCode() ) )
.forEach( code ->
{
TrackedEntityAttributeValue trackedEntityAttributeValue = this.createTrackedEntityAttributeValue( parsedMessage, code, trackedEntityInstance) ;
patientAttributeValues.add( trackedEntityAttributeValue );
});
int trackedEntityInstanceId = 0;
if ( patientAttributeValues.size() > 0 )
{
trackedEntityInstanceId = trackedEntityInstanceService.createTrackedEntityInstance( trackedEntityInstance,
null, null, patientAttributeValues );
}
else
{
sendFeedback( "No TrackedEntityAttribute found", senderPhoneNumber, WARNING );
}
TrackedEntityInstance tei = trackedEntityInstanceService.getTrackedEntityInstance( trackedEntityInstanceId );
programInstanceService.enrollTrackedEntityInstance( tei, smsCommand.getProgram(), new Date(), date, orgUnit );
sendFeedback( StringUtils.defaultIfBlank( smsCommand.getSuccessMessage(), SUCCESS_MESSAGE + tei.getUid() ), senderPhoneNumber, INFO );
update( sms, SmsMessageStatus.PROCESSED, true );
}
@Override
protected SMSCommand getSMSCommand( IncomingSms sms )
{
return smsCommandService.getSMSCommand( SmsUtils.getCommandString( sms ),
ParserType.TRACKED_ENTITY_REGISTRATION_PARSER );
}
private TrackedEntityAttributeValue createTrackedEntityAttributeValue( Map<String, String> parsedMessage,
SMSCode code, TrackedEntityInstance trackedEntityInstance )
{
String value = parsedMessage.get( code.getCode() );
TrackedEntityAttribute trackedEntityAttribute = code.getTrackedEntityAttribute();
TrackedEntityAttributeValue trackedEntityAttributeValue = new TrackedEntityAttributeValue();
trackedEntityAttributeValue.setAttribute( trackedEntityAttribute );
trackedEntityAttributeValue.setEntityInstance( trackedEntityInstance );
trackedEntityAttributeValue.setValue( value );
return trackedEntityAttributeValue;
}
}
| msf-oca-his/dhis-core | dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/sms/listener/TrackedEntityRegistrationSMSListener.java | Java | bsd-3-clause | 7,054 |
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yiic message' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE, this file must be saved in UTF-8 encoding.
*/
return array(
'Community' => 'Сообщество',
'forum' => 'форум',
'Thank you!' => 'Спасибо!',
'Help us!' => 'Помоги нам!',
'Error' => 'Ошибка',
'0.2' => '0.2',
'< Back' => '< Назад',
'Optional.' => 'Дополнительно.',
'{app} can help to deploy YiiFramework project fast and easy.' => '{app} позволит быстро и легко запустить новый проект на Yiiframework',
'APC extension' => 'Расширение APC',
'Activation of Yupe core!' => 'Активация ядра Yupe!',
'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-classes</a>' => 'Все <a href="http://www.yiiframework.com/doc/api/#system.db">БД-классы</a>',
'An error occurred during the installation of modules - copying the file to a folder modulesBack with error!' => 'Во время установки модулей произошла ошибка - файлы модулей с ошибкой копируются в каталог modulesBack',
'Assets folder' => 'Каталог Assets',
'At startup errors occured, please check the permissions for the all the files and directories (see the above errors)' => 'Во время начала установки произошли ошибки. Проверьте права для всех необходимых директорий. (Смотрите ошибки ниже)',
'Can not open file \'{file}\' in write mode!' => 'Не возможно открыть файл \'{file}\' для записи',
'Configuration option safe_mode' => 'Опции конфигурации safe_mode',
'Could not obtain information about the location. Please check whether the correct value in the variable {path_info} (or {php_self} and {script_name}).' => 'Не удалось получить информацию о директории. Проверьте правильность значений переменных {path_info} (или {php_self} и {script_name})',
'Couldn\'t connect to DB with these params!' => 'Не удалось подключиться к базе данных используя текущие параметры!',
'Couldn\'t connect to DB!' => 'Не удалось подключиться к базе данных!',
'Ctype extension' => 'Расширение Ctype',
'DOM extension' => 'Расширение DOM',
'Email' => 'Email',
'Administrator e-mail' => 'Email администратора',
'Site administrator e-mail. Uses for admin cp authorization.' => 'Email администратора сайта. Используется для авторизации в панели управления.',
'Everything is fine!' => 'Все в порядке!',
'Failed to create the database!' => 'Не удалось создать базу данных!',
'File db.php' => 'Файл db.php',
'GD extension installed {br} without the support of FreeType' => 'Расширение GD установлено {br} без поддержки FreeType',
'GD extension {br} with support for FreeType {br} or ImageMagick {br} supporting PNG' => 'Расширение GD {br} с поддержкой FreeType {br} или ImageMagick {br} с поддержкой PNG',
'ImageMagick or GD extension is not installed' => 'Расширение ImageMagick или GD не установлено',
'Installed!' => 'Установлен!',
'Mcrypt extension' => 'Расширение Mcrypt',
'Memcache extension' => 'Расширение Memcache',
'Module "{module}" depends on the module "{dep}", which is not activated.' => 'Модуль "{module}" зависит от модуля "{dep}" который не был активирован.',
'Modules folder' => 'Каталог Modules',
'ModulesBack folder' => 'Каталог ModulesBack',
'Multibyte String Functions' => 'Функции для работы с мультибайтовыми строками',
'Need PHP version 5.4 and above.' => 'Необходима весрия PHP 5.4 и выше',
'PCRE extension' => 'Расширение PCRE',
'PDO MSSQL extension (<a href="http://sqlsrvphp.codeplex.com/">pdo_sqlsrv</a>)' => 'Расширение PDO MSSQL(<a href="http://sqlsrvphp.codeplex.com/">pdo_sqlsrv</a>)',
'PDO MSSQL extension (pdo_dblib)' => 'Расширение PDO MSSQL(pdo_dblib)',
'PDO MSSQL extension (pdo_mssql)' => 'Расширение PDO MSSQL(pdo_mssql)',
'PDO MySQL extension' => 'Расширение PDO MySQL',
'PDO Oracle extension' => 'Расширение PDO Oracle',
'PDO extension' => 'Расширение PDO',
'Reflection extension' => 'Расширение Reflection',
'Required for MySQL DB.' => 'Необходимо для работы с MySQL',
'Required for Oracle DB.' => 'Необходимо для работы с Oracle',
'Required for encryption and decryption methods.' => 'Необходимо для поддержки криптографических функций',
'Required to work with MSSQL database on MS Windows.' => 'Необходимо для работы с MSSQL на платформе MS Windows',
'Required to work with MSSQL database using Microsoft\'s driver' => 'Необходимо для работы с MSSQL при использовании драйвера Microsoft',
'Required to work with MSSQL database when work from GNU/Linux or Unix' => 'Необходимо для работы с MSSQL на платформе GNU/Linux или Unix',
'Runtime folder' => 'Каталог Runtime',
'SOAP extension' => 'Расширение SOAP',
'SPL extension' => 'Расширение SPL',
'Security and Safe Mode' => 'Безопасность и безопасный режим',
'Site settings saved successfully!' => 'Настройки сайта успешно сохранены!',
'The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code. {b}Optional{/b}.' => 'APC - свободный opcode кешер для PHP. Необходим для кеширования и оптимизации выполнения PHP кода {b}Не обязателен{/b}',
'The administrator has successfully created!' => 'Администратор успешно создан!',
'The module {name} is disabled!' => 'Модуль {name} отключен!',
'The module {name} not found!' => 'Модуль с именем {name} не найден!',
'The variable $_SERVER' => 'Перменная $_SERVER',
'The variable $_SERVER does not contain {vars}.' => 'Переменная $_SERVER не содержит {vars}.',
'There should be at least one server variables: {vars}.' => 'Необходимо установить как минимум одну переменную сервера из данного списка: {vars}.',
'There was an error writing to file \'{file}\'!' => 'Произошла ошибка при попытке записи в файл \'{file}\'!',
'To use memcached, set the value of the property {useMemcachedLink} equal {code_true}.' => 'Для использования memcached установите значение свойства {useMemcachedLink} равным {code_true}.',
'Updating module\'s tables to current state!' => 'Обновление таблиц модулей до актуального состояния',
'Uploads folder' => 'Каталог загрузок',
'You need to set write permissions for the directory {folder}' => 'Необходимо установить права на запись для дитектории {folder}',
'You need to set write permissions for the directory {folder}assets' => 'Необходимо установить права на запись для дитектории {folder}assets',
'You should copy {from file} to {to file} and give it permission to write' => 'Необходимо скопировать {from file} в {to file} и дать доступ для записи',
'You should disable the directive safe_mode.' => 'Необходимо отключить директиву safe_mode',
'http://yupe.ru' => 'http://yupe.ru',
'installation of Yupe!' => 'установка Yupe!',
'mbstring extension' => 'расширение mbstring',
'team@yupe.ru' => 'team@yupe.ru',
'yupe team' => 'yupe team',
'Author:' => 'Автор:',
'You can create DB with phpmyadmin help, or with some other sql tools.' => 'Базу данных можно создать при помощи phpmyadmin или любого другого инструмента.',
'Will be installed <small class="label label-info checked-count">0</small> modules. Do you want to continue?' => 'Будет установлено <small class="label label-info checked-count">0</small> модулей. Продолжить?',
'Your site is ready to work!' => 'Ваш сайт готов к работе!',
'Version' => 'Версия',
'There is an error occured when installing modules. You can watch errors in backlog journal.' => 'Во время установки выбранных Вами модулей произошла ошибка. Вы можете ознакомиться с журналом.',
'All' => 'Все',
'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-classes</a>' => 'Все <a href="http://www.yiiframework.com/doc/api/#system.db">DB-классы</a>',
'All modules' => 'Все модули',
'Install can\'t be continued. Please check errors!' => 'Дальнейшая установка невозможна, пожалуйста, исправьте ошибки!',
'To continue installation you need to repair error was occured.' => 'Для продолжения установки необходимо исправить все возникшие проблемы.',
'Welcome!' => 'Добро пожаловать!',
'DNS and IP for DB access' => 'Домен и ip-адрес используемый для доступа к БД',
'Addition modules you can install/activate from control panel.' => 'Дополнительные модули можно будет установить/активировать через панель управления.',
'Summary modules: {all}, checked for install: {checked}' => 'Доступно модулей: {all}, выбрано для установки: {checked}',
'You can donate us some money if you like our project.' => 'Если Вам не жалко - отправьте нам чуть-чуть денежек, мы будем довольны =) !',
'Backlog journal' => 'Журнал установки',
'Dependencies' => 'Зависимости',
'Dependent' => 'Зависимые',
'Depends from' => 'Зависит от',
'Memorize please. Data form this section will need you for Control Panel access' => 'Запомните, указанные на данном этапе данные, они Вам потребуются для доступа к панели управления.',
'Value' => 'Значение',
'Installation in progress...' => 'Идет установка модулей...',
'DB name on DBMS server' => 'Имя БД на сервере СУБД',
'User name' => 'Имя пользователя',
'Using in site title' => 'Используется в заголовке сайта.',
'Using in description meta-tag' => 'Используется в поле description meta-тега.',
'Using in keywords meta-tag' => 'Используется в поле keywords meta-тега.',
'Using for administration delivery' => 'Используется для административной рассылки.',
'Sources on GitHub' => 'Исходный код на Github',
'Site keywords' => 'Ключевые слова сайта',
'Comments' => 'Комментарий',
'Admin login' => 'Логин администратора сайта.',
'Multibyte strings' => 'Многобайтные строки',
'Module for system installation' => 'Модуль для установки системы',
'Multilanguage module' => 'Модуль мультиязычный',
'System module. (Can\'t disable)' => 'Модуль не отключаемый',
'We working with it' => 'Мы активно ее пишем =)',
'We always happy to see you on our site {link}. We also have {twitter} and {forum}!' => 'Мы всегда рады видеть Вас на нашем сайте {link}, а еще у нас есть {twitter} и {forum} !',
'On this step Yupe trying to install modules you checked. This process can take several minutes...' => 'На данном этапе Юпи! постарается установить выбранные вами модули. Установка может занять некоторое время...',
'Yupe checks PHP version and needed extensions on this step.' => 'На данном этапе Юпи! проверяет версию PHP и наличие всех необходимых модулей.',
'On this step Yupe checks access right for needed directories.' => 'На данном этапе Юпи! проверяет права доступа для всех необходимых каталогов.',
'Name' => 'Название',
'DB name' => 'Название базы данных',
'Site title' => 'Название сайта',
'Start installation >' => 'Начать установку >',
'Refresh' => 'Обновить',
'Description' => 'Описание',
'Site description' => 'Описание сайта',
'Describe appearance of your Site' => 'Определяет внешний вид Вашего сайта.',
'Describe appearance of your Control Panel' => 'Определяет внешний вид панели управления.',
'Disable depends modules,<br/>which you would not like to install.' => 'Отключите зависимые,<br/>чтобы не устанавливать',
'Cancel' => 'Отмена',
'Official docs' => 'Официальная документация Юпи!',
'Official Yupe site' => 'Официальный сайт Юпи!',
'Official Yupe twitter' => 'Официальный твиттер Юпи!',
'Error' => 'Ошибка',
'Error!' => 'Ошибка!',
'GO TO CONTROL PANEL' => 'ПЕРЕЙТИ В ПАНЕЛЬ УПРАВЛЕНИЯ',
'GO TO SITE HOME PAGE' => 'ПЕРЕЙТИ НА САЙТ',
'Passwords are not consistent' => 'Пароли не совпадают!',
'Password' => 'Пароль',
'Admin password' => 'Пароль администратора сайта.',
'DB access password' => 'Пароль для доступа к указанной БД',
'Mail us to <b><a href="mailto:team@yupe.ru">team@yupe.ru</a></b>' => 'Пишите нам на <b><a href="mailto:team@yupe.ru">team@yupe.ru</a></b>',
'Password confirm' => 'Подтверждение пароля',
'Admin password confirm' => 'Подтверждение пароля администратора сайта.',
'Please check modules you want to be installed.' => 'Пожалуйста, выберите модули, которые хотите установить.',
'Please select hard password with digits, alphas and special symbols.' => 'Пожалуйста, указывайте сложный пароль, содержащий как цифры и буквы, так и специальные символы.',
'Congratulations Yupe was installed successfully!' => 'Поздравляем, установка "Юпи!" завершена!',
'Congratulations, modules which you checked installed successfully!' => 'Поздравляем, установка выбранных вами модулей завершена.<br/>Вы можете ознакомиться с журналом или продолжить установку.',
'Interesting links:' => 'Полезные ссылки:',
'User' => 'Пользователь',
'User for access to selected DB' => 'Пользователь для доступа к указанной БД',
'Port' => 'Порт',
'DBMS server port' => 'Порт СУБД сервера',
'Warning' => 'Предупреждение',
'Table prefix, "yupe_" by defaults' => 'Префикс добавляется в начале имени каждой таблицы, по умолчанию "yupe_"',
'Tables prefix' => 'Префикс таблиц',
'If you have problems with installation, please check {link} or {feedback}' => 'При возникновении проблем с установкой, пожалуйста, посетите {link} или {feedback} !',
'If you have a problem with install, please go to {link}' => 'При возникновении проблем с установкой, пожалуйста, посетите вот {link}!',
'Check connection and continue >' => 'Проверить подключение и продолжить >',
'Continue >' => 'Продолжить >',
'Path to mysql' => 'Путь к mysql',
'РНР version' => 'Версия РНР',
'Result' => 'Результат',
'Recommended' => 'Рекомендованные',
'Module site:' => 'Сайт модуля:',
'Please follow installation instructions.' => 'Следуйте инструкциям установщика и все у Вас получится!',
'Look journal' => 'Смотреть журнал',
'Create admin account' => 'Создайте учетную запись администратора сайта.',
'Create DB on DBMS server' => 'Создать БД на сервере СУБД',
'Create DB' => 'Создать базу данных',
'Unix socket (if it need)' => 'Сокет (если необходимо)',
'Default backend (Admin CP) theme' => 'Тема оформления панели управления',
'Default frontend theme' => 'Тема оформления публичной части',
'DBMS type (Experimental)' => 'Тип сервера БД (экспериментальная возможность)',
'DBMS type' => 'Тип сервера базы данных',
'Only basic modules' => 'Только основные',
'You have "Insatll" module active! After install it need to be disabled!' => 'У Вас активирован модуль "Установщик", после установки системы его необходимо отключить!',
'More about SEO {link}' => 'Узнать больше о SEO-оптимизации можно {link}.',
'Select your site title, description and keywords for SEO.' => 'Укажите название Вашего сайта, его описание и ключевые слова, необходимые для SEO-оптимизации.',
'Select DB connection settings' => 'Укажите параметры соединения с базой данных.',
'Installing module' => 'Устанавливаем модуль',
'Install' => 'Установка',
'Installation completed' => 'Установка завершена',
'Module was installed' => 'Установлен модуль',
'Installer' => 'Установщик',
'File {file} not exists or not accessible for write!' => 'Файл {file} не существует или не доступен для записи!',
'Support Yupe forum' => 'Форум поддержки Юпи!',
'Host' => 'Хост',
'our forum' => 'наш форум',
'contact us' => 'напишите нам',
'Step 1 of 8: Welcome!' => 'Шаг 1 из 8 : "Приветствие!"',
'Step 2 of 8: Environment check!' => 'Шаг 2 из 8 : "Проверка окружения!"',
'Step 3 of 8: System requirements' => 'Шаг 3 из 8 : "Проверка системных требований"',
'Step 4 of 8: DB settings' => 'Шаг 4 из 8 : "Соединение с базой данных"',
'Step 5 of 8: Installing modules' => 'Шаг 5 из 8 : "Установка модулей"',
'Step 6 of 8: Creating administrator' => 'Шаг 6 из 8 : "Создание учетной записи администратора"',
'Step 7 of 8: Project settings' => 'Шаг 7 из 8 : "Настройки проекта"',
'Step 8 of 8: Finish' => 'Шаг 8 из 8 : "Окончание установки"',
'Yupe!' => 'Юпи!',
'Yupe!, yupe, cms, yii' => 'Юпи!, yupe, цмс, yii',
'Yupe! - the fastest way to create a site build on top of Yiiframework!' => 'Юпи! - самый простой способ создать сайт на Yii!',
'Yupe try to create DB if it doesn\'t exists.' => 'Юпи! попытается сам создать базу данных если вы поставите галочку "Создать базу данных"',
'here' => 'вот здесь',
'go frequently' => 'заходите чаще =)',
'or' => 'или',
'interesing thoughts and ideas' => 'интересные мысли и идеи',
'Follow us' => 'обязательно заффоловьте нас, мы не спамим',
'We always open for commercial and other propositions' => 'принимаем всякого рода коммерческие и любые предложения',
'Send pull request' => 'пришлите нам парочку пулл-реквестов, все только выиграют',
'Zend OPcache required to optimize and speed up your project.' => 'Zend OPcache необходим для оптимизации и ускорения работы вашего проекта',
'General sponsor' => 'Генеральный спонсор',
'All discussions here' => '',
'Just good guys' => 'Просто отличные парни',
'Please, select your language below for continue.' => 'Пожалуйста, выберите язык ниже для продолжения.',
'This option is experiment. Only MySQL works stable.' => 'Это экспериментальная возможность. На данный момент гарантирована поддержка MySQL.',
);
| otis22/yupe-test | protected/modules/install/messages/ru/install.php | PHP | bsd-3-clause | 23,446 |
# Support
## Timer
A timer class that can be called static or dynamically.
Source code: [support/blob/master/src/Timer.php](https://github.com/antonioribeiro/support/blob/master/src/Timer.php)
### Methods
Those are the methods:
Timer::start();
Timer::stop();
Timer::isStarted();
Timer::isStopped();
Timer::elapsed(); // returns a formatted value 9.0192
Timer::elapsedRaw(); // returns a double 9.019223049023
Timer::setFormat(default = '%.4f');
You can name your timers and have more than one running:
Timer::start('mary');
Timer::stop('mary');
Timer::elapsed('mary');
### Examples
Timer::start();
Timer::start('2nd timer');
var_dump("started: " . (Timer::isStarted() ? 'yes' : 'no'));
var_dump("stopped: " . (Timer::isStopped() ? 'yes' : 'no'));
sleep(5);
Timer::stop();
var_dump("started: " . (Timer::isStarted() ? 'yes' : 'no'));
var_dump("stopped: " . (Timer::isStopped() ? 'yes' : 'no'));
var_dump("elapsed: " . Timer::elapsed());
var_dump("raw: " . Timer::elapsedRaw());
sleep(2);
var_dump("'2nd timer' started: " . (Timer::isStarted('2nd timer') ? 'yes' : 'no'));
var_dump("'2nd timer' stopped: " . (Timer::isStopped('2nd timer') ? 'yes' : 'no'));
var_dump("'2nd timer' elapsed: " . Timer::elapsed('2nd timer'));
var_dump("'2nd timer' raw: " . Timer::elapsedRaw('2nd timer'));
sleep(2);
Timer::stop('2nd timer');
var_dump("'2nd timer' started: " . (Timer::isStarted('2nd timer') ? 'yes' : 'no'));
var_dump("'2nd timer' stopped: " . (Timer::isStopped('2nd timer') ? 'yes' : 'no'));
var_dump("'2nd timer' elapsed: " . Timer::elapsed('2nd timer'));
var_dump("'2nd timer' raw: " . Timer::elapsedRaw('2nd timer'));
Timer::setFormat('%.8f');
var_dump("'2nd timer' elapsed 8 decimals: " . Timer::elapsed('2nd timer'));
/// And you can instantiate it and do it all over again:
$t = new Timer;
$t->start();
sleep(3);
$t->stop();
var_dump("elapsed dynamic: " . $t->elapsed());
This should give you this result:
string(12) "started: yes"
string(11) "stopped: no"
string(11) "started: no"
string(12) "stopped: yes"
string(15) "elapsed: 5.0004"
string(20) "raw: 5.0005040168762"
string(24) "'2nd timer' started: yes"
string(23) "'2nd timer' stopped: no"
string(27) "'2nd timer' elapsed: 7.0008"
string(32) "'2nd timer' raw: 7.0008120536804"
string(23) "'2nd timer' started: no"
string(24) "'2nd timer' stopped: yes"
string(27) "'2nd timer' elapsed: 9.0011"
string(32) "'2nd timer' raw: 9.0010931491852"
string(42) "'2nd timer' elapsed 8 decimals: 9.00113106"
string(27) "elapsed dynamic: 3.00018883"
| younes0/support | readme.md | Markdown | bsd-3-clause | 2,660 |
//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/CodeGen/CodeGenAction.h"
#include "CodeGenModule.h"
#include "CoverageMappingGen.h"
#include "MacroPPCallbacks.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/BackendUtil.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Pass.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Transforms/IPO/Internalize.h"
#include <memory>
using namespace clang;
using namespace llvm;
namespace clang {
class BackendConsumer;
class ClangDiagnosticHandler final : public DiagnosticHandler {
public:
ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
: CodeGenOpts(CGOpts), BackendCon(BCon) {}
bool handleDiagnostics(const DiagnosticInfo &DI) override;
bool isAnalysisRemarkEnabled(StringRef PassName) const override {
return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
}
bool isMissedOptRemarkEnabled(StringRef PassName) const override {
return (CodeGenOpts.OptimizationRemarkMissedPattern &&
CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
}
bool isPassedOptRemarkEnabled(StringRef PassName) const override {
return (CodeGenOpts.OptimizationRemarkPattern &&
CodeGenOpts.OptimizationRemarkPattern->match(PassName));
}
bool isAnyRemarkEnabled() const override {
return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
CodeGenOpts.OptimizationRemarkMissedPattern ||
CodeGenOpts.OptimizationRemarkPattern);
}
private:
const CodeGenOptions &CodeGenOpts;
BackendConsumer *BackendCon;
};
class BackendConsumer : public ASTConsumer {
using LinkModule = CodeGenAction::LinkModule;
virtual void anchor();
DiagnosticsEngine &Diags;
BackendAction Action;
const HeaderSearchOptions &HeaderSearchOpts;
const CodeGenOptions &CodeGenOpts;
const TargetOptions &TargetOpts;
const LangOptions &LangOpts;
std::unique_ptr<raw_pwrite_stream> AsmOutStream;
ASTContext *Context;
Timer LLVMIRGeneration;
unsigned LLVMIRGenerationRefCount;
/// True if we've finished generating IR. This prevents us from generating
/// additional LLVM IR after emitting output in HandleTranslationUnit. This
/// can happen when Clang plugins trigger additional AST deserialization.
bool IRGenFinished = false;
std::unique_ptr<CodeGenerator> Gen;
SmallVector<LinkModule, 4> LinkModules;
// This is here so that the diagnostic printer knows the module a diagnostic
// refers to.
llvm::Module *CurLinkModule = nullptr;
public:
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
const HeaderSearchOptions &HeaderSearchOpts,
const PreprocessorOptions &PPOpts,
const CodeGenOptions &CodeGenOpts,
const TargetOptions &TargetOpts,
const LangOptions &LangOpts, bool TimePasses,
const std::string &InFile,
SmallVector<LinkModule, 4> LinkModules,
std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
CoverageSourceInfo *CoverageInfo = nullptr)
: Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
AsmOutStream(std::move(OS)), Context(nullptr),
LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
LLVMIRGenerationRefCount(0),
Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
CodeGenOpts, C, CoverageInfo)),
LinkModules(std::move(LinkModules)) {
FrontendTimesIsEnabled = TimePasses;
llvm::TimePassesIsEnabled = TimePasses;
}
llvm::Module *getModule() const { return Gen->GetModule(); }
std::unique_ptr<llvm::Module> takeModule() {
return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
}
CodeGenerator *getCodeGenerator() { return Gen.get(); }
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Gen->HandleCXXStaticMemberVarInstantiation(VD);
}
void Initialize(ASTContext &Ctx) override {
assert(!Context && "initialized multiple times");
Context = &Ctx;
if (FrontendTimesIsEnabled)
LLVMIRGeneration.startTimer();
Gen->Initialize(Ctx);
if (FrontendTimesIsEnabled)
LLVMIRGeneration.stopTimer();
}
bool HandleTopLevelDecl(DeclGroupRef D) override {
PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Context->getSourceManager(),
"LLVM IR generation of declaration");
// Recurse.
if (FrontendTimesIsEnabled) {
LLVMIRGenerationRefCount += 1;
if (LLVMIRGenerationRefCount == 1)
LLVMIRGeneration.startTimer();
}
Gen->HandleTopLevelDecl(D);
if (FrontendTimesIsEnabled) {
LLVMIRGenerationRefCount -= 1;
if (LLVMIRGenerationRefCount == 0)
LLVMIRGeneration.stopTimer();
}
return true;
}
void HandleInlineFunctionDefinition(FunctionDecl *D) override {
PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
Context->getSourceManager(),
"LLVM IR generation of inline function");
if (FrontendTimesIsEnabled)
LLVMIRGeneration.startTimer();
Gen->HandleInlineFunctionDefinition(D);
if (FrontendTimesIsEnabled)
LLVMIRGeneration.stopTimer();
}
void HandleInterestingDecl(DeclGroupRef D) override {
// Ignore interesting decls from the AST reader after IRGen is finished.
if (!IRGenFinished)
HandleTopLevelDecl(D);
}
// Links each entry in LinkModules into our module. Returns true on error.
bool LinkInModules() {
for (auto &LM : LinkModules) {
if (LM.PropagateAttrs)
for (Function &F : *LM.Module)
Gen->CGM().AddDefaultFnAttrs(F);
CurLinkModule = LM.Module.get();
bool Err;
if (LM.Internalize) {
Err = Linker::linkModules(
*getModule(), std::move(LM.Module), LM.LinkFlags,
[](llvm::Module &M, const llvm::StringSet<> &GVS) {
internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
return !GV.hasName() || (GVS.count(GV.getName()) == 0);
});
});
} else {
Err = Linker::linkModules(*getModule(), std::move(LM.Module),
LM.LinkFlags);
}
if (Err)
return true;
}
return false; // success
}
void HandleTranslationUnit(ASTContext &C) override {
{
PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
if (FrontendTimesIsEnabled) {
LLVMIRGenerationRefCount += 1;
if (LLVMIRGenerationRefCount == 1)
LLVMIRGeneration.startTimer();
}
Gen->HandleTranslationUnit(C);
if (FrontendTimesIsEnabled) {
LLVMIRGenerationRefCount -= 1;
if (LLVMIRGenerationRefCount == 0)
LLVMIRGeneration.stopTimer();
}
IRGenFinished = true;
}
// Silently ignore if we weren't initialized for some reason.
if (!getModule())
return;
// Install an inline asm handler so that diagnostics get printed through
// our diagnostics hooks.
LLVMContext &Ctx = getModule()->getContext();
LLVMContext::InlineAsmDiagHandlerTy OldHandler =
Ctx.getInlineAsmDiagnosticHandler();
void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
Ctx.getDiagnosticHandler();
Ctx.setDiagnosticHandler(llvm::make_unique<ClangDiagnosticHandler>(
CodeGenOpts, this));
Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
if (CodeGenOpts.DiagnosticsHotnessThreshold != 0)
Ctx.setDiagnosticsHotnessThreshold(
CodeGenOpts.DiagnosticsHotnessThreshold);
std::unique_ptr<llvm::ToolOutputFile> OptRecordFile;
if (!CodeGenOpts.OptRecordFile.empty()) {
std::error_code EC;
OptRecordFile = llvm::make_unique<llvm::ToolOutputFile>(
CodeGenOpts.OptRecordFile, EC, sys::fs::F_None);
if (EC) {
Diags.Report(diag::err_cannot_open_file) <<
CodeGenOpts.OptRecordFile << EC.message();
return;
}
Ctx.setDiagnosticsOutputFile(
llvm::make_unique<yaml::Output>(OptRecordFile->os()));
if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
Ctx.setDiagnosticsHotnessRequested(true);
}
// Link each LinkModule into our module.
if (LinkInModules())
return;
EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
LangOpts, C.getTargetInfo().getDataLayout(),
getModule(), Action, std::move(AsmOutStream));
Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
if (OptRecordFile)
OptRecordFile->keep();
}
void HandleTagDeclDefinition(TagDecl *D) override {
PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
Context->getSourceManager(),
"LLVM IR generation of declaration");
Gen->HandleTagDeclDefinition(D);
}
void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
Gen->HandleTagDeclRequiredDefinition(D);
}
void CompleteTentativeDefinition(VarDecl *D) override {
Gen->CompleteTentativeDefinition(D);
}
void AssignInheritanceModel(CXXRecordDecl *RD) override {
Gen->AssignInheritanceModel(RD);
}
void HandleVTable(CXXRecordDecl *RD) override {
Gen->HandleVTable(RD);
}
static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
unsigned LocCookie) {
SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
}
/// Get the best possible source location to represent a diagnostic that
/// may have associated debug info.
const FullSourceLoc
getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo, StringRef &Filename,
unsigned &Line, unsigned &Column) const;
void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
SourceLocation LocCookie);
void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
/// Specialized handler for InlineAsm diagnostic.
/// \return True if the diagnostic has been successfully reported, false
/// otherwise.
bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
/// Specialized handler for StackSize diagnostic.
/// \return True if the diagnostic has been successfully reported, false
/// otherwise.
bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
/// Specialized handler for unsupported backend feature diagnostic.
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
/// Specialized handlers for optimization remarks.
/// Note that these handlers only accept remarks and they always handle
/// them.
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID);
void
OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
void OptimizationRemarkHandler(
const llvm::OptimizationRemarkAnalysisFPCommute &D);
void OptimizationRemarkHandler(
const llvm::OptimizationRemarkAnalysisAliasing &D);
void OptimizationFailureHandler(
const llvm::DiagnosticInfoOptimizationFailure &D);
};
void BackendConsumer::anchor() {}
}
bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
BackendCon->DiagnosticHandlerImpl(DI);
return true;
}
/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
/// buffer to be a valid FullSourceLoc.
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
SourceManager &CSM) {
// Get both the clang and llvm source managers. The location is relative to
// a memory buffer that the LLVM Source Manager is handling, we need to add
// a copy to the Clang source manager.
const llvm::SourceMgr &LSM = *D.getSourceMgr();
// We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
// already owns its one and clang::SourceManager wants to own its one.
const MemoryBuffer *LBuf =
LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
// Create the copy and transfer ownership to clang::SourceManager.
// TODO: Avoid copying files into memory.
std::unique_ptr<llvm::MemoryBuffer> CBuf =
llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
LBuf->getBufferIdentifier());
// FIXME: Keep a file ID map instead of creating new IDs for each location.
FileID FID = CSM.createFileID(std::move(CBuf));
// Translate the offset into the file.
unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
SourceLocation NewLoc =
CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
return FullSourceLoc(NewLoc, CSM);
}
/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
/// error parsing inline asm. The SMDiagnostic indicates the error relative to
/// the temporary memory buffer that the inline asm parser has set up.
void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
SourceLocation LocCookie) {
// There are a couple of different kinds of errors we could get here. First,
// we re-format the SMDiagnostic in terms of a clang diagnostic.
// Strip "error: " off the start of the message string.
StringRef Message = D.getMessage();
if (Message.startswith("error: "))
Message = Message.substr(7);
// If the SMDiagnostic has an inline asm source location, translate it.
FullSourceLoc Loc;
if (D.getLoc() != SMLoc())
Loc = ConvertBackendLocation(D, Context->getSourceManager());
unsigned DiagID;
switch (D.getKind()) {
case llvm::SourceMgr::DK_Error:
DiagID = diag::err_fe_inline_asm;
break;
case llvm::SourceMgr::DK_Warning:
DiagID = diag::warn_fe_inline_asm;
break;
case llvm::SourceMgr::DK_Note:
DiagID = diag::note_fe_inline_asm;
break;
case llvm::SourceMgr::DK_Remark:
llvm_unreachable("remarks unexpected");
}
// If this problem has clang-level source location information, report the
// issue in the source with a note showing the instantiated
// code.
if (LocCookie.isValid()) {
Diags.Report(LocCookie, DiagID).AddString(Message);
if (D.getLoc().isValid()) {
DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
// Convert the SMDiagnostic ranges into SourceRange and attach them
// to the diagnostic.
for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
unsigned Column = D.getColumnNo();
B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
Loc.getLocWithOffset(Range.second - Column));
}
}
return;
}
// Otherwise, report the backend issue as occurring in the generated .s file.
// If Loc is invalid, we still need to report the issue, it just gets no
// location info.
Diags.Report(Loc, DiagID).AddString(Message);
}
#define ComputeDiagID(Severity, GroupName, DiagID) \
do { \
switch (Severity) { \
case llvm::DS_Error: \
DiagID = diag::err_fe_##GroupName; \
break; \
case llvm::DS_Warning: \
DiagID = diag::warn_fe_##GroupName; \
break; \
case llvm::DS_Remark: \
llvm_unreachable("'remark' severity not expected"); \
break; \
case llvm::DS_Note: \
DiagID = diag::note_fe_##GroupName; \
break; \
} \
} while (false)
#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
do { \
switch (Severity) { \
case llvm::DS_Error: \
DiagID = diag::err_fe_##GroupName; \
break; \
case llvm::DS_Warning: \
DiagID = diag::warn_fe_##GroupName; \
break; \
case llvm::DS_Remark: \
DiagID = diag::remark_fe_##GroupName; \
break; \
case llvm::DS_Note: \
DiagID = diag::note_fe_##GroupName; \
break; \
} \
} while (false)
bool
BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
unsigned DiagID;
ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
std::string Message = D.getMsgStr().str();
// If this problem has clang-level source location information, report the
// issue as being a problem in the source with a note showing the instantiated
// code.
SourceLocation LocCookie =
SourceLocation::getFromRawEncoding(D.getLocCookie());
if (LocCookie.isValid())
Diags.Report(LocCookie, DiagID).AddString(Message);
else {
// Otherwise, report the backend diagnostic as occurring in the generated
// .s file.
// If Loc is invalid, we still need to report the diagnostic, it just gets
// no location info.
FullSourceLoc Loc;
Diags.Report(Loc, DiagID).AddString(Message);
}
// We handled all the possible severities.
return true;
}
bool
BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
if (D.getSeverity() != llvm::DS_Warning)
// For now, the only support we have for StackSize diagnostic is warning.
// We do not know how to format other severities.
return false;
if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
// FIXME: Shouldn't need to truncate to uint32_t
Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
diag::warn_fe_frame_larger_than)
<< static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
return true;
}
return false;
}
const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
StringRef &Filename, unsigned &Line, unsigned &Column) const {
SourceManager &SourceMgr = Context->getSourceManager();
FileManager &FileMgr = SourceMgr.getFileManager();
SourceLocation DILoc;
if (D.isLocationAvailable()) {
D.getLocation(&Filename, &Line, &Column);
const FileEntry *FE = FileMgr.getFile(Filename);
if (FE && Line > 0) {
// If -gcolumn-info was not used, Column will be 0. This upsets the
// source manager, so pass 1 if Column is not set.
DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
}
BadDebugInfo = DILoc.isInvalid();
}
// If a location isn't available, try to approximate it using the associated
// function definition. We use the definition's right brace to differentiate
// from diagnostics that genuinely relate to the function itself.
FullSourceLoc Loc(DILoc, SourceMgr);
if (Loc.isInvalid())
if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Loc = FD->getASTContext().getFullLoc(FD->getLocation());
if (DILoc.isInvalid() && D.isLocationAvailable())
// If we were not able to translate the file:line:col information
// back to a SourceLocation, at least emit a note stating that
// we could not translate this location. This can happen in the
// case of #line directives.
Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
<< Filename << Line << Column;
return Loc;
}
void BackendConsumer::UnsupportedDiagHandler(
const llvm::DiagnosticInfoUnsupported &D) {
// We only support errors.
assert(D.getSeverity() == llvm::DS_Error);
StringRef Filename;
unsigned Line, Column;
bool BadDebugInfo = false;
FullSourceLoc Loc =
getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
if (BadDebugInfo)
// If we were not able to translate the file:line:col information
// back to a SourceLocation, at least emit a note stating that
// we could not translate this location. This can happen in the
// case of #line directives.
Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
<< Filename << Line << Column;
}
void BackendConsumer::EmitOptimizationMessage(
const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
// We only support warnings and remarks.
assert(D.getSeverity() == llvm::DS_Remark ||
D.getSeverity() == llvm::DS_Warning);
StringRef Filename;
unsigned Line, Column;
bool BadDebugInfo = false;
FullSourceLoc Loc =
getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
std::string Msg;
raw_string_ostream MsgStream(Msg);
MsgStream << D.getMsg();
if (D.getHotness())
MsgStream << " (hotness: " << *D.getHotness() << ")";
Diags.Report(Loc, DiagID)
<< AddFlagValue(D.getPassName())
<< MsgStream.str();
if (BadDebugInfo)
// If we were not able to translate the file:line:col information
// back to a SourceLocation, at least emit a note stating that
// we could not translate this location. This can happen in the
// case of #line directives.
Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
<< Filename << Line << Column;
}
void BackendConsumer::OptimizationRemarkHandler(
const llvm::DiagnosticInfoOptimizationBase &D) {
// Without hotness information, don't show noisy remarks.
if (D.isVerbose() && !D.getHotness())
return;
if (D.isPassed()) {
// Optimization remarks are active only if the -Rpass flag has a regular
// expression that matches the name of the pass name in \p D.
if (CodeGenOpts.OptimizationRemarkPattern &&
CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
} else if (D.isMissed()) {
// Missed optimization remarks are active only if the -Rpass-missed
// flag has a regular expression that matches the name of the pass
// name in \p D.
if (CodeGenOpts.OptimizationRemarkMissedPattern &&
CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
EmitOptimizationMessage(
D, diag::remark_fe_backend_optimization_remark_missed);
} else {
assert(D.isAnalysis() && "Unknown remark type");
bool ShouldAlwaysPrint = false;
if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
if (ShouldAlwaysPrint ||
(CodeGenOpts.OptimizationRemarkAnalysisPattern &&
CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
EmitOptimizationMessage(
D, diag::remark_fe_backend_optimization_remark_analysis);
}
}
void BackendConsumer::OptimizationRemarkHandler(
const llvm::OptimizationRemarkAnalysisFPCommute &D) {
// Optimization analysis remarks are active if the pass name is set to
// llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
// regular expression that matches the name of the pass name in \p D.
if (D.shouldAlwaysPrint() ||
(CodeGenOpts.OptimizationRemarkAnalysisPattern &&
CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
EmitOptimizationMessage(
D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
}
void BackendConsumer::OptimizationRemarkHandler(
const llvm::OptimizationRemarkAnalysisAliasing &D) {
// Optimization analysis remarks are active if the pass name is set to
// llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
// regular expression that matches the name of the pass name in \p D.
if (D.shouldAlwaysPrint() ||
(CodeGenOpts.OptimizationRemarkAnalysisPattern &&
CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
EmitOptimizationMessage(
D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
}
void BackendConsumer::OptimizationFailureHandler(
const llvm::DiagnosticInfoOptimizationFailure &D) {
EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
}
/// This function is invoked when the backend needs
/// to report something to the user.
void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
unsigned DiagID = diag::err_fe_inline_asm;
llvm::DiagnosticSeverity Severity = DI.getSeverity();
// Get the diagnostic ID based.
switch (DI.getKind()) {
case llvm::DK_InlineAsm:
if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
return;
ComputeDiagID(Severity, inline_asm, DiagID);
break;
case llvm::DK_StackSize:
if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
return;
ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
break;
case DK_Linker:
assert(CurLinkModule);
// FIXME: stop eating the warnings and notes.
if (Severity != DS_Error)
return;
DiagID = diag::err_fe_cannot_link_module;
break;
case llvm::DK_OptimizationRemark:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
return;
case llvm::DK_OptimizationRemarkMissed:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
return;
case llvm::DK_OptimizationRemarkAnalysis:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
return;
case llvm::DK_OptimizationRemarkAnalysisFPCommute:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
return;
case llvm::DK_OptimizationRemarkAnalysisAliasing:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
return;
case llvm::DK_MachineOptimizationRemark:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
return;
case llvm::DK_MachineOptimizationRemarkMissed:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
return;
case llvm::DK_MachineOptimizationRemarkAnalysis:
// Optimization remarks are always handled completely by this
// handler. There is no generic way of emitting them.
OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
return;
case llvm::DK_OptimizationFailure:
// Optimization failures are always handled completely by this
// handler.
OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
return;
case llvm::DK_Unsupported:
UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
return;
default:
// Plugin IDs are not bound to any value as they are set dynamically.
ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
break;
}
std::string MsgStorage;
{
raw_string_ostream Stream(MsgStorage);
DiagnosticPrinterRawOStream DP(Stream);
DI.print(DP);
}
if (DiagID == diag::err_fe_cannot_link_module) {
Diags.Report(diag::err_fe_cannot_link_module)
<< CurLinkModule->getModuleIdentifier() << MsgStorage;
return;
}
// Report the backend message using the usual diagnostic mechanism.
FullSourceLoc Loc;
Diags.Report(Loc, DiagID).AddString(MsgStorage);
}
#undef ComputeDiagID
CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
: Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
OwnsVMContext(!_VMContext) {}
CodeGenAction::~CodeGenAction() {
TheModule.reset();
if (OwnsVMContext)
delete VMContext;
}
bool CodeGenAction::hasIRSupport() const { return true; }
void CodeGenAction::EndSourceFileAction() {
// If the consumer creation failed, do nothing.
if (!getCompilerInstance().hasASTConsumer())
return;
// Steal the module from the consumer.
TheModule = BEConsumer->takeModule();
}
std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
return std::move(TheModule);
}
llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
OwnsVMContext = false;
return VMContext;
}
static std::unique_ptr<raw_pwrite_stream>
GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
switch (Action) {
case Backend_EmitAssembly:
return CI.createDefaultOutputFile(false, InFile, "s");
case Backend_EmitLL:
return CI.createDefaultOutputFile(false, InFile, "ll");
case Backend_EmitBC:
return CI.createDefaultOutputFile(true, InFile, "bc");
case Backend_EmitNothing:
return nullptr;
case Backend_EmitMCNull:
return CI.createNullOutputFile();
case Backend_EmitObj:
return CI.createDefaultOutputFile(true, InFile, "o");
}
llvm_unreachable("Invalid action!");
}
std::unique_ptr<ASTConsumer>
CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
BackendAction BA = static_cast<BackendAction>(Act);
std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
if (!OS)
OS = GetOutputStream(CI, InFile, BA);
if (BA != Backend_EmitNothing && !OS)
return nullptr;
// Load bitcode modules to link with, if we need to.
if (LinkModules.empty())
for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
if (!BCBuf) {
CI.getDiagnostics().Report(diag::err_cannot_open_file)
<< F.Filename << BCBuf.getError().message();
LinkModules.clear();
return nullptr;
}
Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
if (!ModuleOrErr) {
handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
CI.getDiagnostics().Report(diag::err_cannot_open_file)
<< F.Filename << EIB.message();
});
LinkModules.clear();
return nullptr;
}
LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
F.Internalize, F.LinkFlags});
}
CoverageSourceInfo *CoverageInfo = nullptr;
// Add the preprocessor callback only when the coverage mapping is generated.
if (CI.getCodeGenOpts().CoverageMapping) {
CoverageInfo = new CoverageSourceInfo;
CI.getPreprocessor().addPPCallbacks(
std::unique_ptr<PPCallbacks>(CoverageInfo));
}
std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
BEConsumer = Result.get();
// Enable generating macro debug info only when debug info is not disabled and
// also macro debug info is enabled.
if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
CI.getCodeGenOpts().MacroDebugInfo) {
std::unique_ptr<PPCallbacks> Callbacks =
llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
CI.getPreprocessor());
CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
}
return std::move(Result);
}
static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
void *Context,
unsigned LocCookie) {
SM.print(nullptr, llvm::errs());
auto Diags = static_cast<DiagnosticsEngine *>(Context);
unsigned DiagID;
switch (SM.getKind()) {
case llvm::SourceMgr::DK_Error:
DiagID = diag::err_fe_inline_asm;
break;
case llvm::SourceMgr::DK_Warning:
DiagID = diag::warn_fe_inline_asm;
break;
case llvm::SourceMgr::DK_Note:
DiagID = diag::note_fe_inline_asm;
break;
case llvm::SourceMgr::DK_Remark:
llvm_unreachable("remarks unexpected");
}
Diags->Report(DiagID).AddString("cannot compile inline asm");
}
std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
CompilerInstance &CI = getCompilerInstance();
SourceManager &SM = CI.getSourceManager();
// For ThinLTO backend invocations, ensure that the context
// merges types based on ODR identifiers. We also need to read
// the correct module out of a multi-module bitcode file.
if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
VMContext->enableDebugTypeODRUniquing();
auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
unsigned DiagID =
CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
CI.getDiagnostics().Report(DiagID) << EIB.message();
});
return {};
};
Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
if (!BMsOrErr)
return DiagErrors(BMsOrErr.takeError());
BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
// We have nothing to do if the file contains no ThinLTO module. This is
// possible if ThinLTO compilation was not able to split module. Content of
// the file was already processed by indexing and will be passed to the
// linker using merged object file.
if (!Bm) {
auto M = llvm::make_unique<llvm::Module>("empty", *VMContext);
M->setTargetTriple(CI.getTargetOpts().Triple);
return M;
}
Expected<std::unique_ptr<llvm::Module>> MOrErr =
Bm->parseModule(*VMContext);
if (!MOrErr)
return DiagErrors(MOrErr.takeError());
return std::move(*MOrErr);
}
llvm::SMDiagnostic Err;
if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
return M;
// Translate from the diagnostic info to the SourceManager location if
// available.
// TODO: Unify this with ConvertBackendLocation()
SourceLocation Loc;
if (Err.getLineNo() > 0) {
assert(Err.getColumnNo() >= 0);
Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
Err.getLineNo(), Err.getColumnNo() + 1);
}
// Strip off a leading diagnostic code if there is one.
StringRef Msg = Err.getMessage();
if (Msg.startswith("error: "))
Msg = Msg.substr(7);
unsigned DiagID =
CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
CI.getDiagnostics().Report(Loc, DiagID) << Msg;
return {};
}
void CodeGenAction::ExecuteAction() {
// If this is an IR file, we have to treat it specially.
if (getCurrentFileKind().getLanguage() == InputKind::LLVM_IR) {
BackendAction BA = static_cast<BackendAction>(Act);
CompilerInstance &CI = getCompilerInstance();
std::unique_ptr<raw_pwrite_stream> OS =
GetOutputStream(CI, getCurrentFile(), BA);
if (BA != Backend_EmitNothing && !OS)
return;
bool Invalid;
SourceManager &SM = CI.getSourceManager();
FileID FID = SM.getMainFileID();
llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
if (Invalid)
return;
TheModule = loadModule(*MainFile);
if (!TheModule)
return;
const TargetOptions &TargetOpts = CI.getTargetOpts();
if (TheModule->getTargetTriple() != TargetOpts.Triple) {
CI.getDiagnostics().Report(SourceLocation(),
diag::warn_fe_override_module)
<< TargetOpts.Triple;
TheModule->setTargetTriple(TargetOpts.Triple);
}
EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
MainFile->getMemBufferRef());
LLVMContext &Ctx = TheModule->getContext();
Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
&CI.getDiagnostics());
EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
CI.getTarget().getDataLayout(), TheModule.get(), BA,
std::move(OS));
return;
}
// Otherwise follow the normal AST path.
this->ASTFrontendAction::ExecuteAction();
}
//
void EmitAssemblyAction::anchor() { }
EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
: CodeGenAction(Backend_EmitAssembly, _VMContext) {}
void EmitBCAction::anchor() { }
EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
: CodeGenAction(Backend_EmitBC, _VMContext) {}
void EmitLLVMAction::anchor() { }
EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
: CodeGenAction(Backend_EmitLL, _VMContext) {}
void EmitLLVMOnlyAction::anchor() { }
EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
: CodeGenAction(Backend_EmitNothing, _VMContext) {}
void EmitCodeGenOnlyAction::anchor() { }
EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
: CodeGenAction(Backend_EmitMCNull, _VMContext) {}
void EmitObjAction::anchor() { }
EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
: CodeGenAction(Backend_EmitObj, _VMContext) {}
| youtube/cobalt | third_party/llvm-project/clang/lib/CodeGen/CodeGenAction.cpp | C++ | bsd-3-clause | 41,495 |
# frozen_string_literal: true
module Stupidedi
using Refinements
module Schema
#
# The 5010 X12 "data segment requirement designator"s include
# M - Mandatory
# O - Optional
#
# @see X222 B.1.3.12.6 Data Segment Requirement Designators
#
# The HIPAA implementation guides "industry usage" include
# SITUATIONAL
# REQUIRED
#
class SegmentReq
def initialize(required, forbidden, to_s)
@required, @forbidden, @to_s =
required, forbidden, to_s
end
def required?
@required
end
def forbidden?
@forbidden
end
def optional?
not (@required or @forbidden)
end
# @return [void]
def pretty_print(q)
q.text @to_s
end
# @return [String]
def inspect
@to_s
end
end
end
end
| kputnam/stupidedi | lib/stupidedi/schema/segment_req.rb | Ruby | bsd-3-clause | 871 |
// Copyright 2010-2021, 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.
#include "prediction/dictionary_predictor.h"
#include <algorithm>
#include <cctype>
#include <climits> // INT_MAX
#include <cmath>
#include <cstdint>
#include <list>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/japanese_util.h"
#include "base/logging.h"
#include "base/number_util.h"
#include "base/util.h"
#include "composer/composer.h"
#include "converter/connector.h"
#include "converter/converter_interface.h"
#include "converter/immutable_converter_interface.h"
#include "converter/node_list_builder.h"
#include "converter/segmenter.h"
#include "converter/segments.h"
#include "dictionary/dictionary_interface.h"
#include "dictionary/pos_matcher.h"
#include "prediction/predictor_interface.h"
#include "prediction/suggestion_filter.h"
#include "prediction/zero_query_dict.h"
#include "protocol/commands.pb.h"
#include "protocol/config.pb.h"
#include "request/conversion_request.h"
#include "usage_stats/usage_stats.h"
#include "absl/container/flat_hash_map.h"
#include "absl/flags/flag.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#ifndef NDEBUG
#define MOZC_DEBUG
#define MOZC_WORD_LOG_MESSAGE(message) \
absl::StrCat(__FILE__, ":", __LINE__, " ", message, "\n")
#define MOZC_WORD_LOG(result, message) \
(result).log.append(MOZC_WORD_LOG_MESSAGE(message))
#else // NDEBUG
#define MOZC_WORD_LOG(result, message) \
{}
#endif // NDEBUG
namespace mozc {
namespace {
using ::mozc::commands::Request;
using ::mozc::dictionary::DictionaryInterface;
using ::mozc::dictionary::PosMatcher;
using ::mozc::dictionary::Token;
using ::mozc::usage_stats::UsageStats;
// Used to emulate positive infinity for cost. This value is set for those
// candidates that are thought to be aggressive; thus we can eliminate such
// candidates from suggestion or prediction. Note that for this purpose we don't
// want to use INT_MAX because someone might further add penalty after cost is
// set to INT_MAX, which leads to overflow and consequently aggressive
// candidates would appear in the top results.
constexpr int kInfinity = (2 << 20);
// Note that PREDICTION mode is much slower than SUGGESTION.
// Number of prediction calls should be minimized.
constexpr size_t kSuggestionMaxResultsSize = 256;
constexpr size_t kPredictionMaxResultsSize = 100000;
bool IsEnableNewSpatialScoring(const ConversionRequest &request) {
return request.request()
.decoder_experiment_params()
.enable_new_spatial_scoring();
}
// Returns true if the |target| may be reduncant result.
bool MaybeRedundant(const std::string &reference, const std::string &target) {
return absl::StartsWith(target, reference);
}
bool IsLatinInputMode(const ConversionRequest &request) {
return (request.has_composer() &&
(request.composer().GetInputMode() == transliteration::HALF_ASCII ||
request.composer().GetInputMode() == transliteration::FULL_ASCII));
}
bool IsQwertyMobileTable(const ConversionRequest &request) {
const auto table = request.request().special_romanji_table();
return (table == commands::Request::QWERTY_MOBILE_TO_HIRAGANA ||
table == commands::Request::QWERTY_MOBILE_TO_HALFWIDTHASCII);
}
bool IsLanguageAwareInputEnabled(const ConversionRequest &request) {
const auto lang_aware = request.request().language_aware_input();
return lang_aware == commands::Request::LANGUAGE_AWARE_SUGGESTION;
}
// Returns true if |segments| contains number history.
// Normalized number will be set to |number_key|
// Note:
// Now this function supports arabic number candidates only and
// we don't support kanji number candidates for now.
// This is because We have several kanji number styles, for example,
// "一二", "十二", "壱拾弐", etc for 12.
// TODO(toshiyuki): Define the spec and support Kanji.
bool GetNumberHistory(const Segments &segments, std::string *number_key) {
DCHECK(number_key);
const size_t history_size = segments.history_segments_size();
if (history_size <= 0) {
return false;
}
const Segment &last_segment = segments.history_segment(history_size - 1);
DCHECK_GT(last_segment.candidates_size(), 0);
const std::string &history_value = last_segment.candidate(0).value;
if (!NumberUtil::IsArabicNumber(history_value)) {
return false;
}
japanese_util::FullWidthToHalfWidth(history_value, number_key);
return true;
}
bool IsMixedConversionEnabled(const commands::Request &request) {
return request.mixed_conversion();
}
bool IsTypingCorrectionEnabled(const ConversionRequest &request) {
return request.config().use_typing_correction();
}
bool HasHistoryKeyLongerThanOrEqualTo(const Segments &segments,
size_t utf8_len) {
const size_t history_segments_size = segments.history_segments_size();
if (history_segments_size == 0) {
return false;
}
const Segment &history_segment =
segments.history_segment(history_segments_size - 1);
if (history_segment.candidates_size() == 0) {
return false;
}
return Util::CharsLen(history_segment.candidate(0).key) >= utf8_len;
}
bool IsLongKeyForRealtimeCandidates(const Segments &segments) {
constexpr int kFewResultThreshold = 8;
return (segments.segments_size() > 0 &&
Util::CharsLen(segments.segment(0).key()) >= kFewResultThreshold);
}
size_t GetMaxSizeForRealtimeCandidates(const ConversionRequest &request,
const Segments &segments,
bool is_long_key) {
const auto &segment = segments.conversion_segment(0);
const size_t size = (request.max_dictionary_prediction_candidates_size() -
segment.candidates_size());
return is_long_key ? std::min<size_t>(size, 8) : size;
}
size_t GetDefaultSizeForRealtimeCandidates(bool is_long_key) {
return is_long_key ? 5 : 10;
}
ConversionRequest GetConversionRequestForRealtimeCandidates(
const ConversionRequest &request, size_t realtime_candidates_size,
size_t current_candidates_size) {
ConversionRequest ret = request;
ret.set_max_conversion_candidates_size(current_candidates_size +
realtime_candidates_size);
return ret;
}
} // namespace
class DictionaryPredictor::PredictiveLookupCallback
: public DictionaryInterface::Callback {
public:
PredictiveLookupCallback(DictionaryPredictor::PredictionTypes types,
size_t limit, size_t original_key_len,
const std::set<std::string> *subsequent_chars,
Segment::Candidate::SourceInfo source_info,
int unknown_id,
absl::string_view non_expanded_original_key,
const SpatialCostParams &spatial_cost_params,
std::vector<DictionaryPredictor::Result> *results)
: penalty_(0),
types_(types),
limit_(limit),
original_key_len_(original_key_len),
subsequent_chars_(subsequent_chars),
source_info_(source_info),
unknown_id_(unknown_id),
non_expanded_original_key_(non_expanded_original_key),
spatial_cost_params_(spatial_cost_params),
results_(results) {}
PredictiveLookupCallback(const PredictiveLookupCallback &) = delete;
PredictiveLookupCallback &operator=(const PredictiveLookupCallback &) =
delete;
ResultType OnKey(absl::string_view key) override {
if (subsequent_chars_ == nullptr) {
return TRAVERSE_CONTINUE;
}
// If |subsequent_chars_| was provided, check if the substring of |key|
// obtained by removing the original lookup key starts with a string in the
// set. For example, if original key is "he" and "hello" was found,
// continue traversing only when one of "l", "ll", or "llo" is in
// |subsequent_chars_|.
// Implementation note: Although absl::StartsWith is called at most N times
// where N = subsequent_chars_.size(), N is very small in practice, less
// than 10. Thus, this linear order algorithm is fast enough.
// Theoretically, we can construct a trie of strings in |subsequent_chars_|
// to get more performance but it's overkill here.
// TODO(noriyukit): std::vector<string> would be better than set<string>.
// To this end, we need to fix Comopser as well.
const absl::string_view rest = absl::ClippedSubstr(key, original_key_len_);
for (const std::string &chr : *subsequent_chars_) {
if (absl::StartsWith(rest, chr)) {
return TRAVERSE_CONTINUE;
}
}
return TRAVERSE_NEXT_KEY;
}
ResultType OnActualKey(absl::string_view key, absl::string_view actual_key,
int num_expanded) override {
penalty_ = 0;
if (num_expanded > 0 ||
(!non_expanded_original_key_.empty() &&
!absl::StartsWith(actual_key, non_expanded_original_key_))) {
penalty_ = spatial_cost_params_.GetPenalty(key);
}
return TRAVERSE_CONTINUE;
}
ResultType OnToken(absl::string_view key, absl::string_view actual_key,
const Token &token) override {
// If the token is from user dictionary and its POS is unknown, it is
// suggest-only words. Such words are looked up only when their keys
// exactly match |key|. Otherwise, unigram suggestion can be annoying. For
// example, suppose a user registers their email address as める. Then,
// we don't want to show the email address from め but exactly from める.
if ((token.attributes & Token::USER_DICTIONARY) != 0 &&
token.lid == unknown_id_) {
const auto orig_key = absl::ClippedSubstr(key, 0, original_key_len_);
if (token.key != orig_key) {
return TRAVERSE_CONTINUE;
}
}
results_->push_back(Result());
results_->back().InitializeByTokenAndTypes(token, types_);
results_->back().wcost += penalty_;
results_->back().source_info |= source_info_;
return (results_->size() < limit_) ? TRAVERSE_CONTINUE : TRAVERSE_DONE;
}
protected:
int32_t penalty_;
const DictionaryPredictor::PredictionTypes types_;
const size_t limit_;
const size_t original_key_len_;
const std::set<std::string> *subsequent_chars_;
const Segment::Candidate::SourceInfo source_info_;
const int unknown_id_;
absl::string_view non_expanded_original_key_;
const SpatialCostParams spatial_cost_params_;
std::vector<DictionaryPredictor::Result> *results_;
};
class DictionaryPredictor::PredictiveBigramLookupCallback
: public PredictiveLookupCallback {
public:
PredictiveBigramLookupCallback(
DictionaryPredictor::PredictionTypes types, size_t limit,
size_t original_key_len, const std::set<std::string> *subsequent_chars,
absl::string_view history_value,
Segment::Candidate::SourceInfo source_info, int unknown_id,
absl::string_view non_expanded_original_key,
const SpatialCostParams spatial_cost_params,
std::vector<DictionaryPredictor::Result> *results)
: PredictiveLookupCallback(types, limit, original_key_len,
subsequent_chars, source_info, unknown_id,
non_expanded_original_key, spatial_cost_params,
results),
history_value_(history_value) {}
PredictiveBigramLookupCallback(const PredictiveBigramLookupCallback &) =
delete;
PredictiveBigramLookupCallback &operator=(
const PredictiveBigramLookupCallback &) = delete;
ResultType OnToken(absl::string_view key, absl::string_view expanded_key,
const Token &token) override {
// Skip the token if its value doesn't start with the previous user input,
// |history_value_|.
if (!absl::StartsWith(token.value, history_value_) ||
token.value.size() <= history_value_.size()) {
return TRAVERSE_CONTINUE;
}
ResultType result_type =
PredictiveLookupCallback::OnToken(key, expanded_key, token);
return result_type;
}
private:
absl::string_view history_value_;
};
// Comparator for sorting prediction candidates.
// If we have words A and AB, for example "六本木" and "六本木ヒルズ",
// assume that cost(A) < cost(AB).
class DictionaryPredictor::ResultWCostLess {
public:
bool operator()(const DictionaryPredictor::Result &lhs,
const DictionaryPredictor::Result &rhs) const {
return lhs.wcost < rhs.wcost;
}
};
class DictionaryPredictor::ResultCostLess {
public:
bool operator()(const DictionaryPredictor::Result &lhs,
const DictionaryPredictor::Result &rhs) const {
return lhs.cost > rhs.cost;
}
};
DictionaryPredictor::DictionaryPredictor(
const DataManagerInterface &data_manager,
const ConverterInterface *converter,
const ImmutableConverterInterface *immutable_converter,
const DictionaryInterface *dictionary,
const DictionaryInterface *suffix_dictionary, const Connector *connector,
const Segmenter *segmenter, const PosMatcher *pos_matcher,
const SuggestionFilter *suggestion_filter)
: converter_(converter),
immutable_converter_(immutable_converter),
dictionary_(dictionary),
suffix_dictionary_(suffix_dictionary),
connector_(connector),
segmenter_(segmenter),
suggestion_filter_(suggestion_filter),
counter_suffix_word_id_(pos_matcher->GetCounterSuffixWordId()),
general_symbol_id_(pos_matcher->GetGeneralSymbolId()),
unknown_id_(pos_matcher->GetUnknownId()),
predictor_name_("DictionaryPredictor") {
absl::string_view zero_query_token_array_data;
absl::string_view zero_query_string_array_data;
absl::string_view zero_query_number_token_array_data;
absl::string_view zero_query_number_string_array_data;
data_manager.GetZeroQueryData(&zero_query_token_array_data,
&zero_query_string_array_data,
&zero_query_number_token_array_data,
&zero_query_number_string_array_data);
zero_query_dict_.Init(zero_query_token_array_data,
zero_query_string_array_data);
zero_query_number_dict_.Init(zero_query_number_token_array_data,
zero_query_number_string_array_data);
}
DictionaryPredictor::~DictionaryPredictor() {}
void DictionaryPredictor::Finish(const ConversionRequest &request,
Segments *segments) {
if (segments->request_type() == Segments::REVERSE_CONVERSION) {
// Do nothing for REVERSE_CONVERSION.
return;
}
const Segment &segment = segments->conversion_segment(0);
if (segment.candidates_size() < 1) {
VLOG(2) << "candidates size < 1";
return;
}
const Segment::Candidate &candidate = segment.candidate(0);
if (segment.segment_type() != Segment::FIXED_VALUE) {
VLOG(2) << "segment is not FIXED_VALUE" << candidate.value;
return;
}
MaybeRecordUsageStats(candidate);
}
void DictionaryPredictor::MaybeRecordUsageStats(
const Segment::Candidate &candidate) const {
if (candidate.source_info &
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_NONE) {
UsageStats::IncrementCount("CommitDictionaryPredictorZeroQueryTypeNone");
}
if (candidate.source_info &
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_NUMBER_SUFFIX) {
UsageStats::IncrementCount(
"CommitDictionaryPredictorZeroQueryTypeNumberSuffix");
}
if (candidate.source_info &
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_EMOTICON) {
UsageStats::IncrementCount(
"CommitDictionaryPredictorZeroQueryTypeEmoticon");
}
if (candidate.source_info &
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_EMOJI) {
UsageStats::IncrementCount("CommitDictionaryPredictorZeroQueryTypeEmoji");
}
if (candidate.source_info &
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_BIGRAM) {
UsageStats::IncrementCount("CommitDictionaryPredictorZeroQueryTypeBigram");
}
if (candidate.source_info &
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_SUFFIX) {
UsageStats::IncrementCount("CommitDictionaryPredictorZeroQueryTypeSuffix");
}
}
bool DictionaryPredictor::PredictForRequest(const ConversionRequest &request,
Segments *segments) const {
if (segments == nullptr) {
return false;
}
if (segments->request_type() == Segments::CONVERSION) {
VLOG(2) << "request type is CONVERSION";
return false;
}
if (segments->conversion_segments_size() < 1) {
VLOG(2) << "segment size < 1";
return false;
}
std::vector<Result> results;
// Mixed conversion is the feature that mixes prediction and
// conversion, meaning that results may include the candidates whose
// key is exactly the same as the composition. This mode is used in mobile.
const bool is_mixed_conversion = IsMixedConversionEnabled(request.request());
AggregatePredictionForRequest(request, segments, &results);
if (results.empty()) {
return false;
}
if (is_mixed_conversion) {
SetPredictionCostForMixedConversion(*segments, &results);
if (!IsEnableNewSpatialScoring(request)) {
ApplyPenaltyForKeyExpansion(*segments, &results);
}
// Currently, we don't have spelling correction feature when in
// the mixed conversion mode, so RemoveMissSpelledCandidates() is
// not called.
return AddPredictionToCandidates(
request,
true, // Include exact key result even if it's a bad suggestion.
segments, &results);
}
// Normal prediction.
SetPredictionCost(*segments, &results);
if (!IsEnableNewSpatialScoring(request)) {
ApplyPenaltyForKeyExpansion(*segments, &results);
}
const std::string &input_key = segments->conversion_segment(0).key();
const size_t input_key_len = Util::CharsLen(input_key);
RemoveMissSpelledCandidates(input_key_len, &results);
return AddPredictionToCandidates(request, false, // Remove exact key result.
segments, &results);
}
DictionaryPredictor::PredictionTypes
DictionaryPredictor::AggregatePredictionForRequest(
const ConversionRequest &request, Segments *segments,
std::vector<Result> *results) const {
const bool is_mixed_conversion = IsMixedConversionEnabled(request.request());
// In mixed conversion mode, the number of real time candidates is increased.
const size_t realtime_max_size =
GetRealtimeCandidateMaxSize(request, *segments, is_mixed_conversion);
const auto &unigram_config = GetUnigramConfig(request, *segments);
return AggregatePrediction(request, realtime_max_size, unigram_config,
segments, results);
}
DictionaryPredictor::UnigramConfig DictionaryPredictor::GetUnigramConfig(
const ConversionRequest &request, const Segments &segments) const {
const bool is_mixed_conversion = IsMixedConversionEnabled(request.request());
if (IsLatinInputMode(request)) {
// For SUGGESTION request in Desktop, We don't look up English words when
// key length is one.
const size_t min_key_len_for_latin_input =
(is_mixed_conversion || segments.request_type() == Segments::PREDICTION)
? 1
: 2;
return {&DictionaryPredictor::AggregateUnigramCandidateForLatinInput,
min_key_len_for_latin_input};
}
if (is_mixed_conversion) {
// In mixed conversion mode, we want to show unigram candidates even for
// short keys to emulate PREDICTION mode.
constexpr size_t kMinUnigramKeyLen = 1;
return {&DictionaryPredictor::AggregateUnigramCandidateForMixedConversion,
kMinUnigramKeyLen};
}
// Normal prediction.
const size_t min_unigram_key_len =
(segments.request_type() == Segments::PREDICTION) ? 1 : 3;
return {&DictionaryPredictor::AggregateUnigramCandidate, min_unigram_key_len};
}
DictionaryPredictor::PredictionTypes DictionaryPredictor::AggregatePrediction(
const ConversionRequest &request, size_t realtime_max_size,
const UnigramConfig &unigram_config, Segments *segments,
std::vector<Result> *results) const {
DCHECK(segments);
DCHECK(results);
// Zero query prediction.
if (segments->conversion_segment(0).key().empty()) {
return AggregatePredictionForZeroQuery(request, segments, results);
}
const std::string &key = segments->conversion_segment(0).key();
const size_t key_len = Util::CharsLen(key);
// TODO(toshiyuki): Check if we can remove this SUGGESTION check.
// i.e. can we return NO_PREDICTION here for both of SUGGESTION and
// PREDICTION?
if (segments->request_type() == Segments::SUGGESTION) {
if (!request.config().use_dictionary_suggest()) {
VLOG(2) << "no_dictionary_suggest";
return NO_PREDICTION;
}
// Never trigger prediction if the key looks like zip code.
if (DictionaryPredictor::IsZipCodeRequest(key) && key_len < 6) {
return NO_PREDICTION;
}
}
PredictionTypes selected_types = NO_PREDICTION;
if (ShouldAggregateRealTimeConversionResults(request, *segments)) {
AggregateRealtimeConversion(request, realtime_max_size, segments, results);
selected_types |= REALTIME;
}
// In partial suggestion or prediction, only realtime candidates are used.
if (segments->request_type() == Segments::PARTIAL_SUGGESTION ||
segments->request_type() == Segments::PARTIAL_PREDICTION) {
return selected_types;
}
// Add unigram candidates.
const size_t min_unigram_key_len = unigram_config.min_key_len;
if (key_len >= min_unigram_key_len) {
const auto &unigram_fn = unigram_config.unigram_fn;
PredictionType type = (this->*unigram_fn)(request, *segments, results);
selected_types |= type;
}
// Add bigram candidates.
constexpr int kMinHistoryKeyLen = 3;
if (HasHistoryKeyLongerThanOrEqualTo(*segments, kMinHistoryKeyLen)) {
AggregateBigramPrediction(request, *segments,
Segment::Candidate::SOURCE_INFO_NONE, results);
selected_types |= BIGRAM;
}
// Add english candidates.
if (IsLanguageAwareInputEnabled(request) && IsQwertyMobileTable(request) &&
key_len >= min_unigram_key_len) {
AggregateEnglishPredictionUsingRawInput(request, *segments, results);
selected_types |= ENGLISH;
}
// Add typing correction candidates.
constexpr int kMinTypingCorrectionKeyLen = 3;
if (IsTypingCorrectionEnabled(request) &&
key_len >= kMinTypingCorrectionKeyLen) {
AggregateTypeCorrectingPrediction(request, *segments, results);
selected_types |= TYPING_CORRECTION;
}
return selected_types;
}
bool DictionaryPredictor::AddPredictionToCandidates(
const ConversionRequest &request, bool include_exact_key,
Segments *segments, std::vector<Result> *results) const {
DCHECK(segments);
DCHECK(results);
const std::string &input_key = segments->conversion_segment(0).key();
const size_t input_key_len = Util::CharsLen(input_key);
std::string history_key, history_value;
GetHistoryKeyAndValue(*segments, &history_key, &history_value);
// exact_bigram_key does not contain ambiguity expansion, because
// this is used for exact matching for the key.
const std::string exact_bigram_key = history_key + input_key;
Segment *segment = segments->mutable_conversion_segment(0);
DCHECK(segment);
// Instead of sorting all the results, we construct a heap.
// This is done in linear time and
// we can pop as many results as we need efficiently.
std::make_heap(results->begin(), results->end(), ResultCostLess());
const size_t size = std::min(
request.max_dictionary_prediction_candidates_size(), results->size());
int added = 0;
std::set<std::string> seen;
int added_suffix = 0;
bool cursor_at_tail =
request.has_composer() &&
request.composer().GetCursor() == request.composer().GetLength();
absl::flat_hash_map<std::string, int32_t> merged_types;
#ifndef NDEBUG
const bool is_debug = true;
#else // NDEBUG
// TODO(taku): Sets more advanced debug info depending on the verbose_level.
const bool is_debug = request.config().verbose_level() >= 1;
#endif // NDEBUG
if (is_debug) {
for (const auto &result : *results) {
if (!result.removed) {
merged_types[result.value] |= result.types;
}
}
}
auto add_candidate = [&](const Result &result, const std::string &key,
const std::string &value,
Segment::Candidate *candidate) {
DCHECK(candidate);
candidate->Init();
candidate->content_key = key;
candidate->content_value = value;
candidate->key = key;
candidate->value = value;
candidate->lid = result.lid;
candidate->rid = result.rid;
candidate->wcost = result.wcost;
candidate->cost = result.cost;
candidate->attributes = result.candidate_attributes;
if ((!(candidate->attributes & Segment::Candidate::SPELLING_CORRECTION) &&
IsLatinInputMode(request)) ||
(result.types & SUFFIX)) {
candidate->attributes |= Segment::Candidate::NO_VARIANTS_EXPANSION;
candidate->attributes |= Segment::Candidate::NO_EXTRA_DESCRIPTION;
}
if (candidate->attributes & Segment::Candidate::PARTIALLY_KEY_CONSUMED) {
candidate->consumed_key_size = result.consumed_key_size;
// There are two scenarios to reach here.
// 1. Auto partial suggestion.
// e.g. composition わたしのなまえ| -> candidate 私の
// 2. Partial suggestion.
// e.g. composition わたしの|なまえ -> candidate 私の
// To distinguish auto partial suggestion from (non-auto) partial
// suggestion, see the cursor position. If the cursor is at the tail
// of the composition, this is auto partial suggestion.
if (cursor_at_tail) {
candidate->attributes |= Segment::Candidate::AUTO_PARTIAL_SUGGESTION;
}
}
candidate->source_info = result.source_info;
if (result.types & REALTIME) {
candidate->inner_segment_boundary = result.inner_segment_boundary;
}
if (result.types & TYPING_CORRECTION) {
candidate->attributes |= Segment::Candidate::TYPING_CORRECTION;
}
SetDescription(result.types, candidate->attributes,
&candidate->description);
if (is_debug) {
SetDebugDescription(merged_types[result.value], &candidate->description);
}
#ifdef MOZC_DEBUG
candidate->log += "\n" + result.log;
#endif // MOZC_DEBUG
};
#ifdef MOZC_DEBUG
auto add_debug_candidate = [&](Result result, const std::string &log) {
std::string key, value;
if (result.types & BIGRAM) {
// remove the prefix of history key and history value.
key = result.key.substr(history_key.size(),
result.key.size() - history_key.size());
value = result.value.substr(history_value.size(),
result.value.size() - history_value.size());
} else {
key = result.key;
value = result.value;
}
result.log.append(log);
Segment::Candidate candidate;
add_candidate(result, key, value, &candidate);
segment->removed_candidates_for_debug_.push_back(std::move(candidate));
};
#define MOZC_ADD_DEBUG_CANDIDATE(result, log) \
add_debug_candidate(result, MOZC_WORD_LOG_MESSAGE(log))
#else // MOZC_DEBUG
#define MOZC_ADD_DEBUG_CANDIDATE(result, log) \
{}
#endif // MOZC_DEBUG
for (size_t i = 0; i < results->size(); ++i) {
// Pop a result from a heap. Please pay attention not to use results->at(i).
std::pop_heap(results->begin(), results->end() - i, ResultCostLess());
const Result &result = results->at(results->size() - i - 1);
if (added >= size || result.cost >= kInfinity) {
break;
}
if (result.removed) {
MOZC_ADD_DEBUG_CANDIDATE(result, "Removed flag is on");
continue;
}
// When |include_exact_key| is true, we don't filter the results
// which have the exactly same key as the input even if it's a bad
// suggestion.
if (!(include_exact_key && (result.key == input_key)) &&
suggestion_filter_->IsBadSuggestion(result.value)) {
MOZC_ADD_DEBUG_CANDIDATE(result, "Bad suggestion");
continue;
}
// Don't suggest exactly the same candidate as key.
// if |include_exact_key| is true, that's not the case.
if (!include_exact_key && !(result.types & REALTIME) &&
(((result.types & BIGRAM) && exact_bigram_key == result.value) ||
(!(result.types & BIGRAM) && input_key == result.value))) {
MOZC_ADD_DEBUG_CANDIDATE(result, "Key == candidate");
continue;
}
std::string key, value;
if (result.types & BIGRAM) {
// remove the prefix of history key and history value.
key = result.key.substr(history_key.size(),
result.key.size() - history_key.size());
value = result.value.substr(history_value.size(),
result.value.size() - history_value.size());
} else {
key = result.key;
value = result.value;
}
if (!seen.insert(value).second) {
MOZC_ADD_DEBUG_CANDIDATE(result, "Duplicated");
continue;
}
// User input: "おーすとり" (len = 5)
// key/value: "おーすとりら" "オーストラリア" (miss match pos = 4)
if ((result.candidate_attributes &
Segment::Candidate::SPELLING_CORRECTION) &&
key != input_key &&
input_key_len <= GetMissSpelledPosition(key, value) + 1) {
MOZC_ADD_DEBUG_CANDIDATE(result, "Spelling correction");
continue;
}
if (result.types == SUFFIX && added_suffix++ >= 20) {
// TODO(toshiyuki): Need refactoring for controlling suffix
// prediction number after we will fix the appropriate number.
MOZC_ADD_DEBUG_CANDIDATE(result, "Added suffix >= 20");
continue;
}
Segment::Candidate *candidate = segment->push_back_candidate();
add_candidate(result, key, value, candidate);
++added;
}
return added > 0;
#undef MOZC_ADD_DEBUG_CANDIDATE
}
DictionaryPredictor::PredictionTypes
DictionaryPredictor::AggregatePredictionForZeroQuery(
const ConversionRequest &request, Segments *segments,
std::vector<Result> *results) const {
DCHECK(segments);
DCHECK(results);
if (!request.request().zero_query_suggestion()) {
// Zero query is disabled by request.
return NO_PREDICTION;
}
PredictionTypes selected_types = NO_PREDICTION;
constexpr int kMinHistoryKeyLenForZeroQuery = 2;
if (HasHistoryKeyLongerThanOrEqualTo(*segments,
kMinHistoryKeyLenForZeroQuery)) {
AggregateBigramPrediction(
request, *segments,
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_BIGRAM, results);
selected_types |= BIGRAM;
}
if (segments->history_segments_size() > 0) {
AggregateZeroQuerySuffixPrediction(request, *segments, results);
selected_types |= SUFFIX;
}
return selected_types;
}
DictionaryPredictor::PredictionType
DictionaryPredictor::AggregateUnigramCandidateForLatinInput(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
AggregateEnglishPrediction(request, segments, results);
return ENGLISH;
}
void DictionaryPredictor::SetDescription(PredictionTypes types,
uint32_t attributes,
std::string *description) {
if (types & TYPING_CORRECTION) {
Util::AppendStringWithDelimiter(" ", "補正", description);
}
if (attributes & Segment::Candidate::AUTO_PARTIAL_SUGGESTION) {
Util::AppendStringWithDelimiter(" ", "部分", description);
}
}
void DictionaryPredictor::SetDebugDescription(PredictionTypes types,
std::string *description) {
std::string debug_desc;
if (types & UNIGRAM) {
debug_desc.append(1, 'U');
}
if (types & BIGRAM) {
debug_desc.append(1, 'B');
}
if (types & REALTIME_TOP) {
debug_desc.append("R1");
} else if (types & REALTIME) {
debug_desc.append(1, 'R');
}
if (types & SUFFIX) {
debug_desc.append(1, 'S');
}
if (types & ENGLISH) {
debug_desc.append(1, 'E');
}
// Note that description for TYPING_CORRECTION is omitted
// because it is appended by SetDescription.
if (!debug_desc.empty()) {
Util::AppendStringWithDelimiter(" ", debug_desc, description);
}
}
// Returns cost for |result| when it's transitioned from |rid|. Suffix penalty
// is also added for non-realtime results.
int DictionaryPredictor::GetLMCost(const Result &result, int rid) const {
const int cost_with_context = connector_->GetTransitionCost(rid, result.lid);
int lm_cost = 0;
if (result.types & SUFFIX) {
// We always respect the previous context to calculate the cost of SUFFIX.
// Otherwise, the suffix that doesn't match the context will be promoted.
lm_cost = cost_with_context + result.wcost;
} else {
// Sometimes transition cost is too high and causes a bug like b/18112966.
// For example, "接続詞 が" -> "始まる 動詞,五段活用,基本形" has very large
// cost and "始まる" is demoted. To prevent such cases, ImmutableConverter
// computes transition from BOS/EOS too; see
// ImmutableConverterImpl::MakeLatticeNodesForHistorySegments().
// Here, taking the minimum of |cost1| and |cost2| has a similar effect.
const int cost_without_context =
connector_->GetTransitionCost(0, result.lid);
lm_cost = std::min(cost_with_context, cost_without_context) + result.wcost;
}
if (!(result.types & REALTIME)) {
// Relatime conversion already adds perfix/suffix penalties to the result.
// Note that we don't add prefix penalty the role of "bunsetsu" is
// ambiguous on zero-query suggestion.
lm_cost += segmenter_->GetSuffixPenalty(result.rid);
}
return lm_cost;
}
namespace {
class FindValueCallback : public DictionaryInterface::Callback {
public:
explicit FindValueCallback(absl::string_view target_value)
: target_value_(target_value), found_(false) {}
ResultType OnToken(absl::string_view, // key
absl::string_view, // actual_key
const Token &token) override {
if (token.value != target_value_) {
return TRAVERSE_CONTINUE;
}
found_ = true;
token_ = token;
return TRAVERSE_DONE;
}
bool found() const { return found_; }
const Token &token() const { return token_; }
private:
absl::string_view target_value_;
bool found_;
Token token_;
DISALLOW_COPY_AND_ASSIGN(FindValueCallback);
};
} // namespace
void DictionaryPredictor::Result::InitializeByTokenAndTypes(
const Token &token, PredictionTypes types) {
SetTypesAndTokenAttributes(types, token.attributes);
key = token.key;
value = token.value;
wcost = token.cost;
lid = token.lid;
rid = token.rid;
}
void DictionaryPredictor::Result::SetTypesAndTokenAttributes(
PredictionTypes prediction_types, Token::AttributesBitfield token_attr) {
types = prediction_types;
candidate_attributes = 0;
if (types & TYPING_CORRECTION) {
candidate_attributes |= Segment::Candidate::TYPING_CORRECTION;
}
if (types & (REALTIME | REALTIME_TOP)) {
candidate_attributes |= Segment::Candidate::REALTIME_CONVERSION;
}
if (token_attr & Token::SPELLING_CORRECTION) {
candidate_attributes |= Segment::Candidate::SPELLING_CORRECTION;
}
if (token_attr & Token::USER_DICTIONARY) {
candidate_attributes |= (Segment::Candidate::USER_DICTIONARY |
Segment::Candidate::NO_VARIANTS_EXPANSION);
}
}
void DictionaryPredictor::Result::SetSourceInfoForZeroQuery(
ZeroQueryType type) {
switch (type) {
case ZERO_QUERY_NONE:
source_info |= Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_NONE;
return;
case ZERO_QUERY_NUMBER_SUFFIX:
source_info |=
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_NUMBER_SUFFIX;
return;
case ZERO_QUERY_EMOTICON:
source_info |=
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_EMOTICON;
return;
case ZERO_QUERY_EMOJI:
source_info |= Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_EMOJI;
return;
case ZERO_QUERY_BIGRAM:
source_info |= Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_BIGRAM;
return;
case ZERO_QUERY_SUFFIX:
source_info |= Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_SUFFIX;
return;
default:
LOG(ERROR) << "Should not come here";
return;
}
}
bool DictionaryPredictor::Result::IsUserDictionaryResult() const {
return (candidate_attributes & Segment::Candidate::USER_DICTIONARY) != 0;
}
// Here, we treat the word as English when its key consists of Latin
// characters.
bool DictionaryPredictor::Result::IsEnglishEntryResult() const {
return Util::IsEnglishTransliteration(key);
}
bool DictionaryPredictor::GetHistoryKeyAndValue(const Segments &segments,
std::string *key,
std::string *value) const {
DCHECK(key);
DCHECK(value);
if (segments.history_segments_size() == 0) {
return false;
}
const Segment &history_segment =
segments.history_segment(segments.history_segments_size() - 1);
if (history_segment.candidates_size() == 0) {
return false;
}
key->assign(history_segment.candidate(0).key);
value->assign(history_segment.candidate(0).value);
return true;
}
void DictionaryPredictor::SetPredictionCost(
const Segments &segments, std::vector<Result> *results) const {
DCHECK(results);
int rid = 0; // 0 (BOS) is default
if (segments.history_segments_size() > 0) {
const Segment &history_segment =
segments.history_segment(segments.history_segments_size() - 1);
if (history_segment.candidates_size() > 0) {
rid = history_segment.candidate(0).rid; // use history segment's id
}
}
const std::string &input_key = segments.conversion_segment(0).key();
std::string history_key, history_value;
GetHistoryKeyAndValue(segments, &history_key, &history_value);
const std::string bigram_key = history_key + input_key;
const bool is_suggestion = (segments.request_type() == Segments::SUGGESTION);
// use the same scoring function for both unigram/bigram.
// Bigram will be boosted because we pass the previous
// key as a context information.
const size_t bigram_key_len = Util::CharsLen(bigram_key);
const size_t unigram_key_len = Util::CharsLen(input_key);
// In the loop below, we track the minimum cost among those REALTIME
// candidates that have the same key length as |input_key| so that we can set
// a slightly smaller cost to REALTIME_TOP than these.
int realtime_cost_min = kInfinity;
Result *realtime_top_result = nullptr;
for (size_t i = 0; i < results->size(); ++i) {
const Result &result = results->at(i);
// The cost of REALTIME_TOP is determined after the loop based on the
// minimum cost for REALTIME. Just remember the pointer of result.
if (result.types & REALTIME_TOP) {
realtime_top_result = &results->at(i);
continue;
}
const int cost = GetLMCost(result, rid);
const size_t query_len =
(result.types & BIGRAM) ? bigram_key_len : unigram_key_len;
const size_t key_len = Util::CharsLen(result.key);
if (IsAggressiveSuggestion(query_len, key_len, cost, is_suggestion,
results->size())) {
results->at(i).cost = kInfinity;
continue;
}
// cost = -500 * log(lang_prob(w) * (1 + remain_length)) -- (1)
// where lang_prob(w) is a language model probability of the word "w", and
// remain_length the length of key user must type to input "w".
//
// Example:
// key/value = "とうきょう/東京"
// user_input = "とう"
// remain_length = len("とうきょう") - len("とう") = 3
//
// By taking the log of (1),
// cost = -500 [log(lang_prob(w)) + log(1 + ramain_length)]
// = -500 * log(lang_prob(w)) + 500 * log(1 + remain_length)
// = cost - 500 * log(1 + remain_length)
// Because 500 * log(lang_prob(w)) = -cost.
//
// lang_prob(w) * (1 + remain_length) represents how user can reduce
// the total types by choosing this candidate.
// Before this simple algorithm, we have been using an SVM-base scoring,
// but we stop usign it with the following reasons.
// 1) Hard to maintain the ranking.
// 2) Hard to control the final results of SVM.
// 3) Hard to debug.
// 4) Since we used the log(remain_length) as a feature,
// the new ranking algorithm and SVM algorithm was essentially
// the same.
// 5) Since we used the length of value as a feature, we find
// inconsistencies between the conversion and the prediction
// -- the results of top prediction and the top conversion
// (the candidate shown after the space key) may differ.
//
// The new function brings consistent results. If two candidate
// have the same reading (key), they should have the same cost bonus
// from the length part. This implies that the result is reranked by
// the language model probability as long as the key part is the same.
// This behavior is baisically the same as the converter.
//
// TODO(team): want find the best parameter instead of kCostFactor.
constexpr int kCostFactor = 500;
results->at(i).cost =
cost - kCostFactor * log(1.0 + std::max<int>(0, key_len - query_len));
// Update the minimum cost for REALTIME candidates that have the same key
// length as input_key.
if (result.types & REALTIME && result.cost < realtime_cost_min &&
result.key.size() == input_key.size()) {
realtime_cost_min = result.cost;
}
}
// Ensure that the REALTIME_TOP candidate has relatively smaller cost than
// those of REALTIME candidates.
if (realtime_top_result != nullptr) {
realtime_top_result->cost = std::max(0, realtime_cost_min - 10);
}
}
void DictionaryPredictor::SetPredictionCostForMixedConversion(
const Segments &segments, std::vector<Result> *results) const {
DCHECK(results);
// ranking for mobile
int rid = 0; // 0 (BOS) is default
int prev_cost = 0; // cost of the last history candidate.
if (segments.history_segments_size() > 0) {
const Segment &history_segment =
segments.history_segment(segments.history_segments_size() - 1);
if (history_segment.candidates_size() > 0) {
rid = history_segment.candidate(0).rid; // use history segment's id
prev_cost = history_segment.candidate(0).cost;
if (prev_cost == 0) {
// if prev_cost is set to be 0 for some reason, use default cost.
prev_cost = 5000;
}
}
}
const size_t input_key_len =
Util::CharsLen(segments.conversion_segment(0).key());
for (Result &result : *results) {
int cost = GetLMCost(result, rid);
MOZC_WORD_LOG(result, absl::StrCat("GetLMCost: ", cost));
// Demote filtered word here, because they are not filtered for exact match.
// Even for exact match, we don't want to show aggressive words with high
// ranking.
if (suggestion_filter_->IsBadSuggestion(result.value)) {
// Cost penalty means for bad suggestion.
// 3453 = 500 * log(1000)
constexpr int kBadSuggestionPenalty = 3453;
cost += kBadSuggestionPenalty;
MOZC_WORD_LOG(result, absl::StrCat("BadSuggestionPenalty: ", cost));
}
// Make exact candidates to have higher ranking.
// Because for mobile, suggestion is the main candidates and
// users expect the candidates for the input key on the candidates.
if (result.types & (UNIGRAM | TYPING_CORRECTION)) {
const size_t key_len = Util::CharsLen(result.key);
if (key_len > input_key_len) {
// Cost penalty means that exact candidates are evaluated
// 50 times bigger in frequency.
// Note that the cost is calculated by cost = -500 * log(prob)
// 1956 = 500 * log(50)
constexpr int kNotExactPenalty = 1956;
cost += kNotExactPenalty;
MOZC_WORD_LOG(result,
absl::StrCat("Unigram | Typing correction: ", cost));
}
}
if (result.types & BIGRAM) {
// When user inputs "六本木" and there is an entry
// "六本木ヒルズ" in the dictionary, we can suggest
// "ヒルズ" as a ZeroQuery suggestion. In this case,
// We can't calcurate the transition cost between "六本木"
// and "ヒルズ". If we ignore the transition cost,
// bigram-based suggestion will be overestimated.
// Here we use kDefaultTransitionCost as an
// transition cost between "六本木" and "ヒルズ". Currently,
// the cost is basically the same as the cost between
// "名詞,一般" and "名詞,一般".
// TODO(taku): Adjust these parameters.
// Seems the bigram is overestimated.
constexpr int kDefaultTransitionCost = 1347;
// Promoting bigram candidates.
constexpr int kBigramBonus = 800; // ~= 500*ln(5)
cost += (kDefaultTransitionCost - kBigramBonus - prev_cost);
MOZC_WORD_LOG(result, absl::StrCat("Bigram: ", cost));
}
if (result.candidate_attributes & Segment::Candidate::USER_DICTIONARY &&
result.lid != general_symbol_id_) {
// Decrease cost for words from user dictionary in order to promote them,
// provided that it is not a general symbol (Note: emoticons are mapped to
// general symbol). Currently user dictionary words are evaluated 5 times
// bigger in frequency, being capped by 1000 (this number is adhoc, so
// feel free to adjust).
constexpr int kUserDictionaryPromotionFactor = 804; // 804 = 500 * log(5)
constexpr int kUserDictionaryCostUpperLimit = 1000;
cost = std::min(cost - kUserDictionaryPromotionFactor,
kUserDictionaryCostUpperLimit);
MOZC_WORD_LOG(result, absl::StrCat("User dictionary: ", cost));
}
// Note that the cost is defined as -500 * log(prob).
// Even after the ad hoc manipulations, cost must remain larger than 0.
result.cost = std::max(1, cost);
MOZC_WORD_LOG(result, absl::StrCat("SetLMCost: ", result.cost));
}
}
// This method should be deprecated, as it is unintentionally adding extra
// spatial penalty to the candidate.
void DictionaryPredictor::ApplyPenaltyForKeyExpansion(
const Segments &segments, std::vector<Result> *results) const {
if (segments.conversion_segments_size() == 0) {
return;
}
// Cost penalty 1151 means that expanded candidates are evaluated
// 10 times smaller in frequency.
// Note that the cost is calcurated by cost = -500 * log(prob)
// 1151 = 500 * log(10)
constexpr int kKeyExpansionPenalty = 1151;
const std::string &conversion_key = segments.conversion_segment(0).key();
for (size_t i = 0; i < results->size(); ++i) {
Result &result = results->at(i);
if (result.types & TYPING_CORRECTION) {
continue;
}
if (!absl::StartsWith(result.key, conversion_key)) {
result.cost += kKeyExpansionPenalty;
MOZC_WORD_LOG(result, absl::StrCat("KeyExpansionPenalty: ", result.cost));
}
}
}
size_t DictionaryPredictor::GetMissSpelledPosition(
const std::string &key, const std::string &value) const {
std::string hiragana_value;
japanese_util::KatakanaToHiragana(value, &hiragana_value);
// value is mixed type. return true if key == request_key.
if (Util::GetScriptType(hiragana_value) != Util::HIRAGANA) {
return Util::CharsLen(key);
}
// Find the first position of character where miss spell occurs.
int position = 0;
ConstChar32Iterator key_iter(key);
for (ConstChar32Iterator hiragana_iter(hiragana_value);
!hiragana_iter.Done() && !key_iter.Done();
hiragana_iter.Next(), key_iter.Next(), ++position) {
if (hiragana_iter.Get() != key_iter.Get()) {
return position;
}
}
// not find. return the length of key.
while (!key_iter.Done()) {
++position;
key_iter.Next();
}
return position;
}
void DictionaryPredictor::RemoveMissSpelledCandidates(
size_t request_key_len, std::vector<Result> *results) const {
DCHECK(results);
if (results->size() <= 1) {
return;
}
int spelling_correction_size = 5;
for (size_t i = 0; i < results->size(); ++i) {
const Result &result = (*results)[i];
if (!(result.candidate_attributes &
Segment::Candidate::SPELLING_CORRECTION)) {
continue;
}
// Only checks at most 5 spelling corrections to avoid the case
// like all candidates have SPELLING_CORRECTION.
if (--spelling_correction_size == 0) {
return;
}
std::vector<size_t> same_key_index, same_value_index;
for (size_t j = 0; j < results->size(); ++j) {
if (i == j) {
continue;
}
const Result &target_result = (*results)[j];
if (target_result.candidate_attributes &
Segment::Candidate::SPELLING_CORRECTION) {
continue;
}
if (target_result.key == result.key) {
same_key_index.push_back(j);
}
if (target_result.value == result.value) {
same_value_index.push_back(j);
}
}
// delete same_key_index and same_value_index
if (!same_key_index.empty() && !same_value_index.empty()) {
results->at(i).removed = true;
MOZC_WORD_LOG(results->at(i), "Removed. same_(key|value)_index.");
for (size_t k = 0; k < same_key_index.size(); ++k) {
results->at(same_key_index[k]).removed = true;
MOZC_WORD_LOG(results->at(i), "Removed. same_(key|value)_index.");
}
} else if (same_key_index.empty() && !same_value_index.empty()) {
results->at(i).removed = true;
MOZC_WORD_LOG(results->at(i), "Removed. same_value_index.");
} else if (!same_key_index.empty() && same_value_index.empty()) {
for (size_t k = 0; k < same_key_index.size(); ++k) {
results->at(same_key_index[k]).removed = true;
MOZC_WORD_LOG(results->at(i), "Removed. same_key_index.");
}
if (request_key_len <= GetMissSpelledPosition(result.key, result.value)) {
results->at(i).removed = true;
MOZC_WORD_LOG(results->at(i), "Removed. Invalid MissSpelledPosition.");
}
}
}
}
bool DictionaryPredictor::IsAggressiveSuggestion(
size_t query_len, size_t key_len, int cost, bool is_suggestion,
size_t total_candidates_size) const {
// Temporal workaround for fixing the problem where longer sentence-like
// suggestions are shown when user input is very short.
// "ただしい" => "ただしいけめんにかぎる"
// "それでもぼ" => "それでもぼくはやっていない".
// If total_candidates_size is small enough, we don't perform
// special filtering. e.g., "せんとち" has only two candidates, so
// showing "千と千尋の神隠し" is OK.
// Also, if the cost is too small (< 5000), we allow to display
// long phrases. Examples include "よろしくおねがいします".
if (is_suggestion && total_candidates_size >= 10 && key_len >= 8 &&
cost >= 5000 && query_len <= static_cast<size_t>(0.4 * key_len)) {
return true;
}
return false;
}
size_t DictionaryPredictor::GetRealtimeCandidateMaxSize(
const ConversionRequest &request, const Segments &segments,
bool mixed_conversion) const {
const Segments::RequestType request_type = segments.request_type();
DCHECK(request_type == Segments::PREDICTION ||
request_type == Segments::SUGGESTION ||
request_type == Segments::PARTIAL_PREDICTION ||
request_type == Segments::PARTIAL_SUGGESTION);
if (segments.conversion_segments_size() == 0) {
return 0;
}
const bool is_long_key = IsLongKeyForRealtimeCandidates(segments);
const size_t max_size =
GetMaxSizeForRealtimeCandidates(request, segments, is_long_key);
const size_t default_size = GetDefaultSizeForRealtimeCandidates(is_long_key);
size_t size = 0;
switch (request_type) {
case Segments::PREDICTION:
size = mixed_conversion ? max_size : default_size;
break;
case Segments::SUGGESTION:
// Fewer candidatats are needed basically.
// But on mixed_conversion mode we should behave like as conversion mode.
size = mixed_conversion ? default_size : 1;
break;
case Segments::PARTIAL_PREDICTION:
// This is kind of prediction so richer result than PARTIAL_SUGGESTION
// is needed.
size = max_size;
break;
case Segments::PARTIAL_SUGGESTION:
// PARTIAL_SUGGESTION works like as conversion mode so returning
// some candidates is needed.
size = default_size;
break;
default:
size = 0; // Never reach here
}
return std::min(max_size, size);
}
bool DictionaryPredictor::PushBackTopConversionResult(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK_EQ(1, segments.conversion_segments_size());
Segments tmp_segments = segments;
ConversionRequest tmp_request = request;
tmp_request.set_max_conversion_candidates_size(20);
tmp_request.set_composer_key_selection(ConversionRequest::PREDICTION_KEY);
// Some rewriters cause significant performance loss. So we skip them.
tmp_request.set_skip_slow_rewriters(true);
// This method emulates usual converter's behavior so here disable
// partial candidates.
tmp_request.set_create_partial_candidates(false);
if (!converter_->StartConversionForRequest(tmp_request, &tmp_segments)) {
return false;
}
results->push_back(Result());
Result *result = &results->back();
result->key = segments.conversion_segment(0).key();
result->lid = tmp_segments.conversion_segment(0).candidate(0).lid;
result->rid =
tmp_segments
.conversion_segment(tmp_segments.conversion_segments_size() - 1)
.candidate(0)
.rid;
result->SetTypesAndTokenAttributes(REALTIME | REALTIME_TOP, Token::NONE);
result->candidate_attributes |= Segment::Candidate::NO_VARIANTS_EXPANSION;
// Concatenate the top candidates.
// Note that since StartConversionForRequest() runs in conversion mode, the
// resulting |tmp_segments| doesn't have inner_segment_boundary. We need to
// construct it manually here.
// TODO(noriyukit): This is code duplicate in converter/nbest_generator.cc and
// we should refactor code after finding more good design.
bool inner_segment_boundary_success = true;
for (size_t i = 0; i < tmp_segments.conversion_segments_size(); ++i) {
const Segment &segment = tmp_segments.conversion_segment(i);
const Segment::Candidate &candidate = segment.candidate(0);
result->value.append(candidate.value);
result->wcost += candidate.cost;
uint32_t encoded_lengths;
if (inner_segment_boundary_success &&
Segment::Candidate::EncodeLengths(
candidate.key.size(), candidate.value.size(),
candidate.content_key.size(), candidate.content_value.size(),
&encoded_lengths)) {
result->inner_segment_boundary.push_back(encoded_lengths);
} else {
inner_segment_boundary_success = false;
}
}
if (!inner_segment_boundary_success) {
LOG(WARNING) << "Failed to construct inner segment boundary";
result->inner_segment_boundary.clear();
}
return true;
}
void DictionaryPredictor::AggregateRealtimeConversion(
const ConversionRequest &request, size_t realtime_candidates_size,
Segments *segments, std::vector<Result> *results) const {
DCHECK(converter_);
DCHECK(immutable_converter_);
DCHECK(segments);
DCHECK(results);
// TODO(noriyukit): Currently, |segments| is abused as a temporary output from
// the immutable converter. Therefore, the first segment needs to be mutable.
// Fix this bad abuse.
Segment *segment = segments->mutable_conversion_segment(0);
DCHECK(!segment->key().empty());
// First insert a top conversion result.
if (request.use_actual_converter_for_realtime_conversion()) {
if (!PushBackTopConversionResult(request, *segments, results)) {
LOG(WARNING) << "Realtime conversion with converter failed";
}
}
if (realtime_candidates_size == 0) {
return;
}
// In what follows, add results from immutable converter.
// TODO(noriyukit): The |immutable_converter_| used below can be replaced by
// |converter_| in principle. There's a problem of ranking when we get
// multiple segments, i.e., how to concatenate candidates in each segment.
// Currently, immutable converter handles such ranking in prediction mode to
// generate single segment results. So we want to share that code.
// Preserve the current candidates_size to restore segments at the end of this
// method.
const size_t prev_candidates_size = segment->candidates_size();
const ConversionRequest request_for_realtime =
GetConversionRequestForRealtimeCandidates(
request, realtime_candidates_size, prev_candidates_size);
if (!immutable_converter_->ConvertForRequest(request_for_realtime,
segments) ||
prev_candidates_size >= segment->candidates_size()) {
LOG(WARNING) << "Convert failed";
return;
}
// A little tricky treatment:
// Since ImmutableConverter::Convert creates a set of new candidates,
// copy them into the array of Results.
for (size_t i = prev_candidates_size; i < segment->candidates_size(); ++i) {
const Segment::Candidate &candidate = segment->candidate(i);
results->push_back(Result());
Result *result = &results->back();
result->key = candidate.key;
result->value = candidate.value;
result->wcost = candidate.wcost;
result->lid = candidate.lid;
result->rid = candidate.rid;
result->inner_segment_boundary = candidate.inner_segment_boundary;
result->SetTypesAndTokenAttributes(REALTIME, Token::NONE);
result->candidate_attributes |= candidate.attributes;
result->consumed_key_size = candidate.consumed_key_size;
}
// Remove candidates created by ImmutableConverter.
segment->erase_candidates(prev_candidates_size,
segment->candidates_size() - prev_candidates_size);
}
size_t DictionaryPredictor::GetCandidateCutoffThreshold(
const Segments &segments) const {
DCHECK(segments.request_type() == Segments::PREDICTION ||
segments.request_type() == Segments::SUGGESTION);
if (segments.request_type() == Segments::PREDICTION) {
// If PREDICTION, many candidates are needed than SUGGESTION.
return kPredictionMaxResultsSize;
}
return kSuggestionMaxResultsSize;
}
DictionaryPredictor::PredictionType
DictionaryPredictor::AggregateUnigramCandidate(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK(results);
DCHECK(dictionary_);
DCHECK(segments.request_type() == Segments::PREDICTION ||
segments.request_type() == Segments::SUGGESTION);
const size_t cutoff_threshold = GetCandidateCutoffThreshold(segments);
const size_t prev_results_size = results->size();
GetPredictiveResults(*dictionary_, "", request, segments, UNIGRAM,
cutoff_threshold, Segment::Candidate::SOURCE_INFO_NONE,
unknown_id_, results);
const size_t unigram_results_size = results->size() - prev_results_size;
// If size reaches max_results_size (== cutoff_threshold).
// we don't show the candidates, since disambiguation from
// 256 candidates is hard. (It may exceed max_results_size, because this is
// just a limit for each backend, so total number may be larger)
if (unigram_results_size >= cutoff_threshold) {
results->resize(prev_results_size);
}
return UNIGRAM;
}
DictionaryPredictor::PredictionType
DictionaryPredictor::AggregateUnigramCandidateForMixedConversion(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK(segments.request_type() == Segments::PREDICTION ||
segments.request_type() == Segments::SUGGESTION);
AggregateUnigramCandidateForMixedConversion(*dictionary_, request, segments,
unknown_id_, results);
return UNIGRAM;
}
void DictionaryPredictor::AggregateUnigramCandidateForMixedConversion(
const dictionary::DictionaryInterface &dictionary,
const ConversionRequest &request, const Segments &segments, int unknown_id,
std::vector<Result> *results) {
const size_t cutoff_threshold = kPredictionMaxResultsSize;
std::vector<Result> raw_result;
// No history key
GetPredictiveResults(dictionary, "", request, segments, UNIGRAM,
cutoff_threshold, Segment::Candidate::SOURCE_INFO_NONE,
unknown_id, &raw_result);
// Hereafter, we split "Needed Results" and "(maybe) Unneeded Results."
// The algorithm is:
// 1) Take the Result with minimum cost.
// 2) Remove results which is "redundant" (defined by MaybeRedundant),
// from remaining results.
// 3) Repeat 1) and 2) five times.
// Note: to reduce the number of memory allocation, we swap out the
// "redundant" results to the end of the |results| vector.
constexpr size_t kDeleteTrialNum = 5;
// min_iter is the beginning of the remaining results (inclusive), and
// max_iter is the end of the remaining results (exclusive).
typedef std::vector<Result>::iterator Iter;
Iter min_iter = raw_result.begin();
Iter max_iter = raw_result.end();
for (size_t i = 0; i < kDeleteTrialNum; ++i) {
if (min_iter == max_iter) {
break;
}
// Find the Result with minimum cost. Swap it with the beginning element.
std::iter_swap(min_iter,
std::min_element(min_iter, max_iter, ResultWCostLess()));
const Result &reference_result = *min_iter;
// Preserve the reference result.
++min_iter;
// Traverse all remaining elements and check if each result is redundant.
for (Iter iter = min_iter; iter != max_iter;) {
// - We do not filter user dictionary word.
const bool should_check_redundant = !iter->IsUserDictionaryResult();
if (should_check_redundant &&
MaybeRedundant(reference_result.value, iter->value)) {
// Swap out the redundant result.
--max_iter;
std::iter_swap(iter, max_iter);
} else {
++iter;
}
}
}
// Then the |raw_result| contains;
// [begin, min_iter): reference results in the above loop.
// [max_iter, end): (maybe) redundant results.
// [min_iter, max_iter): remaining results.
// Here, we revive the redundant results up to five in the result cost order.
constexpr size_t kDoNotDeleteNum = 5;
if (std::distance(max_iter, raw_result.end()) >= kDoNotDeleteNum) {
std::partial_sort(max_iter, max_iter + kDoNotDeleteNum, raw_result.end(),
ResultWCostLess());
max_iter += kDoNotDeleteNum;
} else {
max_iter = raw_result.end();
}
// Finally output the result.
results->insert(results->end(), raw_result.begin(), max_iter);
}
void DictionaryPredictor::AggregateBigramPrediction(
const ConversionRequest &request, const Segments &segments,
Segment::Candidate::SourceInfo source_info,
std::vector<Result> *results) const {
DCHECK(results);
DCHECK(dictionary_);
// TODO(toshiyuki): Support suggestion from the last 2 histories.
// ex) "六本木"+"ヒルズ"->"レジデンス"
std::string history_key, history_value;
if (!GetHistoryKeyAndValue(segments, &history_key, &history_value)) {
return;
}
AddBigramResultsFromHistory(history_key, history_value, request, segments,
source_info, results);
}
void DictionaryPredictor::AddBigramResultsFromHistory(
const std::string &history_key, const std::string &history_value,
const ConversionRequest &request, const Segments &segments,
Segment::Candidate::SourceInfo source_info,
std::vector<Result> *results) const {
// Check that history_key/history_value are in the dictionary.
FindValueCallback find_history_callback(history_value);
dictionary_->LookupPrefix(history_key, request, &find_history_callback);
// History value is not found in the dictionary.
// User may create this the history candidate from T13N or segment
// expand/shrinkg operations.
if (!find_history_callback.found()) {
return;
}
const size_t cutoff_threshold = GetCandidateCutoffThreshold(segments);
const size_t prev_results_size = results->size();
GetPredictiveResultsForBigram(*dictionary_, history_key, history_value,
request, segments, BIGRAM, cutoff_threshold,
source_info, unknown_id_, results);
const size_t bigram_results_size = results->size() - prev_results_size;
// if size reaches max_results_size,
// we don't show the candidates, since disambiguation from
// 256 candidates is hard. (It may exceed max_results_size, because this is
// just a limit for each backend, so total number may be larger)
if (bigram_results_size >= cutoff_threshold) {
results->resize(prev_results_size);
return;
}
// Obtain the character type of the last history value.
const size_t history_value_size = Util::CharsLen(history_value);
if (history_value_size == 0) {
return;
}
const Util::ScriptType history_ctype = Util::GetScriptType(history_value);
const Util::ScriptType last_history_ctype = Util::GetScriptType(
Util::Utf8SubString(history_value, history_value_size - 1, 1));
for (size_t i = prev_results_size; i < results->size(); ++i) {
CheckBigramResult(find_history_callback.token(), history_ctype,
last_history_ctype, request, &(*results)[i]);
}
}
// Filter out irrelevant bigrams. For example, we don't want to
// suggest "リカ" from the history "アメ".
void DictionaryPredictor::CheckBigramResult(
const Token &history_token, const Util::ScriptType history_ctype,
const Util::ScriptType last_history_ctype, const ConversionRequest &request,
Result *result) const {
DCHECK(result);
const std::string &history_key = history_token.key;
const std::string &history_value = history_token.value;
const std::string key(result->key, history_key.size(),
result->key.size() - history_key.size());
const std::string value(result->value, history_value.size(),
result->value.size() - history_value.size());
// Don't suggest 0-length key/value.
if (key.empty() || value.empty()) {
result->removed = true;
MOZC_WORD_LOG(*result, "Removed. key, value or both are empty.");
return;
}
const Util::ScriptType ctype =
Util::GetScriptType(Util::Utf8SubString(value, 0, 1));
if (history_ctype == Util::KANJI && ctype == Util::KATAKANA) {
// Do not filter "六本木ヒルズ"
MOZC_WORD_LOG(*result, "Valid bigram. Kanji + Katakana pattern.");
return;
}
// If freq("アメ") < freq("アメリカ"), we don't
// need to suggest it. As "アメリカ" should already be
// suggested when user type "アメ".
// Note that wcost = -500 * log(prob).
if (ctype != Util::KANJI && history_token.cost > result->wcost) {
result->removed = true;
MOZC_WORD_LOG(*result,
"Removed. The prefix's score is lower than the whole.");
return;
}
// If character type doesn't change, this boundary might NOT
// be a word boundary. Only use iif the entire key is reasonably long.
const size_t key_len = Util::CharsLen(result->key);
if (ctype == last_history_ctype &&
((ctype == Util::HIRAGANA && key_len <= 9) ||
(ctype == Util::KATAKANA && key_len <= 5))) {
result->removed = true;
MOZC_WORD_LOG(*result, "Removed. Short Hiragana (<= 9) or Katakana (<= 5)");
return;
}
// The suggested key/value pair must exist in the dictionary.
// For example, we don't want to suggest "ターネット" from
// the history "イン".
// If character type is Kanji and the suggestion is not a
// zero_query_suggestion, we relax this condition, as there are
// many Kanji-compounds which may not in the dictionary. For example,
// we want to suggest "霊長類研究所" from the history "京都大学".
if (ctype == Util::KANJI && Util::CharsLen(value) >= 2) {
// Do not filter this.
// TODO(toshiyuki): one-length kanji prediciton may be annoying other than
// some exceptions, "駅", "口", etc
MOZC_WORD_LOG(*result, "Valid bigram. Kanji suffix (>= 2).");
return;
}
// Check if the word is in the dictionary or not.
// For Hiragana words, check if that word is in a key of values.
// This is for a situation that
// ありがとうございました is not in the dictionary, but
// ありがとう御座いました is in the dictionary.
if (ctype == Util::HIRAGANA) {
if (!dictionary_->HasKey(key)) {
result->removed = true;
MOZC_WORD_LOG(*result, "Removed. No keys are found.");
return;
}
} else {
FindValueCallback callback(value);
dictionary_->LookupPrefix(key, request, &callback);
if (!callback.found()) {
result->removed = true;
MOZC_WORD_LOG(*result, "Removed. No prefix found.");
return;
}
}
MOZC_WORD_LOG(*result, "Valid bigram.");
}
void DictionaryPredictor::GetPredictiveResults(
const DictionaryInterface &dictionary, const std::string &history_key,
const ConversionRequest &request, const Segments &segments,
PredictionTypes types, size_t lookup_limit,
Segment::Candidate::SourceInfo source_info, int unknown_id_,
std::vector<Result> *results) {
if (!request.has_composer()) {
std::string input_key = history_key;
input_key.append(segments.conversion_segment(0).key());
PredictiveLookupCallback callback(types, lookup_limit, input_key.size(),
nullptr, source_info, unknown_id_, "",
GetSpatialCostParams(request), results);
dictionary.LookupPredictive(input_key, request, &callback);
return;
}
// If we have ambiguity for the input, get expanded key.
// Example1 roman input: for "あk", we will get |base|, "あ" and |expanded|,
// "か", "き", etc
// Example2 kana input: for "あか", we will get |base|, "あ" and |expanded|,
// "か", and "が".
std::string base;
std::set<std::string> expanded;
request.composer().GetQueriesForPrediction(&base, &expanded);
std::string input_key;
if (expanded.empty()) {
input_key.assign(history_key).append(base);
PredictiveLookupCallback callback(types, lookup_limit, input_key.size(),
nullptr, source_info, unknown_id_, "",
GetSpatialCostParams(request), results);
dictionary.LookupPredictive(input_key, request, &callback);
return;
}
// `non_expanded_original_key` keeps the original key request before
// key expansions. This key is passed to the callback so that it can
// identify whether the key is actually expanded or not.
const std::string non_expanded_original_key =
IsEnableNewSpatialScoring(request)
? history_key + segments.conversion_segment(0).key()
: "";
// |expanded| is a very small set, so calling LookupPredictive multiple
// times is not so expensive. Also, the number of lookup results is limited
// by |lookup_limit|.
for (const std::string &expanded_char : expanded) {
input_key.assign(history_key).append(base).append(expanded_char);
PredictiveLookupCallback callback(types, lookup_limit, input_key.size(),
nullptr, source_info, unknown_id_,
non_expanded_original_key,
GetSpatialCostParams(request), results);
dictionary.LookupPredictive(input_key, request, &callback);
}
}
void DictionaryPredictor::GetPredictiveResultsForBigram(
const DictionaryInterface &dictionary, const std::string &history_key,
const std::string &history_value, const ConversionRequest &request,
const Segments &segments, PredictionTypes types, size_t lookup_limit,
Segment::Candidate::SourceInfo source_info, int unknown_id_,
std::vector<Result> *results) const {
if (!request.has_composer()) {
std::string input_key = history_key;
input_key.append(segments.conversion_segment(0).key());
PredictiveBigramLookupCallback callback(
types, lookup_limit, input_key.size(), nullptr, history_value,
source_info, unknown_id_, "", GetSpatialCostParams(request), results);
dictionary.LookupPredictive(input_key, request, &callback);
return;
}
// If we have ambiguity for the input, get expanded key.
// Example1 roman input: for "あk", we will get |base|, "あ" and |expanded|,
// "か", "き", etc
// Example2 kana input: for "あか", we will get |base|, "あ" and |expanded|,
// "か", and "が".
std::string base;
std::set<std::string> expanded;
request.composer().GetQueriesForPrediction(&base, &expanded);
const std::string input_key = history_key + base;
const std::string non_expanded_original_key =
IsEnableNewSpatialScoring(request)
? history_key + segments.conversion_segment(0).key()
: "";
PredictiveBigramLookupCallback callback(
types, lookup_limit, input_key.size(),
expanded.empty() ? nullptr : &expanded, history_value, source_info,
unknown_id_, non_expanded_original_key, GetSpatialCostParams(request),
results);
dictionary.LookupPredictive(input_key, request, &callback);
}
void DictionaryPredictor::GetPredictiveResultsForEnglishKey(
const DictionaryInterface &dictionary, const ConversionRequest &request,
const std::string &input_key, PredictionTypes types, size_t lookup_limit,
std::vector<Result> *results) const {
const size_t prev_results_size = results->size();
if (Util::IsUpperAscii(input_key)) {
// For upper case key, look up its lower case version and then transform
// the results to upper case.
std::string key(input_key);
Util::LowerString(&key);
PredictiveLookupCallback callback(types, lookup_limit, key.size(), nullptr,
Segment::Candidate::SOURCE_INFO_NONE,
unknown_id_, "",
GetSpatialCostParams(request), results);
dictionary.LookupPredictive(key, request, &callback);
for (size_t i = prev_results_size; i < results->size(); ++i) {
Util::UpperString(&(*results)[i].value);
}
} else if (Util::IsCapitalizedAscii(input_key)) {
// For capitalized key, look up its lower case version and then transform
// the results to capital.
std::string key(input_key);
Util::LowerString(&key);
PredictiveLookupCallback callback(types, lookup_limit, key.size(), nullptr,
Segment::Candidate::SOURCE_INFO_NONE,
unknown_id_, "",
GetSpatialCostParams(request), results);
dictionary.LookupPredictive(key, request, &callback);
for (size_t i = prev_results_size; i < results->size(); ++i) {
Util::CapitalizeString(&(*results)[i].value);
}
} else {
// For other cases (lower and as-is), just look up directly.
PredictiveLookupCallback callback(
types, lookup_limit, input_key.size(), nullptr,
Segment::Candidate::SOURCE_INFO_NONE, unknown_id_, "",
GetSpatialCostParams(request), results);
dictionary.LookupPredictive(input_key, request, &callback);
}
// If input mode is FULL_ASCII, then convert the results to full-width.
if (request.has_composer() &&
request.composer().GetInputMode() == transliteration::FULL_ASCII) {
std::string tmp;
for (size_t i = prev_results_size; i < results->size(); ++i) {
tmp.assign((*results)[i].value);
japanese_util::HalfWidthAsciiToFullWidthAscii(tmp, &(*results)[i].value);
}
}
}
void DictionaryPredictor::GetPredictiveResultsUsingTypingCorrection(
const DictionaryInterface &dictionary, const std::string &history_key,
const ConversionRequest &request, const Segments &segments,
PredictionTypes types, size_t lookup_limit,
std::vector<Result> *results) const {
if (!request.has_composer()) {
return;
}
std::vector<composer::TypeCorrectedQuery> queries;
request.composer().GetTypeCorrectedQueriesForPrediction(&queries);
for (size_t query_index = 0; query_index < queries.size(); ++query_index) {
const composer::TypeCorrectedQuery &query = queries[query_index];
const std::string input_key = history_key + query.base;
const size_t previous_results_size = results->size();
PredictiveLookupCallback callback(
types, lookup_limit, input_key.size(),
query.expanded.empty() ? nullptr : &query.expanded,
Segment::Candidate::SOURCE_INFO_NONE, unknown_id_, "",
GetSpatialCostParams(request), results);
dictionary.LookupPredictive(input_key, request, &callback);
for (size_t i = previous_results_size; i < results->size(); ++i) {
(*results)[i].wcost += query.cost;
}
lookup_limit -= results->size() - previous_results_size;
if (lookup_limit <= 0) {
break;
}
}
}
// static
bool DictionaryPredictor::GetZeroQueryCandidatesForKey(
const ConversionRequest &request, const std::string &key,
const ZeroQueryDict &dict, std::vector<ZeroQueryResult> *results) {
const int32_t available_emoji_carrier =
request.request().available_emoji_carrier();
DCHECK(results);
results->clear();
auto range = dict.equal_range(key);
if (range.first == range.second) {
return false;
}
for (; range.first != range.second; ++range.first) {
const auto &entry = range.first;
if (entry.type() != ZERO_QUERY_EMOJI) {
results->push_back(
std::make_pair(std::string(entry.value()), entry.type()));
continue;
}
if (available_emoji_carrier & Request::UNICODE_EMOJI &&
entry.emoji_type() & EMOJI_UNICODE) {
results->push_back(
std::make_pair(std::string(entry.value()), entry.type()));
continue;
}
if ((available_emoji_carrier & Request::DOCOMO_EMOJI &&
entry.emoji_type() & EMOJI_DOCOMO) ||
(available_emoji_carrier & Request::SOFTBANK_EMOJI &&
entry.emoji_type() & EMOJI_SOFTBANK) ||
(available_emoji_carrier & Request::KDDI_EMOJI &&
entry.emoji_type() & EMOJI_KDDI)) {
std::string android_pua;
Util::Ucs4ToUtf8(entry.emoji_android_pua(), &android_pua);
results->push_back(std::make_pair(android_pua, entry.type()));
}
}
return !results->empty();
}
// static
void DictionaryPredictor::AppendZeroQueryToResults(
const std::vector<ZeroQueryResult> &candidates, uint16_t lid, uint16_t rid,
std::vector<Result> *results) {
int cost = 0;
for (size_t i = 0; i < candidates.size(); ++i) {
// Increment cost to show the candidates in order.
constexpr int kSuffixPenalty = 10;
results->push_back(Result());
Result *result = &results->back();
result->SetTypesAndTokenAttributes(SUFFIX, Token::NONE);
result->SetSourceInfoForZeroQuery(candidates[i].second);
result->key = candidates[i].first;
result->value = candidates[i].first;
result->wcost = cost;
result->lid = lid;
result->rid = rid;
cost += kSuffixPenalty;
}
}
// Returns true if we add zero query result.
bool DictionaryPredictor::AggregateNumberZeroQueryPrediction(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
std::string number_key;
if (!GetNumberHistory(segments, &number_key)) {
return false;
}
std::vector<ZeroQueryResult> candidates_for_number_key;
GetZeroQueryCandidatesForKey(request, number_key, zero_query_number_dict_,
&candidates_for_number_key);
std::vector<ZeroQueryResult> default_candidates_for_number;
GetZeroQueryCandidatesForKey(request, "default", zero_query_number_dict_,
&default_candidates_for_number);
DCHECK(!default_candidates_for_number.empty());
AppendZeroQueryToResults(candidates_for_number_key, counter_suffix_word_id_,
counter_suffix_word_id_, results);
AppendZeroQueryToResults(default_candidates_for_number,
counter_suffix_word_id_, counter_suffix_word_id_,
results);
return true;
}
// Returns true if we add zero query result.
bool DictionaryPredictor::AggregateZeroQueryPrediction(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
const size_t history_size = segments.history_segments_size();
if (history_size <= 0) {
return false;
}
const Segment &last_segment = segments.history_segment(history_size - 1);
DCHECK_GT(last_segment.candidates_size(), 0);
const std::string &history_value = last_segment.candidate(0).value;
std::vector<ZeroQueryResult> candidates;
if (!GetZeroQueryCandidatesForKey(request, history_value, zero_query_dict_,
&candidates)) {
return false;
}
const uint16_t kId = 0; // EOS
AppendZeroQueryToResults(candidates, kId, kId, results);
return true;
}
void DictionaryPredictor::AggregateSuffixPrediction(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK_GT(segments.conversion_segments_size(), 0);
DCHECK(!segments.conversion_segment(0).key().empty()); // Not zero query
// Uses larger cutoff (kPredictionMaxResultsSize) in order to consider
// all suffix entries.
const size_t cutoff_threshold = kPredictionMaxResultsSize;
const std::string kEmptyHistoryKey = "";
GetPredictiveResults(*suffix_dictionary_, kEmptyHistoryKey, request, segments,
SUFFIX, cutoff_threshold,
Segment::Candidate::SOURCE_INFO_NONE, unknown_id_,
results);
}
void DictionaryPredictor::AggregateZeroQuerySuffixPrediction(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK_GT(segments.conversion_segments_size(), 0);
DCHECK(segments.conversion_segment(0).key().empty());
if (AggregateNumberZeroQueryPrediction(request, segments, results)) {
return;
}
AggregateZeroQueryPrediction(request, segments, results);
if (IsLatinInputMode(request)) {
// We do not want zero query results from suffix dictionary for Latin
// input mode. For example, we do not need "です", "。" just after "when".
return;
}
// Uses larger cutoff (kPredictionMaxResultsSize) in order to consider
// all suffix entries.
const size_t cutoff_threshold = kPredictionMaxResultsSize;
const std::string kEmptyHistoryKey = "";
GetPredictiveResults(
*suffix_dictionary_, kEmptyHistoryKey, request, segments, SUFFIX,
cutoff_threshold,
Segment::Candidate::DICTIONARY_PREDICTOR_ZERO_QUERY_SUFFIX, unknown_id_,
results);
}
void DictionaryPredictor::AggregateEnglishPrediction(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK(results);
DCHECK(dictionary_);
const size_t cutoff_threshold = GetCandidateCutoffThreshold(segments);
const size_t prev_results_size = results->size();
const std::string &input_key = segments.conversion_segment(0).key();
GetPredictiveResultsForEnglishKey(*dictionary_, request, input_key, ENGLISH,
cutoff_threshold, results);
size_t unigram_results_size = results->size() - prev_results_size;
if (unigram_results_size >= cutoff_threshold) {
results->resize(prev_results_size);
return;
}
}
void DictionaryPredictor::AggregateEnglishPredictionUsingRawInput(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK(results);
DCHECK(dictionary_);
if (!request.has_composer()) {
return;
}
const size_t cutoff_threshold = GetCandidateCutoffThreshold(segments);
const size_t prev_results_size = results->size();
std::string input_key;
request.composer().GetRawString(&input_key);
GetPredictiveResultsForEnglishKey(*dictionary_, request, input_key, ENGLISH,
cutoff_threshold, results);
size_t unigram_results_size = results->size() - prev_results_size;
if (unigram_results_size >= cutoff_threshold) {
results->resize(prev_results_size);
return;
}
}
void DictionaryPredictor::AggregateTypeCorrectingPrediction(
const ConversionRequest &request, const Segments &segments,
std::vector<Result> *results) const {
DCHECK(results);
DCHECK(dictionary_);
const size_t prev_results_size = results->size();
if (prev_results_size > 10000) {
return;
}
const size_t cutoff_threshold = GetCandidateCutoffThreshold(segments);
// Currently, history key is never utilized.
const std::string kEmptyHistoryKey = "";
GetPredictiveResultsUsingTypingCorrection(
*dictionary_, kEmptyHistoryKey, request, segments, TYPING_CORRECTION,
cutoff_threshold, results);
if (results->size() - prev_results_size >= cutoff_threshold) {
results->resize(prev_results_size);
return;
}
}
bool DictionaryPredictor::ShouldAggregateRealTimeConversionResults(
const ConversionRequest &request, const Segments &segments) {
constexpr size_t kMaxRealtimeKeySize = 300; // 300 bytes in UTF8
const std::string &key = segments.conversion_segment(0).key();
if (key.empty() || key.size() >= kMaxRealtimeKeySize) {
// 1) If key is empty, realtime conversion doesn't work.
// 2) If the key is too long, we'll hit a performance issue.
return false;
}
return (segments.request_type() == Segments::PARTIAL_SUGGESTION ||
request.config().use_realtime_conversion() ||
IsMixedConversionEnabled(request.request()));
}
bool DictionaryPredictor::IsZipCodeRequest(const std::string &key) {
if (key.empty()) {
return false;
}
for (ConstChar32Iterator iter(key); !iter.Done(); iter.Next()) {
const char32 c = iter.Get();
if (!('0' <= c && c <= '9') && (c != '-')) {
return false;
}
}
return true;
}
} // namespace mozc
#undef MOZC_WORD_LOG_MESSAGE
#undef MOZC_WORD_LOG
| fcitx/mozc | src/prediction/dictionary_predictor.cc | C++ | bsd-3-clause | 88,483 |
//===-- HostThreadMacOSX.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef lldb_Host_macosx_HostThreadMacOSX_h_
#define lldb_Host_macosx_HostThreadMacOSX_h_
#include "lldb/Host/posix/HostThreadPosix.h"
namespace lldb_private {
class HostThreadMacOSX : public HostThreadPosix {
friend class ThreadLauncher;
public:
HostThreadMacOSX();
HostThreadMacOSX(lldb::thread_t thread);
protected:
static lldb::thread_result_t ThreadCreateTrampoline(lldb::thread_arg_t arg);
};
}
#endif
| youtube/cobalt | third_party/llvm-project/lldb/include/lldb/Host/macosx/HostThreadMacOSX.h | C | bsd-3-clause | 764 |
'use strict';
angular.module('shopnxApp')
.config(function ($stateProvider) {
$stateProvider
.state('checkout', {
title: 'Checkout with the items you selected',
url: '/checkout',
templateUrl: 'app/checkout/checkout.html',
controller: 'CheckoutCtrl',
authenticate: true
});
});
| kinddevil/shop | client/app/checkout/checkout.js | JavaScript | bsd-3-clause | 338 |
package org.hisp.dhis.email;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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.
*/
/**
* @author Zubair <rajazubair.asghar@gmail.com>
*/
public enum EmailResponse
{
SENT( "success" ),
FAILED( "failed" ),
ABORTED( "aborted" ),
NOT_CONFIGURED( "no configuration found" );
private String responseMessage;
EmailResponse( String responseMessage )
{
this.responseMessage = responseMessage;
}
public String getResponseMessage()
{
return responseMessage;
}
public void setResponseMessage( String responseMessage )
{
this.responseMessage = responseMessage;
}
}
| vietnguyen/dhis2-core | dhis-2/dhis-api/src/main/java/org/hisp/dhis/email/EmailResponse.java | Java | bsd-3-clause | 2,144 |
package cromwell.core.callcaching
import org.scalatest.{FlatSpec, Matchers}
class HashKeySpec extends FlatSpec with Matchers {
"HashKey" should "produce consistent key value" in {
val keys = Set(
HashKey("command template"),
HashKey("backend name"),
HashKey("input count"),
HashKey("output count"),
HashKey("runtime attribute", "failOnStderr"),
HashKey(checkForHitOrMiss = false, "runtime attribute", "cpu"),
HashKey("runtime attribute", "continueOnReturnCode"),
HashKey("input", "String stringInput"),
HashKey("output", "String myOutput"),
HashKey("runtime attribute", "docker")
)
keys map { _.key } should contain theSameElementsAs Set(
"command template",
"backend name",
"input count",
"output count",
"runtime attribute: failOnStderr",
"runtime attribute: cpu",
"runtime attribute: continueOnReturnCode",
"input: String stringInput",
"output: String myOutput",
"runtime attribute: docker"
)
}
}
| ohsu-comp-bio/cromwell | core/src/test/scala/cromwell/core/callcaching/HashKeySpec.scala | Scala | bsd-3-clause | 1,051 |
/**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2009, University of Technology, Sydney
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney 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.
*
* @author Tania Machet (tmachet)
* @date 13 December 2010
*/
package au.edu.uts.eng.remotelabs.schedserver.reports.intf.types;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.axiom.om.OMConstants;
import org.apache.axiom.om.OMDataSource;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.llom.OMSourcedElementImpl;
import org.apache.axis2.databinding.ADBBean;
import org.apache.axis2.databinding.ADBDataSource;
import org.apache.axis2.databinding.ADBException;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl;
import org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter;
/**
* QuerySessionReportType bean class.
*/
public class QuerySessionReportType implements ADBBean
{
/*
* This type was generated from the piece of schema that had
* name = QuerySessionReportType
* Namespace URI = http://remotelabs.eng.uts.edu.au/schedserver/reports
* Namespace Prefix = ns1
*/
private static final long serialVersionUID = -5121246029757741056L;
private static String generatePrefix(final String namespace)
{
if (namespace.equals("http://remotelabs.eng.uts.edu.au/schedserver/reports"))
{
return "ns1";
}
return BeanUtil.getUniquePrefix();
}
protected RequestorType requestor;
public RequestorType getRequestor()
{
return this.requestor;
}
public void setRequestor(final RequestorType param)
{
this.requestor = param;
}
protected QueryFilterType querySelect;
public QueryFilterType getQuerySelect()
{
return this.querySelect;
}
public void setQuerySelect(final QueryFilterType param)
{
this.querySelect = param;
}
protected QueryFilterType queryConstraints;
protected boolean queryConstraintsTracker = false;
public QueryFilterType getQueryConstraints()
{
return this.queryConstraints;
}
public void setQueryConstraints(final QueryFilterType param)
{
this.queryConstraints = param;
this.queryConstraintsTracker = param != null;
}
protected Calendar startTime;
protected boolean startTimeTracker = false;
public Calendar getStartTime()
{
return this.startTime;
}
public void setStartTime(final Calendar param)
{
this.startTime = param;
this.startTimeTracker = param != null;
}
protected Calendar endTime;
protected boolean endTimeTracker = false;
public Calendar getEndTime()
{
return this.endTime;
}
public void setEndTime(final Calendar param)
{
this.endTime = param;
this.endTimeTracker = param != null;
}
protected PaginationType pagination;
protected boolean paginationTracker = false;
public PaginationType getPagination()
{
return this.pagination;
}
public void setPagination(final PaginationType param)
{
this.pagination = param;
this.paginationTracker = param != null;
}
public static boolean isReaderMTOMAware(final XMLStreamReader reader)
{
boolean isReaderMTOMAware = false;
try
{
isReaderMTOMAware = Boolean.TRUE.equals(reader.getProperty(OMConstants.IS_DATA_HANDLERS_AWARE));
}
catch (final IllegalArgumentException e)
{
isReaderMTOMAware = false;
}
return isReaderMTOMAware;
}
public OMElement getOMElement(final QName parentQName, final OMFactory factory) throws ADBException
{
final OMDataSource dataSource = new ADBDataSource(this, parentQName)
{
@Override
public void serialize(final MTOMAwareXMLStreamWriter xmlWriter) throws XMLStreamException
{
QuerySessionReportType.this.serialize(this.parentQName, factory, xmlWriter);
}
};
return new OMSourcedElementImpl(parentQName, factory, dataSource);
}
@Override
public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter)
throws XMLStreamException, ADBException
{
this.serialize(parentQName, factory, xmlWriter, false);
}
@Override
public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter,
final boolean serializeType) throws XMLStreamException, ADBException
{
String prefix = parentQName.getPrefix();
String namespace = parentQName.getNamespaceURI();
if ((namespace != null) && (namespace.trim().length() > 0))
{
final String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null)
{
xmlWriter.writeStartElement(namespace, parentQName.getLocalPart());
}
else
{
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
else
{
xmlWriter.writeStartElement(parentQName.getLocalPart());
}
if (serializeType)
{
final String namespacePrefix = this.registerPrefix(xmlWriter,
"http://remotelabs.eng.uts.edu.au/schedserver/reports");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0))
{
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix
+ ":QuerySessionReportType", xmlWriter);
}
else
{
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type",
"QuerySessionReportType", xmlWriter);
}
}
if (this.requestor == null)
{
throw new ADBException("requestor cannot be null!!");
}
this.requestor.serialize(new QName("", "requestor"), factory, xmlWriter);
if (this.querySelect == null)
{
throw new ADBException("querySelect cannot be null!!");
}
this.querySelect.serialize(new QName("", "querySelect"), factory, xmlWriter);
if (this.queryConstraintsTracker)
{
if (this.queryConstraints == null)
{
throw new ADBException("queryConstraints cannot be null!!");
}
this.queryConstraints.serialize(new QName("", "queryConstraints"), factory, xmlWriter);
}
if (this.startTimeTracker)
{
namespace = "";
if (!namespace.equals(""))
{
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
xmlWriter.writeStartElement(prefix, "startTime", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
else
{
xmlWriter.writeStartElement(namespace, "startTime");
}
}
else
{
xmlWriter.writeStartElement("startTime");
}
if (this.startTime == null)
{
throw new ADBException("startTime cannot be null!!");
}
else
{
xmlWriter.writeCharacters(ConverterUtil.convertToString(this.startTime));
}
xmlWriter.writeEndElement();
}
if (this.endTimeTracker)
{
namespace = "";
if (!namespace.equals(""))
{
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
xmlWriter.writeStartElement(prefix, "endTime", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
else
{
xmlWriter.writeStartElement(namespace, "endTime");
}
}
else
{
xmlWriter.writeStartElement("endTime");
}
if (this.endTime == null)
{
throw new ADBException("endTime cannot be null!!");
}
else
{
xmlWriter.writeCharacters(ConverterUtil.convertToString(this.endTime));
}
xmlWriter.writeEndElement();
}
if (this.paginationTracker)
{
if (this.pagination == null)
{
throw new ADBException("pagination cannot be null!!");
}
this.pagination.serialize(new QName("", "pagination"), factory, xmlWriter);
}
xmlWriter.writeEndElement();
}
private void writeAttribute(final String prefix, final String namespace, final String attName,
final String attValue, final XMLStreamWriter xmlWriter) throws XMLStreamException
{
if (xmlWriter.getPrefix(namespace) == null)
{
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
private String registerPrefix(final XMLStreamWriter xmlWriter, final String namespace) throws XMLStreamException
{
String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null)
{
prefix = BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
@Override
public XMLStreamReader getPullParser(final QName qName) throws ADBException
{
final ArrayList<Serializable> elementList = new ArrayList<Serializable>();
elementList.add(new QName("", "requestor"));
if (this.requestor == null)
{
throw new ADBException("requestor cannot be null!!");
}
elementList.add(this.requestor);
elementList.add(new QName("", "querySelect"));
if (this.querySelect == null)
{
throw new ADBException("querySelect cannot be null!!");
}
elementList.add(this.querySelect);
if (this.queryConstraintsTracker)
{
elementList.add(new QName("", "queryConstraints"));
if (this.queryConstraints == null)
{
throw new ADBException("queryConstraints cannot be null!!");
}
elementList.add(this.queryConstraints);
}
if (this.startTimeTracker)
{
elementList.add(new QName("", "startTime"));
if (this.startTime != null)
{
elementList.add(ConverterUtil.convertToString(this.startTime));
}
else
{
throw new ADBException("startTime cannot be null!!");
}
}
if (this.endTimeTracker)
{
elementList.add(new QName("", "endTime"));
if (this.endTime != null)
{
elementList.add(ConverterUtil.convertToString(this.endTime));
}
else
{
throw new ADBException("endTime cannot be null!!");
}
}
if (this.paginationTracker)
{
elementList.add(new QName("", "pagination"));
if (this.pagination == null)
{
throw new ADBException("pagination cannot be null!!");
}
elementList.add(this.pagination);
}
return new ADBXMLStreamReaderImpl(qName, elementList.toArray(), new Object[0]);
}
public static class Factory
{
public static QuerySessionReportType parse(final XMLStreamReader reader) throws Exception
{
final QuerySessionReportType object = new QuerySessionReportType();
try
{
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null)
{
final String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName != null)
{
String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1)
{
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix == null ? "" : nsPrefix;
final String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"QuerySessionReportType".equals(type))
{
final String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (QuerySessionReportType) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
reader.next();
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "requestor").equals(reader.getName()))
{
object.setRequestor(RequestorType.Factory.parse(reader));
reader.next();
}
else
{
throw new ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "querySelect").equals(reader.getName()))
{
object.setQuerySelect(QueryFilterType.Factory.parse(reader));
reader.next();
}
else
{
throw new ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "queryConstraints").equals(reader.getName()))
{
object.setQueryConstraints(QueryFilterType.Factory.parse(reader));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "startTime").equals(reader.getName()))
{
final String content = reader.getElementText();
object.setStartTime(ConverterUtil.convertToDateTime(content));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "endTime").equals(reader.getName()))
{
final String content = reader.getElementText();
object.setEndTime(ConverterUtil.convertToDateTime(content));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "pagination").equals(reader.getName()))
{
object.setPagination(PaginationType.Factory.parse(reader));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement())
{
throw new ADBException("Unexpected subelement " + reader.getLocalName());
}
}
catch (final XMLStreamException e)
{
throw new Exception(e);
}
return object;
}
}
}
| jeking3/scheduling-server | Reports/src/au/edu/uts/eng/remotelabs/schedserver/reports/intf/types/QuerySessionReportType.java | Java | bsd-3-clause | 20,256 |
/**
* Copyright (c) 2016, The National Archives <pronom@nationalarchives.gsi.gov.uk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives 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.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.03.22 at 11:40:59 AM GMT
//
package uk.gov.nationalarchives.droid.report.planets.domain;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for YearItemType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="YearItemType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="year" type="{http://www.w3.org/2001/XMLSchema}gYear"/>
* <element name="numFiles" type="{http://www.w3.org/2001/XMLSchema}integer"/>
* <element name="totalFileSize" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
* @deprecated PLANETS XML is now generated using XSLT over normal report xml files.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "YearItemType", propOrder = {
"year",
"numFiles",
"totalFileSize"
})
@Deprecated
public class YearItemType {
@XmlElement(required = true)
@XmlSchemaType(name = "gYear")
protected XMLGregorianCalendar year;
@XmlElement(required = true)
protected BigInteger numFiles;
@XmlElement(required = true)
protected BigDecimal totalFileSize;
/**
* Gets the value of the year property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getYear() {
return year;
}
/**
* Sets the value of the year property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setYear(XMLGregorianCalendar value) {
this.year = value;
}
/**
* Gets the value of the numFiles property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumFiles() {
return numFiles;
}
/**
* Sets the value of the numFiles property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumFiles(BigInteger value) {
this.numFiles = value;
}
/**
* Gets the value of the totalFileSize property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getTotalFileSize() {
return totalFileSize;
}
/**
* Sets the value of the totalFileSize property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setTotalFileSize(BigDecimal value) {
this.totalFileSize = value;
}
}
| snail1966/droid | droid-report/src/main/java/uk/gov/nationalarchives/droid/report/planets/domain/YearItemType.java | Java | bsd-3-clause | 5,288 |
/**
* Copyright (c) 2016, The National Archives <pronom@nationalarchives.gsi.gov.uk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives 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.
*/
package uk.gov.nationalarchives.droid.command.action;
import java.io.PrintWriter;
import java.util.Map;
import uk.gov.nationalarchives.droid.command.i18n.I18N;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileException;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileInfo;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureManager;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureType;
/**
* @author rflitcroft
*
*/
public class DisplayDefaultSignatureFileVersionCommand implements DroidCommand {
private PrintWriter printWriter;
private SignatureManager signatureManager;
/**
* {@inheritDoc}
*/
@Override
public void execute() throws CommandExecutionException {
try {
Map<SignatureType, SignatureFileInfo> sigFileInfos = signatureManager.getDefaultSignatures();
for (SignatureFileInfo info : sigFileInfos.values()) {
printWriter.println(I18N.getResource(I18N.DEFAULT_SIGNATURE_VERSION,
info.getType(), info.getVersion(), info.getFile().getName()));
}
} catch (SignatureFileException e) {
throw new CommandExecutionException(e);
}
}
/**
* @param printWriter the printWriter to set
*/
public void setPrintWriter(PrintWriter printWriter) {
this.printWriter = printWriter;
}
/**
* @param signatureManager the signatureManager to set
*/
public void setSignatureManager(SignatureManager signatureManager) {
this.signatureManager = signatureManager;
}
}
| snail1966/droid | droid-command-line/src/main/java/uk/gov/nationalarchives/droid/command/action/DisplayDefaultSignatureFileVersionCommand.java | Java | bsd-3-clause | 3,404 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_calloc_52c.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-52c.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: calloc Allocate data using calloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_calloc_52
{
#ifndef OMITBAD
void badSink_c(int64_t * data)
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(int64_t * data)
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink_c(int64_t * data)
{
/* FIX: Deallocate the memory using free() */
free(data);
}
#endif /* OMITGOOD */
} /* close namespace */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_calloc_52c.cpp | C++ | bsd-3-clause | 1,553 |
# ###########################################################################
#
# $Id: Makefile,v 1.3 2008/03/26 16:35:00 cnepveu Exp $
#
# Copyright (c) 2007 Hexago Inc. All rights reserved.
#
# For license information refer to CLIENT-LICENSE.TXT
#
# Description: Makefile for module library gw6c-pal
# (Gateway6 Client Platform Abstraction Layer)
#
# Author: Charles Nepveu
#
# Date: August 2007
#
# ###########################################################################
#
#
# Target directory definition.
#
linux_CDIR=common unix-common
freebsd_CDIR=common unix-common
openbsd_CDIR=common unix-common
netbsd_CDIR=common unix-common netbsd
darwin_CDIR=common unix-common
sunos_CDIR=common unix-common
dongle6_CDIR=common unix-common
#
# ###########################################################################
#
.PHONY: env-check platform-obj platform-inc
# This makefile target will check the execution context and environment.
#
env-check:
@[ -n "${PLATFORM}" ] || { echo "Error: Invalid environment." ; exit 1 ; }
@[ -n "${PLATFORM_DIR}" ] || { echo "Error: Invalid environment." ; exit 1 ; }
@[ -n "${OBJS_DIR}" ] || { echo "Error: Invalid environment." ; exit 1 ; }
@[ -n "${DEFS_DIR}" ] || { echo "Error: Invalid environment." ; exit 1 ; }
@[ -n "${OUT_INC_DIR}" ] || { echo "Error: Invalid environment." ; exit 1 ; }
# This makefile target will compile the platform PAL objects.
#
platform-obj: env-check
@for dir in $(${PLATFORM}_CDIR) ; do \
$(MAKE) -C $$dir platform-obj ; \
done
# This makefile target will copy the platform includes to out_inc.
#
platform-inc: env-check
@for dir in $(${PLATFORM}_CDIR) ; do \
$(MAKE) -C $$dir platform-inc ; \
done
#
# ###########################################################################
| kevinmark/gw6c-6_0_1 | gw6c-pal/platform/Makefile | Makefile | bsd-3-clause | 1,805 |
/*
* Copyright (c) 2010-2011 Mark Allen.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.restfb;
import static com.restfb.json.JsonObject.NULL;
import static com.restfb.util.ReflectionUtils.findFieldsWithAnnotation;
import static com.restfb.util.ReflectionUtils.getFirstParameterizedTypeArgument;
import static com.restfb.util.ReflectionUtils.isPrimitive;
import static com.restfb.util.StringUtils.isBlank;
import static com.restfb.util.StringUtils.trimToEmpty;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableSet;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.FINEST;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import com.restfb.exception.FacebookJsonMappingException;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonException;
import com.restfb.json.JsonObject;
import com.restfb.types.Post.Comments;
import com.restfb.util.ReflectionUtils.FieldWithAnnotation;
/**
* Default implementation of a JSON-to-Java mapper.
*
* @author <a href="http://restfb.com">Mark Allen</a>
*/
public class DefaultJsonMapper implements JsonMapper {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger(DefaultJsonMapper.class.getName());
/**
* @see com.restfb.JsonMapper#toJavaList(String, Class)
*/
@Override
public <T> List<T> toJavaList(String json, Class<T> type) {
json = trimToEmpty(json);
if (isBlank(json))
throw new FacebookJsonMappingException("JSON is an empty string - can't map it.");
if (type == null)
throw new FacebookJsonMappingException("You must specify the Java type to map to.");
if (json.startsWith("{")) {
// Sometimes Facebook returns the empty object {} when it really should be
// returning an empty list [] (example: do an FQL query for a user's
// affiliations - it's a list except when there are none, then it turns
// into an object). Check for that special case here.
if (isEmptyObject(json)) {
if (logger.isLoggable(FINER))
logger.finer("Encountered {} when we should've seen []. "
+ "Mapping the {} as an empty list and moving on...");
return new ArrayList<T>();
}
// Special case: if the only element of this object is an array called
// "data", then treat it as a list. The Graph API uses this convention for
// connections and in a few other places, e.g. comments on the Post
// object.
// Doing this simplifies mapping, so we don't have to worry about having a
// little placeholder object that only has a "data" value.
try {
JsonObject jsonObject = new JsonObject(json);
String[] fieldNames = JsonObject.getNames(jsonObject);
if (fieldNames != null) {
boolean hasSingleDataProperty = fieldNames.length == 1 && "data".equals(fieldNames[0]);
Object jsonDataObject = jsonObject.get("data");
if (!hasSingleDataProperty && !(jsonDataObject instanceof JsonArray))
throw new FacebookJsonMappingException("JSON is an object but is being mapped as a list "
+ "instead. Offending JSON is '" + json + "'.");
json = jsonDataObject.toString();
}
} catch (JsonException e) {
// Should never get here, but just in case...
throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of "
+ type.getName() + " instances. Offending JSON is " + json, e);
}
}
try {
List<T> list = new ArrayList<T>();
JsonArray jsonArray = new JsonArray(json);
for (int i = 0; i < jsonArray.length(); i++)
list.add(toJavaObject(jsonArray.get(i).toString(), type));
return unmodifiableList(list);
} catch (FacebookJsonMappingException e) {
throw e;
} catch (Exception e) {
throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of "
+ type.getName() + " instances", e);
}
}
/**
* @see com.restfb.JsonMapper#toJavaObject(String, Class)
*/
@Override
@SuppressWarnings("unchecked")
public <T> T toJavaObject(String json, Class<T> type) {
verifyThatJsonIsOfObjectType(json);
try {
// Are we asked to map to JsonObject? If so, short-circuit right away.
if (type.equals(JsonObject.class))
return (T) new JsonObject(json);
List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation = findFieldsWithAnnotation(type, Facebook.class);
Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);
// If there are no annotated fields, assume we're mapping to a built-in
// type. If this is actually the empty object, just return a new instance
// of the corresponding Java type.
if (fieldsWithAnnotation.size() == 0)
if (isEmptyObject(json))
return createInstance(type);
else
return toPrimitiveJavaType(json, type);
// Facebook will sometimes return the string "null".
// Check for that and bail early if we find it.
if ("null".equals(json))
return null;
// Facebook will sometimes return the string "false" to mean null.
// Check for that and bail early if we find it.
if ("false".equals(json)) {
if (logger.isLoggable(FINE))
logger.fine("Encountered 'false' from Facebook when trying to map to " + type.getSimpleName()
+ " - mapping null instead.");
return null;
}
JsonObject jsonObject = new JsonObject(json);
T instance = createInstance(type);
if (instance instanceof JsonObject)
return (T) jsonObject;
// For each Facebook-annotated field on the current Java object, pull data
// out of the JSON object and put it in the Java object
for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);
if (!jsonObject.has(facebookFieldName)) {
if (logger.isLoggable(FINER))
logger.finer("No JSON value present for '" + facebookFieldName + "', skipping. JSON is '" + json + "'.");
continue;
}
fieldWithAnnotation.getField().setAccessible(true);
// Set the Java field's value.
//
// If we notice that this Facebook field name is mapped more than once,
// go into a special mode where we swallow any exceptions that occur
// when mapping to the Java field. This is because Facebook will
// sometimes return data in different formats for the same field name.
// See issues 56 and 90 for examples of this behavior and discussion.
if (facebookFieldNamesWithMultipleMappings.contains(facebookFieldName)) {
try {
fieldWithAnnotation.getField()
.set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName));
} catch (FacebookJsonMappingException e) {
logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json);
} catch (JsonException e) {
logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json);
}
} else {
fieldWithAnnotation.getField().set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName));
}
}
return instance;
} catch (FacebookJsonMappingException e) {
throw e;
} catch (Exception e) {
throw new FacebookJsonMappingException("Unable to map JSON to Java. Offending JSON is '" + json + "'.", e);
}
}
/**
* Dumps out a log message when one of a multiple-mapped Facebook field name
* JSON-to-Java mapping operation fails.
*
* @param facebookFieldName
* The Facebook field name.
* @param fieldWithAnnotation
* The Java field to map to and its annotation.
* @param json
* The JSON that failed to map to the Java field.
*/
protected void logMultipleMappingFailedForField(String facebookFieldName,
FieldWithAnnotation<Facebook> fieldWithAnnotation, String json) {
if (!logger.isLoggable(FINER))
return;
Field field = fieldWithAnnotation.getField();
if (logger.isLoggable(FINER))
logger.finer("Could not map '" + facebookFieldName + "' to " + field.getDeclaringClass().getSimpleName() + "."
+ field.getName() + ", but continuing on because '" + facebookFieldName
+ "' is mapped to multiple fields in " + field.getDeclaringClass().getSimpleName() + ". JSON is " + json);
}
/**
* For a Java field annotated with the {@code Facebook} annotation, figure out
* what the corresponding Facebook JSON field name to map to it is.
*
* @param fieldWithAnnotation
* A Java field annotated with the {@code Facebook} annotation.
* @return The Facebook JSON field name that should be mapped to this Java
* field.
*/
protected String getFacebookFieldName(FieldWithAnnotation<Facebook> fieldWithAnnotation) {
String facebookFieldName = fieldWithAnnotation.getAnnotation().value();
Field field = fieldWithAnnotation.getField();
// If no Facebook field name was specified in the annotation, assume
// it's the same name as the Java field
if (isBlank(facebookFieldName)) {
if (logger.isLoggable(FINEST))
logger.finest("No explicit Facebook field name found for " + field
+ ", so defaulting to the field name itself (" + field.getName() + ")");
facebookFieldName = field.getName();
}
return facebookFieldName;
}
/**
* Finds any Facebook JSON fields that are mapped to more than 1 Java field.
*
* @param fieldsWithAnnotation
* Java fields annotated with the {@code Facebook} annotation.
* @return Any Facebook JSON fields that are mapped to more than 1 Java field.
*/
protected Set<String> facebookFieldNamesWithMultipleMappings(List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation) {
Map<String, Integer> facebookFieldsNamesWithOccurrenceCount = new HashMap<String, Integer>();
Set<String> facebookFieldNamesWithMultipleMappings = new HashSet<String>();
// Get a count of Facebook field name occurrences for each
// @Facebook-annotated field
for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
String fieldName = getFacebookFieldName(fieldWithAnnotation);
int occurrenceCount =
facebookFieldsNamesWithOccurrenceCount.containsKey(fieldName) ? facebookFieldsNamesWithOccurrenceCount
.get(fieldName) : 0;
facebookFieldsNamesWithOccurrenceCount.put(fieldName, occurrenceCount + 1);
}
// Pull out only those field names with multiple mappings
for (Entry<String, Integer> entry : facebookFieldsNamesWithOccurrenceCount.entrySet())
if (entry.getValue() > 1)
facebookFieldNamesWithMultipleMappings.add(entry.getKey());
return unmodifiableSet(facebookFieldNamesWithMultipleMappings);
}
/**
* @see com.restfb.JsonMapper#toJson(Object)
*/
@Override
public String toJson(Object object) {
// Delegate to recursive method
return toJsonInternal(object).toString();
}
/**
* Is the given {@code json} a valid JSON object?
*
* @param json
* The JSON to check.
* @throws FacebookJsonMappingException
* If {@code json} is not a valid JSON object.
*/
protected void verifyThatJsonIsOfObjectType(String json) {
if (isBlank(json))
throw new FacebookJsonMappingException("JSON is an empty string - can't map it.");
if (json.startsWith("["))
throw new FacebookJsonMappingException("JSON is an array but is being mapped as an object "
+ "- you should map it as a List instead. Offending JSON is '" + json + "'.");
}
/**
* Recursively marshal the given {@code object} to JSON.
* <p>
* Used by {@link #toJson(Object)}.
*
* @param object
* The object to marshal.
* @return JSON representation of the given {@code object}.
* @throws FacebookJsonMappingException
* If an error occurs while marshaling to JSON.
*/
protected Object toJsonInternal(Object object) {
if (object == null)
return NULL;
if (object instanceof List<?>) {
JsonArray jsonArray = new JsonArray();
for (Object o : (List<?>) object)
jsonArray.put(toJsonInternal(o));
return jsonArray;
}
if (object instanceof Map<?, ?>) {
JsonObject jsonObject = new JsonObject();
for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
if (!(entry.getKey() instanceof String))
throw new FacebookJsonMappingException("Your Map keys must be of type " + String.class
+ " in order to be converted to JSON. Offending map is " + object);
try {
jsonObject.put((String) entry.getKey(), toJsonInternal(entry.getValue()));
} catch (JsonException e) {
throw new FacebookJsonMappingException("Unable to process value '" + entry.getValue() + "' for key '"
+ entry.getKey() + "' in Map " + object, e);
}
}
return jsonObject;
}
if (isPrimitive(object))
return object;
if (object instanceof BigInteger)
return ((BigInteger) object).longValue();
if (object instanceof BigDecimal)
return ((BigDecimal) object).doubleValue();
// We've passed the special-case bits, so let's try to marshal this as a
// plain old Javabean...
List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation =
findFieldsWithAnnotation(object.getClass(), Facebook.class);
JsonObject jsonObject = new JsonObject();
Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);
if (facebookFieldNamesWithMultipleMappings.size() > 0)
throw new FacebookJsonMappingException("Unable to convert to JSON because multiple @"
+ Facebook.class.getSimpleName() + " annotations for the same name are present: "
+ facebookFieldNamesWithMultipleMappings);
for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);
fieldWithAnnotation.getField().setAccessible(true);
try {
jsonObject.put(facebookFieldName, toJsonInternal(fieldWithAnnotation.getField().get(object)));
} catch (Exception e) {
throw new FacebookJsonMappingException("Unable to process field '" + facebookFieldName + "' for "
+ object.getClass(), e);
}
}
return jsonObject;
}
/**
* Given a {@code json} value of something like {@code MyValue} or {@code 123}
* , return a representation of that value of type {@code type}.
* <p>
* This is to support non-legal JSON served up by Facebook for API calls like
* {@code Friends.get} (example result: {@code [222333,1240079]}).
*
* @param <T>
* The Java type to map to.
* @param json
* The non-legal JSON to map to the Java type.
* @param type
* Type token.
* @return Java representation of {@code json}.
* @throws FacebookJsonMappingException
* If an error occurs while mapping JSON to Java.
*/
@SuppressWarnings("unchecked")
protected <T> T toPrimitiveJavaType(String json, Class<T> type) {
if (String.class.equals(type)) {
// If the string starts and ends with quotes, remove them, since Facebook
// can serve up strings surrounded by quotes.
if (json.length() > 1 && json.startsWith("\"") && json.endsWith("\"")) {
json = json.replaceFirst("\"", "");
json = json.substring(0, json.length() - 1);
}
return (T) json;
}
if (Integer.class.equals(type) || Integer.TYPE.equals(type))
return (T) new Integer(json);
if (Boolean.class.equals(type) || Boolean.TYPE.equals(type))
return (T) new Boolean(json);
if (Long.class.equals(type) || Long.TYPE.equals(type))
return (T) new Long(json);
if (Double.class.equals(type) || Double.TYPE.equals(type))
return (T) new Double(json);
if (Float.class.equals(type) || Float.TYPE.equals(type))
return (T) new Float(json);
if (BigInteger.class.equals(type))
return (T) new BigInteger(json);
if (BigDecimal.class.equals(type))
return (T) new BigDecimal(json);
throw new FacebookJsonMappingException("Don't know how to map JSON to " + type
+ ". Are you sure you're mapping to the right class? " + "Offending JSON is '" + json + "'.");
}
/**
* Extracts JSON data for a field according to its {@code Facebook} annotation
* and returns it converted to the proper Java type.
*
* @param fieldWithAnnotation
* The field/annotation pair which specifies what Java type to
* convert to.
* @param jsonObject
* "Raw" JSON object to pull data from.
* @param facebookFieldName
* Specifies what JSON field to pull "raw" data from.
* @return A
* @throws JsonException
* If an error occurs while mapping JSON to Java.
* @throws FacebookJsonMappingException
* If an error occurs while mapping JSON to Java.
*/
protected Object toJavaType(FieldWithAnnotation<Facebook> fieldWithAnnotation, JsonObject jsonObject,
String facebookFieldName) throws JsonException, FacebookJsonMappingException {
Class<?> type = fieldWithAnnotation.getField().getType();
Object rawValue = jsonObject.get(facebookFieldName);
// Short-circuit right off the bat if we've got a null value.
if (NULL.equals(rawValue))
return null;
if (String.class.equals(type)) {
// Special handling here for better error checking.
// Since JsonObject.getString() will return literal JSON text even if it's
// _not_ a JSON string, we check the marshaled type and bail if needed.
// For example, calling JsonObject.getString("results") on the below
// JSON...
// {"results":[{"name":"Mark Allen"}]}
// ... would return the string "[{"name":"Mark Allen"}]" instead of
// throwing an error. So we throw the error ourselves.
// Per Antonello Naccarato, sometimes FB will return an empty JSON array
// instead of an empty string. Look for that here.
if (rawValue instanceof JsonArray)
if (((JsonArray) rawValue).length() == 0) {
if (logger.isLoggable(FINER))
logger.finer("Coercing an empty JSON array " + "to an empty string for " + fieldWithAnnotation);
return "";
}
// If the user wants a string, _always_ give her a string.
// This is useful if, for example, you've got a @Facebook-annotated string
// field that you'd like to have a numeric type shoved into.
// User beware: this will turn *anything* into a string, which might lead
// to results you don't expect.
return rawValue.toString();
}
if (Integer.class.equals(type) || Integer.TYPE.equals(type))
return new Integer(jsonObject.getInt(facebookFieldName));
if (Boolean.class.equals(type) || Boolean.TYPE.equals(type))
return new Boolean(jsonObject.getBoolean(facebookFieldName));
if (Long.class.equals(type) || Long.TYPE.equals(type))
return new Long(jsonObject.getLong(facebookFieldName));
if (Double.class.equals(type) || Double.TYPE.equals(type))
return new Double(jsonObject.getDouble(facebookFieldName));
if (Float.class.equals(type) || Float.TYPE.equals(type))
return new BigDecimal(jsonObject.getString(facebookFieldName)).floatValue();
if (BigInteger.class.equals(type))
return new BigInteger(jsonObject.getString(facebookFieldName));
if (BigDecimal.class.equals(type))
return new BigDecimal(jsonObject.getString(facebookFieldName));
if (List.class.equals(type))
return toJavaList(rawValue.toString(), getFirstParameterizedTypeArgument(fieldWithAnnotation.getField()));
String rawValueAsString = rawValue.toString();
// Hack for issue 76 where FB will sometimes return a Post's Comments as
// "[]" instead of an object type (wtf)
if (Comments.class.isAssignableFrom(type) && rawValue instanceof JsonArray) {
if (logger.isLoggable(FINE))
logger.fine("Encountered comment array '" + rawValueAsString + "' but expected a "
+ Comments.class.getSimpleName() + " object instead. Working around that " + "by coercing into an empty "
+ Comments.class.getSimpleName() + " instance...");
JsonObject workaroundJsonObject = new JsonObject();
workaroundJsonObject.put("count", 0);
workaroundJsonObject.put("data", new JsonArray());
rawValueAsString = workaroundJsonObject.toString();
}
// Some other type - recurse into it
return toJavaObject(rawValueAsString, type);
}
/**
* Creates a new instance of the given {@code type}.
*
* @param <T>
* Java type to map to.
* @param type
* Type token.
* @return A new instance of {@code type}.
* @throws FacebookJsonMappingException
* If an error occurs when creating a new instance ({@code type} is
* inaccessible, doesn't have a public no-arg constructor, etc.)
*/
protected <T> T createInstance(Class<T> type) {
String errorMessage =
"Unable to create an instance of " + type + ". Please make sure that it's marked 'public' "
+ "and, if it's a nested class, is marked 'static'. " + "It should have a public, no-argument constructor.";
try {
return type.newInstance();
} catch (IllegalAccessException e) {
throw new FacebookJsonMappingException(errorMessage, e);
} catch (InstantiationException e) {
throw new FacebookJsonMappingException(errorMessage, e);
}
}
/**
* Is the given JSON equivalent to the empty object (<code>{}</code>)?
*
* @param json
* The JSON to check.
* @return {@code true} if the JSON is equivalent to the empty object,
* {@code false} otherwise.
*/
protected boolean isEmptyObject(String json) {
return "{}".equals(json);
}
} | gooddata/GoodData-CL | connector/src/main/java/com/restfb/DefaultJsonMapper.java | Java | bsd-3-clause | 26,108 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_PUBLIC_BROWSER_DOWNLOAD_DANGER_TYPE_H_
#define CONTENT_PUBLIC_BROWSER_DOWNLOAD_DANGER_TYPE_H_
#pragma once
namespace content {
// This enum is also used by histograms. Do not change the ordering or remove
// items.
enum DownloadDangerType {
// The download is safe.
DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS = 0,
// A dangerous file to the system (e.g.: a pdf or extension from
// places other than gallery).
DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
// Safebrowsing download service shows this URL leads to malicious file
// download.
DOWNLOAD_DANGER_TYPE_DANGEROUS_URL,
// SafeBrowsing download service shows this file content as being malicious.
DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT,
// The content of this download may be malicious (e.g., extension is exe but
// SafeBrowsing has not finished checking the content).
DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
// Memory space for histograms is determined by the max.
// ALWAYS ADD NEW VALUES BEFORE THIS ONE.
DOWNLOAD_DANGER_TYPE_MAX
};
}
#endif // CONTENT_PUBLIC_BROWSER_DOWNLOAD_DANGER_TYPE_H_
| aYukiSekiguchi/ACCESS-Chromium | content/public/browser/download_danger_type.h | C | bsd-3-clause | 1,271 |
// Copyright NVIDIA Corporation 2012
// 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 NVIDIA CORPORATION 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 ``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.
#include <dp/ui/RenderTarget.h>
namespace dp
{
namespace ui
{
RenderTarget::~RenderTarget()
{
}
bool RenderTarget::beginRendering()
{
return true;
}
void RenderTarget::endRendering()
{
}
bool RenderTarget::isStereoEnabled() const
{
return false;
}
bool RenderTarget::setStereoTarget( StereoTarget target )
{
return target == LEFT;
}
RenderTarget::StereoTarget RenderTarget::getStereoTarget() const
{
return LEFT;
}
} // namespace ui
} // namespace dp | swq0553/pipeline | dp/ui/src/RenderTarget.cpp | C++ | bsd-3-clause | 2,148 |
import PromiseRouter from '../PromiseRouter';
import * as middleware from "../middlewares";
import { Parse } from "parse/node";
export class PushRouter extends PromiseRouter {
mountRoutes() {
this.route("POST", "/push", middleware.promiseEnforceMasterKeyAccess, PushRouter.handlePOST);
}
static handlePOST(req) {
const pushController = req.config.pushController;
if (!pushController) {
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Push controller is not set');
}
let where = PushRouter.getQueryCondition(req);
pushController.sendPush(req.body, where, req.config, req.auth);
return Promise.resolve({
response: {
'result': true
}
});
}
/**
* Get query condition from the request body.
* @param {Object} req A request object
* @returns {Object} The query condition, the where field in a query api call
*/
static getQueryCondition(req) {
let body = req.body || {};
let hasWhere = typeof body.where !== 'undefined';
let hasChannels = typeof body.channels !== 'undefined';
let where;
if (hasWhere && hasChannels) {
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED,
'Channels and query can not be set at the same time.');
} else if (hasWhere) {
where = body.where;
} else if (hasChannels) {
where = {
"channels": {
"$in": body.channels
}
}
} else {
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED,
'Channels and query should be set at least one.');
}
return where;
}
}
export default PushRouter;
| lucianmat/parse-server | src/Routers/PushRouter.js | JavaScript | bsd-3-clause | 1,611 |
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Enumerate the various item subtypes that are supported by sync.
// Each sync object is expected to have an immutable object type.
// An object's type is inferred from the type of data it holds.
#ifndef SYNC_INTERNAL_API_PUBLIC_BASE_MODEL_TYPE_H_
#define SYNC_INTERNAL_API_PUBLIC_BASE_MODEL_TYPE_H_
#include <map>
#include <set>
#include <string>
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "sync/base/sync_export.h"
#include "sync/internal_api/public/base/enum_set.h"
namespace base {
class ListValue;
class StringValue;
class Value;
}
namespace sync_pb {
class EntitySpecifics;
class SyncEntity;
}
namespace syncer {
// TODO(akalin): Move the non-exported functions in this file to a
// private header.
// A Java counterpart will be generated for this enum.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.sync
// |kModelTypeInfoMap| struct entries are in the same order as their definition
// in ModelType enum. Don't forget to update the |kModelTypeInfoMap| struct in
// model_type.cc when you make changes in ModelType enum.
enum ModelType {
// Object type unknown. Objects may transition through
// the unknown state during their initial creation, before
// their properties are set. After deletion, object types
// are generally preserved.
UNSPECIFIED,
// A permanent folder whose children may be of mixed
// datatypes (e.g. the "Google Chrome" folder).
TOP_LEVEL_FOLDER,
// ------------------------------------ Start of "real" model types.
// The model types declared before here are somewhat special, as they
// they do not correspond to any browser data model. The remaining types
// are bona fide model types; all have a related browser data model and
// can be represented in the protocol using a specific Message type in the
// EntitySpecifics protocol buffer.
//
// A bookmark folder or a bookmark URL object.
BOOKMARKS,
FIRST_USER_MODEL_TYPE = BOOKMARKS, // Declared 2nd, for debugger prettiness.
FIRST_REAL_MODEL_TYPE = FIRST_USER_MODEL_TYPE,
// A preference object.
PREFERENCES,
// A password object.
PASSWORDS,
// An AutofillProfile Object
AUTOFILL_PROFILE,
// An autofill object.
AUTOFILL,
// Credit cards and addresses synced from the user's account. These are
// read-only on the client.
AUTOFILL_WALLET_DATA,
// Usage counts and last use dates for Wallet cards and addresses. This data
// is both readable and writable.
AUTOFILL_WALLET_METADATA,
// A themes object.
THEMES,
// A typed_url object.
TYPED_URLS,
// An extension object.
EXTENSIONS,
// An object representing a custom search engine.
SEARCH_ENGINES,
// An object representing a browser session.
SESSIONS,
// An app object.
APPS,
// An app setting from the extension settings API.
APP_SETTINGS,
// An extension setting from the extension settings API.
EXTENSION_SETTINGS,
// App notifications.
APP_NOTIFICATIONS, // Deprecated.
// History delete directives.
HISTORY_DELETE_DIRECTIVES,
// Synced push notifications.
SYNCED_NOTIFICATIONS, // Deprecated.
// Synced Notification app info.
SYNCED_NOTIFICATION_APP_INFO, // Deprecated.
// Custom spelling dictionary.
DICTIONARY,
// Favicon images.
FAVICON_IMAGES,
// Favicon tracking information.
FAVICON_TRACKING,
// Client-specific metadata, synced before other user types.
DEVICE_INFO,
// These preferences are synced before other user types and are never
// encrypted.
PRIORITY_PREFERENCES,
// Supervised user settings.
SUPERVISED_USER_SETTINGS,
// Supervised users. Every supervised user is a profile that is configured
// remotely by this user and can have restrictions applied. SUPERVISED_USERS
// and SUPERVISED_USER_SETTINGS can not be encrypted.
SUPERVISED_USERS,
// Supervised user shared settings. Shared settings can be modified both by
// the manager and the supervised user.
SUPERVISED_USER_SHARED_SETTINGS,
// Distilled articles.
ARTICLES,
// App List items
APP_LIST,
// WiFi credentials. Each item contains the information for connecting to one
// WiFi network. This includes, e.g., network name and password.
WIFI_CREDENTIALS,
// Supervised user whitelists. Each item contains a CRX ID (like an extension
// ID) and a name.
SUPERVISED_USER_WHITELISTS,
// ---- Proxy types ----
// Proxy types are excluded from the sync protocol, but are still considered
// real user types. By convention, we prefix them with 'PROXY_' to distinguish
// them from normal protocol types.
// Tab sync. This is a placeholder type, so that Sessions can be implicitly
// enabled for history sync and tabs sync.
PROXY_TABS,
FIRST_PROXY_TYPE = PROXY_TABS,
LAST_PROXY_TYPE = PROXY_TABS,
LAST_USER_MODEL_TYPE = PROXY_TABS,
// ---- Control Types ----
// An object representing a set of Nigori keys.
NIGORI,
FIRST_CONTROL_MODEL_TYPE = NIGORI,
// Flags to enable experimental features.
EXPERIMENTS,
LAST_CONTROL_MODEL_TYPE = EXPERIMENTS,
LAST_REAL_MODEL_TYPE = LAST_CONTROL_MODEL_TYPE,
// If you are adding a new sync datatype that is exposed to the user via the
// sync preferences UI, be sure to update the list in
// components/sync_driver/user_selectable_sync_type.h so that the UMA
// histograms for sync include your new type. In this case, be sure to also
// update the UserSelectableTypes() definition in
// sync/syncable/model_type.cc.
MODEL_TYPE_COUNT,
};
typedef EnumSet<ModelType, FIRST_REAL_MODEL_TYPE, LAST_REAL_MODEL_TYPE>
ModelTypeSet;
typedef EnumSet<ModelType, UNSPECIFIED, LAST_REAL_MODEL_TYPE>
FullModelTypeSet;
typedef std::map<syncer::ModelType, const char*> ModelTypeNameMap;
inline ModelType ModelTypeFromInt(int i) {
DCHECK_GE(i, 0);
DCHECK_LT(i, MODEL_TYPE_COUNT);
return static_cast<ModelType>(i);
}
// Used by tests outside of sync/.
SYNC_EXPORT void AddDefaultFieldValue(ModelType datatype,
sync_pb::EntitySpecifics* specifics);
// Extract the model type of a SyncEntity protocol buffer. ModelType is a
// local concept: the enum is not in the protocol. The SyncEntity's ModelType
// is inferred from the presence of particular datatype field in the
// entity specifics.
SYNC_EXPORT_PRIVATE ModelType GetModelType(
const sync_pb::SyncEntity& sync_entity);
// Extract the model type from an EntitySpecifics field. Note that there
// are some ModelTypes (like TOP_LEVEL_FOLDER) that can't be inferred this way;
// prefer using GetModelType where possible.
SYNC_EXPORT ModelType GetModelTypeFromSpecifics(
const sync_pb::EntitySpecifics& specifics);
// Protocol types are those types that have actual protocol buffer
// representations. This distinguishes them from Proxy types, which have no
// protocol representation and are never sent to the server.
SYNC_EXPORT ModelTypeSet ProtocolTypes();
// These are the normal user-controlled types. This is to distinguish from
// ControlTypes which are always enabled. Note that some of these share a
// preference flag, so not all of them are individually user-selectable.
SYNC_EXPORT ModelTypeSet UserTypes();
// These are the user-selectable data types.
SYNC_EXPORT ModelTypeSet UserSelectableTypes();
SYNC_EXPORT bool IsUserSelectableType(ModelType model_type);
SYNC_EXPORT ModelTypeNameMap GetUserSelectableTypeNameMap();
// This is the subset of UserTypes() that can be encrypted.
SYNC_EXPORT_PRIVATE ModelTypeSet EncryptableUserTypes();
// This is the subset of UserTypes() that have priority over other types. These
// types are synced before other user types and are never encrypted.
SYNC_EXPORT ModelTypeSet PriorityUserTypes();
// Proxy types are placeholder types for handling implicitly enabling real
// types. They do not exist at the server, and are simply used for
// UI/Configuration logic.
SYNC_EXPORT ModelTypeSet ProxyTypes();
// Returns a list of all control types.
//
// The control types are intended to contain metadata nodes that are essential
// for the normal operation of the syncer. As such, they have the following
// special properties:
// - They are downloaded early during SyncBackend initialization.
// - They are always enabled. Users may not disable these types.
// - Their contents are not encrypted automatically.
// - They support custom update application and conflict resolution logic.
// - All change processing occurs on the sync thread (GROUP_PASSIVE).
SYNC_EXPORT ModelTypeSet ControlTypes();
// Returns true if this is a control type.
//
// See comment above for more information on what makes these types special.
SYNC_EXPORT bool IsControlType(ModelType model_type);
// Core types are those data types used by sync's core functionality (i.e. not
// user data types). These types are always enabled, and include ControlTypes().
//
// The set of all core types.
SYNC_EXPORT ModelTypeSet CoreTypes();
// Those core types that have high priority (includes ControlTypes()).
SYNC_EXPORT ModelTypeSet PriorityCoreTypes();
// Determine a model type from the field number of its associated
// EntitySpecifics field. Returns UNSPECIFIED if the field number is
// not recognized.
//
// If you're putting the result in a ModelTypeSet, you should use the
// following pattern:
//
// ModelTypeSet model_types;
// // Say we're looping through a list of items, each of which has a
// // field number.
// for (...) {
// int field_number = ...;
// ModelType model_type =
// GetModelTypeFromSpecificsFieldNumber(field_number);
// if (!IsRealDataType(model_type)) {
// DLOG(WARNING) << "Unknown field number " << field_number;
// continue;
// }
// model_types.Put(model_type);
// }
SYNC_EXPORT_PRIVATE ModelType GetModelTypeFromSpecificsFieldNumber(
int field_number);
// Return the field number of the EntitySpecifics field associated with
// a model type.
SYNC_EXPORT int GetSpecificsFieldNumberFromModelType(
ModelType model_type);
FullModelTypeSet ToFullModelTypeSet(ModelTypeSet in);
// TODO(sync): The functions below badly need some cleanup.
// Returns a pointer to a string with application lifetime that represents
// the name of |model_type|.
SYNC_EXPORT const char* ModelTypeToString(ModelType model_type);
// Some histograms take an integer parameter that represents a model type.
// The mapping from ModelType to integer is defined here. It should match
// the mapping from integer to labels defined in histograms.xml.
SYNC_EXPORT int ModelTypeToHistogramInt(ModelType model_type);
// Handles all model types, and not just real ones.
//
// Caller takes ownership of returned value.
SYNC_EXPORT_PRIVATE base::StringValue* ModelTypeToValue(ModelType model_type);
// Converts a Value into a ModelType - complement to ModelTypeToValue().
SYNC_EXPORT_PRIVATE ModelType ModelTypeFromValue(const base::Value& value);
// Returns the ModelType corresponding to the name |model_type_string|.
SYNC_EXPORT ModelType ModelTypeFromString(
const std::string& model_type_string);
// Returns the comma-separated string representation of |model_types|.
SYNC_EXPORT std::string ModelTypeSetToString(ModelTypeSet model_types);
// Returns the set of comma-separated model types from |model_type_string|.
SYNC_EXPORT ModelTypeSet ModelTypeSetFromString(
const std::string& model_type_string);
SYNC_EXPORT scoped_ptr<base::ListValue> ModelTypeSetToValue(
ModelTypeSet model_types);
SYNC_EXPORT ModelTypeSet ModelTypeSetFromValue(const base::ListValue& value);
// Returns a string corresponding to the syncable tag for this datatype.
SYNC_EXPORT std::string ModelTypeToRootTag(ModelType type);
// Convert a real model type to a notification type (used for
// subscribing to server-issued notifications). Returns true iff
// |model_type| was a real model type and |notification_type| was
// filled in.
SYNC_EXPORT bool RealModelTypeToNotificationType(
ModelType model_type,
std::string* notification_type);
// Converts a notification type to a real model type. Returns true
// iff |notification_type| was the notification type of a real model
// type and |model_type| was filled in.
SYNC_EXPORT bool NotificationTypeToRealModelType(
const std::string& notification_type,
ModelType* model_type);
// Returns true if |model_type| is a real datatype
SYNC_EXPORT bool IsRealDataType(ModelType model_type);
// Returns true if |model_type| is a proxy type
SYNC_EXPORT bool IsProxyType(ModelType model_type);
// Returns true if |model_type| is an act-once type. Act once types drop
// entities after applying them. Drops are deletes that are not synced to other
// clients.
// TODO(haitaol): Make entries of act-once data types immutable.
SYNC_EXPORT bool IsActOnceDataType(ModelType model_type);
// Returns true if |model_type| requires its root folder to be explicitly
// created on the server during initial sync.
SYNC_EXPORT bool IsTypeWithServerGeneratedRoot(ModelType model_type);
// Returns true if root folder for |model_type| is created on the client when
// that type is initially synced.
SYNC_EXPORT bool IsTypeWithClientGeneratedRoot(ModelType model_type);
// Returns true if |model_type| supports parent-child hierarchy or entries.
SYNC_EXPORT bool TypeSupportsHierarchy(ModelType model_type);
// Returns true if |model_type| supports ordering of sibling entries.
SYNC_EXPORT bool TypeSupportsOrdering(ModelType model_type);
// Returns set of model types that should be backed up before first sync.
SYNC_EXPORT ModelTypeSet BackupTypes();
} // namespace syncer
#endif // SYNC_INTERNAL_API_PUBLIC_BASE_MODEL_TYPE_H_
| Workday/OpenFrame | sync/internal_api/public/base/model_type.h | C | bsd-3-clause | 13,759 |
<?php
/**
* @see https://github.com/zendframework/zend-di for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (https://www.zend.com)
* @license https://github.com/zendframework/zend-di/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Di\TestAsset;
class A
{
}
| zendframework/zend-di | test/TestAsset/A.php | PHP | bsd-3-clause | 329 |
---
id: 587d7fac367417b2b2512bdb
title: Establece un dominio y un rango en una escala
challengeType: 6
forumTopicId: 301491
dashedName: set-a-domain-and-a-range-on-a-scale
---
# --description--
Por defecto, las escalas usan la relación de identidad. Esto significa que el valor de entrada se asigna al valor de salida. Sin embargo, las escalas pueden ser mucho más flexibles e interesantes.
Digamos que un conjunto de datos tiene valores entre 50 y 480. Esta es la información de entrada para una escala, también conocido como el <dfn>dominio</dfn>.
Quieres trazar esos puntos a lo largo del eje `x` en el lienzo SVG, entre 10 unidades y 500 unidades. Esta es la información de salida, también conocida como el <dfn>rango</dfn>.
Los métodos `domain()` y `range()` establecen estos valores para la escala. Ambos métodos toman un arreglo de al menos dos elementos como argumento. Aquí un ejemplo:
```js
scale.domain([50, 480]);
scale.range([10, 500]);
scale(50)
scale(480)
scale(325)
scale(750)
d3.scaleLinear()
```
En orden, los siguientes valores se mostrarían en la consola: `10`, `500`, `323.37`, y `807.67`.
Observa que la escala usa la relación lineal entre los valores del dominio y del rango para averiguar cuál debe ser la salida para un número dado. El valor mínimo en el dominio (50) se asigna al valor mínimo (10) en el rango.
# --instructions--
Crea una escala y establece su dominio a `[250, 500]` y su rango a `[10, 150]`.
**Nota:** Puedes encadenar los métodos `domain()` y `range()` a la variable `scale`.
# --hints--
Tu código debe usar el método `domain()`.
```js
assert(code.match(/\.domain/g));
```
El `domain()` de `scale` (escala) debe ser establecido a `[250, 500]`.
```js
assert(JSON.stringify(scale.domain()) == JSON.stringify([250, 500]));
```
Tu código debe usar el método `range()`.
```js
assert(code.match(/\.range/g));
```
El `range()` de `scale` (escala) debe ser establecido a `[10, 150]`.
```js
assert(JSON.stringify(scale.range()) == JSON.stringify([10, 150]));
```
El texto en el `h2` debe ser `-102`.
```js
assert($('h2').text() == '-102');
```
# --seed--
## --seed-contents--
```html
<body>
<script>
// Add your code below this line
const scale = d3.scaleLinear();
// Add your code above this line
const output = scale(50);
d3.select("body")
.append("h2")
.text(output);
</script>
</body>
```
# --solutions--
```html
<body>
<script>
const scale = d3.scaleLinear();
scale.domain([250, 500])
scale.range([10, 150])
const output = scale(50);
d3.select("body")
.append("h2")
.text(output);
</script>
</body>
```
| FreeCodeCamp/FreeCodeCamp | curriculum/challenges/espanol/04-data-visualization/data-visualization-with-d3/set-a-domain-and-a-range-on-a-scale.md | Markdown | bsd-3-clause | 2,666 |
module Verifier.SAW.SATQuery
( SATQuery(..)
, SATResult(..)
, satQueryAsTerm
) where
import Control.Monad (foldM)
import Data.Map (Map)
import Data.Set (Set)
import Verifier.SAW.Name
import Verifier.SAW.FiniteValue
import Verifier.SAW.SharedTerm
-- | This datatype represents a satisfiability query that might
-- be dispatched to a solver. It carries a series of assertions
-- to be made to a solver, together with a collection of
-- variables we expect the solver to report models over,
-- and a collection of @VarIndex@ values identifying
-- subterms that should be considered uninterpreted.
--
-- All the @ExtCns@ values in the query should
-- appear either in @satVariables@ or @satUninterp@.
-- Constant values for which definitions are provided
-- may also appear in @satUninterp@, in which case
-- they will be treated as uninterpreted. Otherwise,
-- their definitions will be unfolded.
--
-- Solve solvers do not support uninterpreted values
-- and will fail if presented a query that requests them.
data SATQuery =
SATQuery
{ satVariables :: Map (ExtCns Term) FirstOrderType
-- ^ The variables in the query, for which we
-- expect the solver to find values in satisfiable
-- cases. INVARIANT: The type of the @ExtCns@ keys
-- should correspond to the @FirstOrderType@ values.
, satUninterp :: Set VarIndex
-- ^ A set indicating which variables and constant
-- values should be considered uninterpreted by
-- the solver. Models will not report values
-- for uninterpreted values.
, satAsserts :: [Term]
-- ^ A collection of assertions. These should
-- all be terms of type @Bool@. The overall
-- query should be understood as the conjunction
-- of these terms.
}
-- TODO, allow first-order propositions in addition to Boolean terms.
-- | The result of a sat query. In the event a model is found,
-- return a mapping from the @ExtCns@ variables to values.
data SATResult
= Unsatisfiable
| Satisfiable (ExtCns Term -> IO FirstOrderValue)
| Unknown
-- | Compute the conjunction of all the assertions
-- in this SAT query as a single term of type Bool.
satQueryAsTerm :: SharedContext -> SATQuery -> IO Term
satQueryAsTerm sc satq =
case satAsserts satq of
[] -> scBool sc True
(x:xs) -> foldM (scAnd sc) x xs
-- TODO, we may have to rethink this function
-- once we allow first-order statements.
| GaloisInc/saw-script | saw-core/src/Verifier/SAW/SATQuery.hs | Haskell | bsd-3-clause | 2,474 |
//
// detail/pipe_select_interrupter.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP
#define BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if !defined(BOOST_WINDOWS)
#if !defined(__CYGWIN__)
#if !defined(__SYMBIAN32__)
#if !defined(BOOST_ASIO_HAS_EVENTFD)
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
class pipe_select_interrupter
{
public:
// Constructor.
BOOST_ASIO_DECL pipe_select_interrupter();
// Destructor.
BOOST_ASIO_DECL ~pipe_select_interrupter();
// Interrupt the select call.
BOOST_ASIO_DECL void interrupt();
// Reset the select interrupt. Returns true if the call was interrupted.
BOOST_ASIO_DECL bool reset();
// Get the read descriptor to be passed to select.
int read_descriptor() const
{
return read_descriptor_;
}
private:
// The read end of a connection used to interrupt the select call. This file
// descriptor is passed to select such that when it is time to stop, a single
// byte will be written on the other end of the connection and this
// descriptor will become readable.
int read_descriptor_;
// The write end of a connection used to interrupt the select call. A single
// byte may be written to this to wake up the select which is waiting for the
// other end to become readable.
int write_descriptor_;
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#if defined(BOOST_ASIO_HEADER_ONLY)
# include <boost/asio/detail/impl/pipe_select_interrupter.ipp>
#endif // defined(BOOST_ASIO_HEADER_ONLY)
#endif // !defined(BOOST_ASIO_HAS_EVENTFD)
#endif // !defined(__SYMBIAN32__)
#endif // !defined(__CYGWIN__)
#endif // !defined(BOOST_WINDOWS)
#endif // BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP
| benkaraban/anima-games-engine | LibsExternes/Includes/boost/asio/detail/pipe_select_interrupter.hpp | C++ | bsd-3-clause | 2,322 |
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script
| Hackplayers/Empire-mod-Hpys-tests | lib/modules/powershell/management/lock.py | Python | bsd-3-clause | 3,056 |
/* Copyright 2021 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.
*/
/* MT SCP RV32i configuration */
#include "cache.h"
#include "csr.h"
#include "hooks.h"
#include "registers.h"
#define SCP_SRAM_END (CONFIG_IPC_SHARED_OBJ_ADDR & (~(0x400 - 1)))
struct mpu_entry mpu_entries[NR_MPU_ENTRIES] = {
/* SRAM (for most code, data) */
{0, SCP_SRAM_END, MPU_ATTR_C | MPU_ATTR_W | MPU_ATTR_R},
/* SRAM (for IPI shared buffer) */
{SCP_SRAM_END, SCP_FW_END, MPU_ATTR_W | MPU_ATTR_R},
/* For AP domain */
#ifdef CHIP_VARIANT_MT8195
{0x60000000, 0x70000000, MPU_ATTR_W | MPU_ATTR_R | MPU_ATTR_P},
#else
{0x60000000, 0x70000000, MPU_ATTR_W | MPU_ATTR_R},
#endif
/* For SCP sys */
{0x70000000, 0x80000000, MPU_ATTR_W | MPU_ATTR_R},
#ifdef CHIP_VARIANT_MT8195
{0x10000000, 0x11400000, MPU_ATTR_C | MPU_ATTR_W | MPU_ATTR_R},
{CONFIG_PANIC_DRAM_BASE, CONFIG_PANIC_DRAM_BASE + CONFIG_PANIC_DRAM_SIZE, MPU_ATTR_W | MPU_ATTR_R},
#else
{0x10000000, 0x11400000, MPU_ATTR_W | MPU_ATTR_R},
#endif
};
#include "gpio_list.h"
#ifdef CONFIG_PANIC_CONSOLE_OUTPUT
static void report_previous_panic(void)
{
struct panic_data * panic = panic_get_data();
if (panic == NULL && SCP_CORE0_MON_PC_LATCH == 0)
return;
ccprintf("[Previous Panic]\n");
if (panic) {
panic_data_ccprint(panic);
} else {
ccprintf("No panic data\n");
}
ccprintf("Latch PC:%x LR:%x SP:%x\n",
SCP_CORE0_MON_PC_LATCH,
SCP_CORE0_MON_LR_LATCH,
SCP_CORE0_MON_SP_LATCH);
}
DECLARE_HOOK(HOOK_INIT, report_previous_panic, HOOK_PRIO_DEFAULT);
#endif
| coreboot/chrome-ec | baseboard/mtscp-rv32i/baseboard.c | C | bsd-3-clause | 1,621 |
/* Copyright (C) 2012 Motorola Mobility 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:
*
* 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 name of Motorola Mobility 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.
*/
#ifndef CSSSupportsRule_h
#define CSSSupportsRule_h
#include "core/css/CSSGroupingRule.h"
namespace blink {
class CSSRule;
class StyleRuleSupports;
class CSSSupportsRule FINAL : public CSSGroupingRule {
public:
static PassRefPtrWillBeRawPtr<CSSSupportsRule> create(StyleRuleSupports* rule, CSSStyleSheet* sheet)
{
return adoptRefWillBeNoop(new CSSSupportsRule(rule, sheet));
}
virtual ~CSSSupportsRule() { }
virtual CSSRule::Type type() const OVERRIDE { return SUPPORTS_RULE; }
virtual String cssText() const OVERRIDE;
String conditionText() const;
virtual void trace(Visitor* visitor) OVERRIDE { CSSGroupingRule::trace(visitor); }
private:
CSSSupportsRule(StyleRuleSupports*, CSSStyleSheet*);
};
DEFINE_CSS_RULE_TYPE_CASTS(CSSSupportsRule, SUPPORTS_RULE);
} // namespace blink
#endif // CSSSupportsRule_h
| xin3liang/platform_external_chromium_org_third_party_WebKit | Source/core/css/CSSSupportsRule.h | C | bsd-3-clause | 2,448 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var keys = require("./keys");
var useragent = require("./useragent");
exports.addListener = function(elem, type, callback) {
if (elem.addEventListener) {
return elem.addEventListener(type, callback, false);
}
if (elem.attachEvent) {
var wrapper = function() {
callback.call(elem, window.event);
};
callback._wrapper = wrapper;
elem.attachEvent("on" + type, wrapper);
}
};
exports.removeListener = function(elem, type, callback) {
if (elem.removeEventListener) {
return elem.removeEventListener(type, callback, false);
}
if (elem.detachEvent) {
elem.detachEvent("on" + type, callback._wrapper || callback);
}
};
/*
* Prevents propagation and clobbers the default action of the passed event
*/
exports.stopEvent = function(e) {
exports.stopPropagation(e);
exports.preventDefault(e);
return false;
};
exports.stopPropagation = function(e) {
if (e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
};
exports.preventDefault = function(e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
};
/*
* @return {Number} 0 for left button, 1 for middle button, 2 for right button
*/
exports.getButton = function(e) {
if (e.type == "dblclick")
return 0;
if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey)))
return 2;
// DOM Event
if (e.preventDefault) {
return e.button;
}
// old IE
else {
return {1:0, 2:2, 4:1}[e.button];
}
};
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseUp(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler(e);
exports.removeListener(document, "mousemove", eventHandler, true);
exports.removeListener(document, "mouseup", onMouseUp, true);
exports.removeListener(document, "dragstart", onMouseUp, true);
}
exports.addListener(document, "mousemove", eventHandler, true);
exports.addListener(document, "mouseup", onMouseUp, true);
exports.addListener(document, "dragstart", onMouseUp, true);
return onMouseUp;
};
exports.addMouseWheelListener = function(el, callback) {
if ("onmousewheel" in el) {
exports.addListener(el, "mousewheel", function(e) {
var factor = 8;
if (e.wheelDeltaX !== undefined) {
e.wheelX = -e.wheelDeltaX / factor;
e.wheelY = -e.wheelDeltaY / factor;
} else {
e.wheelX = 0;
e.wheelY = -e.wheelDelta / factor;
}
callback(e);
});
} else if ("onwheel" in el) {
exports.addListener(el, "wheel", function(e) {
var factor = 0.35;
switch (e.deltaMode) {
case e.DOM_DELTA_PIXEL:
e.wheelX = e.deltaX * factor || 0;
e.wheelY = e.deltaY * factor || 0;
break;
case e.DOM_DELTA_LINE:
case e.DOM_DELTA_PAGE:
e.wheelX = (e.deltaX || 0) * 5;
e.wheelY = (e.deltaY || 0) * 5;
break;
}
callback(e);
});
} else {
exports.addListener(el, "DOMMouseScroll", function(e) {
if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
e.wheelX = (e.detail || 0) * 5;
e.wheelY = 0;
} else {
e.wheelX = 0;
e.wheelY = (e.detail || 0) * 5;
}
callback(e);
});
}
};
exports.addMultiMouseDownListener = function(el, timeouts, eventHandler, callbackName) {
var clicks = 0;
var startX, startY, timer;
var eventNames = {
2: "dblclick",
3: "tripleclick",
4: "quadclick"
};
exports.addListener(el, "mousedown", function(e) {
if (exports.getButton(e) !== 0) {
clicks = 0;
} else if (e.detail > 1) {
clicks++;
if (clicks > 4)
clicks = 1;
} else {
clicks = 1;
}
if (useragent.isIE) {
var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5;
if (!timer || isNewClick)
clicks = 1;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
if (clicks == 1) {
startX = e.clientX;
startY = e.clientY;
}
}
e._clicks = clicks;
eventHandler[callbackName]("mousedown", e);
if (clicks > 4)
clicks = 0;
else if (clicks > 1)
return eventHandler[callbackName](eventNames[clicks], e);
});
if (useragent.isOldIE) {
exports.addListener(el, "dblclick", function(e) {
clicks = 2;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
eventHandler[callbackName]("mousedown", e);
eventHandler[callbackName](eventNames[clicks], e);
});
}
};
var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window)
? function(e) {
return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
}
: function(e) {
return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
};
exports.getModifierString = function(e) {
return keys.KEY_MODS[getModifierHash(e)];
};
function normalizeCommandKeys(callback, e, keyCode) {
var hashId = getModifierHash(e);
if (!useragent.isMac && pressedKeys) {
if (pressedKeys[91] || pressedKeys[92])
hashId |= 8;
if (pressedKeys.altGr) {
if ((3 & hashId) != 3)
pressedKeys.altGr = 0;
else
return;
}
if (keyCode === 18 || keyCode === 17) {
var location = "location" in e ? e.location : e.keyLocation;
if (keyCode === 17 && location === 1) {
if (pressedKeys[keyCode] == 1)
ts = e.timeStamp;
} else if (keyCode === 18 && hashId === 3 && location === 2) {
var dt = e.timeStamp - ts;
if (dt < 50)
pressedKeys.altGr = true;
}
}
}
if (keyCode in keys.MODIFIER_KEYS) {
keyCode = -1;
}
if (hashId & 8 && (keyCode === 91 || keyCode === 93)) {
keyCode = -1;
}
if (!hashId && keyCode === 13) {
var location = "location" in e ? e.location : e.keyLocation;
if (location === 3) {
callback(e, hashId, -keyCode);
if (e.defaultPrevented)
return;
}
}
if (useragent.isChromeOS && hashId & 8) {
callback(e, hashId, keyCode);
if (e.defaultPrevented)
return;
else
hashId &= ~8;
}
// If there is no hashId and the keyCode is not a function key, then
// we don't call the callback as we don't handle a command key here
// (it's a normal key/character input).
if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) {
return false;
}
return callback(e, hashId, keyCode);
}
var pressedKeys = null;
var ts = 0;
exports.addCommandKeyListener = function(el, callback) {
var addListener = exports.addListener;
if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) {
// Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown
// event if the user pressed the key for a longer time. Instead, the
// keydown event was fired once and later on only the keypress event.
// To emulate the 'right' keydown behavior, the keyCode of the initial
// keyDown event is stored and in the following keypress events the
// stores keyCode is used to emulate a keyDown event.
var lastKeyDownKeyCode = null;
addListener(el, "keydown", function(e) {
lastKeyDownKeyCode = e.keyCode;
});
addListener(el, "keypress", function(e) {
return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
});
} else {
var lastDefaultPrevented = null;
addListener(el, "keydown", function(e) {
pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1;
var result = normalizeCommandKeys(callback, e, e.keyCode);
lastDefaultPrevented = e.defaultPrevented;
return result;
});
addListener(el, "keypress", function(e) {
if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) {
exports.stopEvent(e);
lastDefaultPrevented = null;
}
});
addListener(el, "keyup", function(e) {
pressedKeys[e.keyCode] = null;
});
if (!pressedKeys) {
pressedKeys = Object.create(null);
addListener(window, "focus", function(e) {
pressedKeys = Object.create(null);
});
}
}
};
if (window.postMessage && !useragent.isOldIE) {
var postMessageId = 1;
exports.nextTick = function(callback, win) {
win = win || window;
var messageName = "zero-timeout-message-" + postMessageId;
exports.addListener(win, "message", function listener(e) {
if (e.data == messageName) {
exports.stopPropagation(e);
exports.removeListener(win, "message", listener);
callback();
}
});
win.postMessage(messageName, "*");
};
}
exports.nextFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
if (exports.nextFrame)
exports.nextFrame = exports.nextFrame.bind(window);
else
exports.nextFrame = function(callback) {
setTimeout(callback, 17);
};
});
| louis-tru/touch_code | client/third_party/ace/lib/ace/lib/event.js | JavaScript | bsd-3-clause | 12,179 |
#!/bin/bash
DD=../../PhoneGap/ios/KNappen/assets/world/KNappen
rm -rf "$DD"
mkdir -p "$DD"
cp -va ./KNappen.MobileSPA/* "$DD"
pushd "$DD"
rm -rf Brukerdokumentasjon *.ts bin obj Properties UnitTests index.html Test.html index.html *.csproj *.user config.xml Web*.config packages.config
popd
| knreise/KNappen | KNappen_src/KNappen/CopyToPhoneGap_ios.sh | Shell | bsd-3-clause | 293 |
###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## - Neither the name of the New York University 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."
##
###############################################################################
from __future__ import division
""" This python module defines Connection class.
"""
import copy
from vistrails.db.domain import DBConnection
from vistrails.core.vistrail.port import PortEndPoint, Port
import unittest
from vistrails.db.domain import IdScope
################################################################################
class Connection(DBConnection):
""" A Connection is a connection between two modules.
Right now there's only Module connections.
"""
##########################################################################
# Constructors and copy
@staticmethod
def from_port_specs(source, dest):
"""from_port_specs(source: PortSpec, dest: PortSpec) -> Connection
Static method that creates a Connection given source and
destination ports.
"""
conn = Connection()
conn.source = copy.copy(source)
conn.destination = copy.copy(dest)
return conn
@staticmethod
def fromID(id):
"""fromTypeID(id: int) -> Connection
Static method that creates a Connection given an id.
"""
conn = Connection()
conn.id = id
conn.source.endPoint = PortEndPoint.Source
conn.destination.endPoint = PortEndPoint.Destination
return conn
def __init__(self, *args, **kwargs):
"""__init__() -> Connection
Initializes source and destination ports.
"""
DBConnection.__init__(self, *args, **kwargs)
if self.id is None:
self.db_id = -1
if not len(self.ports) > 0:
self.source = Port(type='source')
self.destination = Port(type='destination')
def __copy__(self):
"""__copy__() -> Connection - Returns a clone of self.
"""
return Connection.do_copy(self)
def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
cp = DBConnection.do_copy(self, new_ids, id_scope, id_remap)
cp.__class__ = Connection
for port in cp.ports:
Port.convert(port)
return cp
##########################################################################
@staticmethod
def convert(_connection):
# print "ports: %s" % _Connection._get_ports(_connection)
if _connection.__class__ == Connection:
return
_connection.__class__ = Connection
for port in _connection.ports:
Port.convert(port)
##########################################################################
# Properties
id = DBConnection.db_id
ports = DBConnection.db_ports
def add_port(self, port):
self.db_add_port(port)
def _get_sourceId(self):
""" _get_sourceId() -> int
Returns the module id of source port. Do not use this function,
use sourceId property: c.sourceId
"""
return self.source.moduleId
def _set_sourceId(self, id):
""" _set_sourceId(id : int) -> None
Sets this connection source id. It updates both self.source.moduleId
and self.source.id. Do not use this function, use sourceId
property: c.sourceId = id
"""
self.source.moduleId = id
self.source.id = id
sourceId = property(_get_sourceId, _set_sourceId)
def _get_destinationId(self):
""" _get_destinationId() -> int
Returns the module id of dest port. Do not use this function,
use sourceId property: c.destinationId
"""
return self.destination.moduleId
def _set_destinationId(self, id):
""" _set_destinationId(id : int) -> None
Sets this connection destination id. It updates self.dest.moduleId.
Do not use this function, use destinationId property:
c.destinationId = id
"""
self.destination.moduleId = id
destinationId = property(_get_destinationId, _set_destinationId)
def _get_source(self):
"""_get_source() -> Port
Returns source port. Do not use this function, use source property:
c.source
"""
try:
return self.db_get_port_by_type('source')
except KeyError:
pass
return None
def _set_source(self, source):
"""_set_source(source: Port) -> None
Sets this connection source port. Do not use this function,
use source property instead: c.source = source
"""
try:
port = self.db_get_port_by_type('source')
self.db_delete_port(port)
except KeyError:
pass
if source is not None:
self.db_add_port(source)
source = property(_get_source, _set_source)
def _get_destination(self):
"""_get_destination() -> Port
Returns destination port. Do not use this function, use destination
property: c.destination
"""
# return self.db_ports['destination']
try:
return self.db_get_port_by_type('destination')
except KeyError:
pass
return None
def _set_destination(self, dest):
"""_set_destination(dest: Port) -> None
Sets this connection destination port. Do not use this
function, use destination property instead: c.destination = dest
"""
try:
port = self.db_get_port_by_type('destination')
self.db_delete_port(port)
except KeyError:
pass
if dest is not None:
self.db_add_port(dest)
destination = property(_get_destination, _set_destination)
dest = property(_get_destination, _set_destination)
##########################################################################
# Operators
def __str__(self):
"""__str__() -> str - Returns a string representation of a Connection
object.
"""
rep = "<connection id='%s'>%s%s</connection>"
return rep % (str(self.id), str(self.source), str(self.destination))
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
if type(other) != type(self):
return False
return (self.source == other.source and
self.dest == other.dest)
def equals_no_id(self, other):
"""Checks equality up to ids (connection and ports)."""
if type(self) != type(other):
return False
return (self.source.equals_no_id(other.source) and
self.dest.equals_no_id(other.dest))
################################################################################
# Testing
class TestConnection(unittest.TestCase):
def create_connection(self, id_scope=IdScope()):
from vistrails.core.vistrail.port import Port
from vistrails.core.modules.basic_modules import identifier as basic_pkg
source = Port(id=id_scope.getNewId(Port.vtType),
type='source',
moduleId=21L,
moduleName='String',
name='value',
signature='(%s:String)' % basic_pkg)
destination = Port(id=id_scope.getNewId(Port.vtType),
type='destination',
moduleId=20L,
moduleName='Float',
name='value',
signature='(%s:Float)' % basic_pkg)
connection = Connection(id=id_scope.getNewId(Connection.vtType),
ports=[source, destination])
return connection
def test_copy(self):
id_scope = IdScope()
c1 = self.create_connection(id_scope)
c2 = copy.copy(c1)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
c3 = c1.do_copy(True, id_scope, {})
self.assertEquals(c1, c3)
self.assertNotEquals(c1.id, c3.id)
def test_serialization(self):
import vistrails.core.db.io
c1 = self.create_connection()
xml_str = vistrails.core.db.io.serialize(c1)
c2 = vistrails.core.db.io.unserialize(xml_str, Connection)
self.assertEquals(c1, c2)
self.assertEquals(c1.id, c2.id)
def testEmptyConnection(self):
"""Tests sane initialization of empty connection"""
c = Connection()
self.assertEquals(c.source.endPoint, PortEndPoint.Source)
self.assertEquals(c.destination.endPoint, PortEndPoint.Destination)
if __name__ == '__main__':
unittest.main()
| VisTrails/VisTrails | vistrails/core/vistrail/connection.py | Python | bsd-3-clause | 10,497 |
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Demo code about collisions and contacts using the penalty method (SMC)
//
// =============================================================================
#include "chrono/physics/ChSystemSMC.h"
#include "chrono/physics/ChContactContainerSMC.h"
#include "chrono/solver/ChSolverSMC.h"
#include "chrono_irrlicht/ChIrrApp.h"
#include <irrlicht.h>
// Use the namespaces of Chrono
using namespace chrono;
using namespace chrono::irrlicht;
// Use the main namespaces of Irrlicht
using namespace irr;
using namespace irr::core;
using namespace irr::scene;
using namespace irr::video;
using namespace irr::io;
using namespace irr::gui;
void AddWall(std::shared_ptr<ChBody> body, const ChVector<>& dim, const ChVector<>& loc) {
body->GetCollisionModel()->AddBox(dim.x(), dim.y(), dim.z(), loc);
auto box = std::make_shared<ChBoxShape>();
box->GetBoxGeometry().Size = dim;
box->GetBoxGeometry().Pos = loc;
box->SetColor(ChColor(1, 0, 0));
box->SetFading(0.6f);
body->AddAsset(box);
}
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
// Simulation parameters
double gravity = -9.81;
double time_step = 0.00001;
double out_step = 2000 * time_step;
// Parameters for the falling ball
int ballId = 100;
double radius = 1;
double mass = 1000;
ChVector<> pos(0, 2, 0);
ChQuaternion<> rot(1, 0, 0, 0);
ChVector<> init_vel(0, 0, 0);
// Parameters for the containing bin
int binId = 200;
double width = 2;
double length = 2;
double height = 1;
double thickness = 0.1;
// Create the system
ChSystemSMC msystem;
// The following two lines are optional, since they are the default options. They are added for future reference,
// i.e. when needed to change those models.
msystem.SetContactForceModel(ChSystemSMC::ContactForceModel::Hertz);
msystem.SetAdhesionForceModel(ChSystemSMC::AdhesionForceModel::Constant);
msystem.Set_G_acc(ChVector<>(0, gravity, 0));
// Change the default collision effective radius of curvature
collision::ChCollisionInfo::SetDefaultEffectiveCurvatureRadius(1);
// Create the Irrlicht visualization
ChIrrApp application(&msystem, L"SMC demo", core::dimension2d<u32>(800, 600), false, true);
// Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(core::vector3df(0, 3, -6));
// This means that contactforces will be shown in Irrlicht application
application.SetSymbolscale(1e-4);
application.SetContactsDrawMode(ChIrrTools::eCh_ContactsDrawMode::CONTACT_FORCES);
// Create a material (will be used by both objects)
auto material = std::make_shared<ChMaterialSurfaceSMC>();
material->SetRestitution(0.1f);
material->SetFriction(0.4f);
material->SetAdhesion(0); // Magnitude of the adhesion in Constant adhesion model
// Create the falling ball
auto ball = std::make_shared<ChBody>(ChMaterialSurface::SMC);
ball->SetIdentifier(ballId);
ball->SetMass(mass);
ball->SetPos(pos);
ball->SetRot(rot);
ball->SetPos_dt(init_vel);
// ball->SetWvel_par(ChVector<>(0,0,3));
ball->SetBodyFixed(false);
ball->SetMaterialSurface(material);
ball->SetCollide(true);
ball->GetCollisionModel()->ClearModel();
ball->GetCollisionModel()->AddSphere(radius);
ball->GetCollisionModel()->BuildModel();
ball->SetInertiaXX(0.4 * mass * radius * radius * ChVector<>(1, 1, 1));
auto sphere = std::make_shared<ChSphereShape>();
sphere->GetSphereGeometry().rad = radius;
ball->AddAsset(sphere);
auto mtexture = std::make_shared<ChTexture>();
mtexture->SetTextureFilename(GetChronoDataFile("bluwhite.png"));
ball->AddAsset(mtexture);
msystem.AddBody(ball);
// Create container
auto bin = std::make_shared<ChBody>(ChMaterialSurface::SMC);
bin->SetIdentifier(binId);
bin->SetMass(1);
bin->SetPos(ChVector<>(0, 0, 0));
bin->SetRot(ChQuaternion<>(1, 0, 0, 0));
bin->SetCollide(true);
bin->SetBodyFixed(true);
bin->SetMaterialSurface(material);
bin->GetCollisionModel()->ClearModel();
AddWall(bin, ChVector<>(width, thickness, length), ChVector<>(0, 0, 0));
// AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(-width + thickness, height, 0));
// AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(width - thickness, height, 0));
// AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, -length + thickness));
// AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, length - thickness));
bin->GetCollisionModel()->BuildModel();
msystem.AddBody(bin);
// Complete asset construction
application.AssetBindAll();
application.AssetUpdateAll();
// The soft-real-time cycle
double time = 0.0;
double out_time = 0.0;
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
ChIrrTools::drawGrid(application.GetVideoDriver(), 0.2, 0.2, 20, 20,
ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI_2)),
video::SColor(255, 80, 100, 100), true);
while (time < out_time) {
msystem.DoStepDynamics(time_step);
time += time_step;
}
out_time += out_step;
application.EndScene();
}
return 0;
}
| amelmquist/chrono | src/demos/irrlicht/demo_IRR_ballSMC.cpp | C++ | bsd-3-clause | 6,214 |
Spree Ordering Info
===================
Introduction goes here.
Installation
------------
Add spree_ordering_info to your Gemfile:
```ruby
gem 'spree_ordering_info'
```
Bundle your dependencies and run the installation generator:
```shell
bundle
bundle exec rails g spree_ordering_info:install
```
Testing
-------
First bundle your dependencies, then run `rake`. `rake` will default to building the dummy app if it does not exist, then it will run specs. The dummy app can be regenerated by using `rake test_app`.
```shell
bundle
bundle exec rake
```
When testing your applications integration with this extension you may use it's factories.
Simply add this require statement to your spec_helper:
```ruby
require 'spree_ordering_info/factories'
```
Copyright (c) 2017 Astek Wallcovering, Inc., released under the New BSD License
| astek-inc/spree-ordering-info | README.md | Markdown | bsd-3-clause | 841 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82a.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-82a.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Copy a fixed string into data
* Sinks: fprintf
* GoodSink: fprintf with "%s" as the second argument and data as the third
* BadSink : fprintf with data as the second argument
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
namespace CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82_base* baseObject = new CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82_bad;
baseObject->action(data);
delete baseObject;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
/* FIX: Use a fixed string that does not contain a format specifier */
strcpy(data, "fixedstringtest");
CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82_base* baseObject = new CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82_goodG2B;
baseObject->action(data);
delete baseObject;
}
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82_base* baseObject = new CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82_goodB2G;
baseObject->action(data);
delete baseObject;
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE134_Uncontrolled_Format_String/s01/CWE134_Uncontrolled_Format_String__char_connect_socket_fprintf_82a.cpp | C++ | bsd-3-clause | 7,904 |
/*
* libjingle
* Copyright 2010, Google Inc.
*
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#include <stdio.h>
#include <string>
#include "talk/p2p/base/sessionmessages.h"
#include "talk/base/logging.h"
#include "talk/base/scoped_ptr.h"
#include "talk/base/stringutils.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/p2ptransport.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/sessionclient.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/p2p/base/transport.h"
#include "talk/xmllite/xmlconstants.h"
#include "talk/xmpp/constants.h"
namespace cricket {
ActionType ToActionType(const std::string& type) {
if (type == GINGLE_ACTION_INITIATE)
return ACTION_SESSION_INITIATE;
if (type == GINGLE_ACTION_INFO)
return ACTION_SESSION_INFO;
if (type == GINGLE_ACTION_ACCEPT)
return ACTION_SESSION_ACCEPT;
if (type == GINGLE_ACTION_REJECT)
return ACTION_SESSION_REJECT;
if (type == GINGLE_ACTION_TERMINATE)
return ACTION_SESSION_TERMINATE;
if (type == GINGLE_ACTION_CANDIDATES)
return ACTION_TRANSPORT_INFO;
if (type == JINGLE_ACTION_SESSION_INITIATE)
return ACTION_SESSION_INITIATE;
if (type == JINGLE_ACTION_TRANSPORT_INFO)
return ACTION_TRANSPORT_INFO;
if (type == JINGLE_ACTION_TRANSPORT_ACCEPT)
return ACTION_TRANSPORT_ACCEPT;
if (type == JINGLE_ACTION_SESSION_INFO)
return ACTION_SESSION_INFO;
if (type == JINGLE_ACTION_SESSION_ACCEPT)
return ACTION_SESSION_ACCEPT;
if (type == JINGLE_ACTION_SESSION_TERMINATE)
return ACTION_SESSION_TERMINATE;
if (type == JINGLE_ACTION_TRANSPORT_INFO)
return ACTION_TRANSPORT_INFO;
if (type == JINGLE_ACTION_TRANSPORT_ACCEPT)
return ACTION_TRANSPORT_ACCEPT;
if (type == JINGLE_ACTION_DESCRIPTION_INFO)
return ACTION_DESCRIPTION_INFO;
if (type == GINGLE_ACTION_UPDATE)
return ACTION_DESCRIPTION_INFO;
return ACTION_UNKNOWN;
}
std::string ToJingleString(ActionType type) {
switch (type) {
case ACTION_SESSION_INITIATE:
return JINGLE_ACTION_SESSION_INITIATE;
case ACTION_SESSION_INFO:
return JINGLE_ACTION_SESSION_INFO;
case ACTION_SESSION_ACCEPT:
return JINGLE_ACTION_SESSION_ACCEPT;
// Notice that reject and terminate both go to
// "session-terminate", but there is no "session-reject".
case ACTION_SESSION_REJECT:
case ACTION_SESSION_TERMINATE:
return JINGLE_ACTION_SESSION_TERMINATE;
case ACTION_TRANSPORT_INFO:
return JINGLE_ACTION_TRANSPORT_INFO;
case ACTION_TRANSPORT_ACCEPT:
return JINGLE_ACTION_TRANSPORT_ACCEPT;
default:
return "";
}
}
std::string ToGingleString(ActionType type) {
switch (type) {
case ACTION_SESSION_INITIATE:
return GINGLE_ACTION_INITIATE;
case ACTION_SESSION_INFO:
return GINGLE_ACTION_INFO;
case ACTION_SESSION_ACCEPT:
return GINGLE_ACTION_ACCEPT;
case ACTION_SESSION_REJECT:
return GINGLE_ACTION_REJECT;
case ACTION_SESSION_TERMINATE:
return GINGLE_ACTION_TERMINATE;
case ACTION_TRANSPORT_INFO:
return GINGLE_ACTION_CANDIDATES;
default:
return "";
}
}
bool IsJingleMessage(const buzz::XmlElement* stanza) {
const buzz::XmlElement* jingle = stanza->FirstNamed(QN_JINGLE);
if (jingle == NULL)
return false;
return (jingle->HasAttr(buzz::QN_ACTION) && jingle->HasAttr(QN_SID));
}
bool IsGingleMessage(const buzz::XmlElement* stanza) {
const buzz::XmlElement* session = stanza->FirstNamed(QN_GINGLE_SESSION);
if (session == NULL)
return false;
return (session->HasAttr(buzz::QN_TYPE) &&
session->HasAttr(buzz::QN_ID) &&
session->HasAttr(QN_INITIATOR));
}
bool IsSessionMessage(const buzz::XmlElement* stanza) {
return (stanza->Name() == buzz::QN_IQ &&
stanza->Attr(buzz::QN_TYPE) == buzz::STR_SET &&
(IsJingleMessage(stanza) ||
IsGingleMessage(stanza)));
}
bool ParseGingleSessionMessage(const buzz::XmlElement* session,
SessionMessage* msg,
ParseError* error) {
msg->protocol = PROTOCOL_GINGLE;
std::string type_string = session->Attr(buzz::QN_TYPE);
msg->type = ToActionType(type_string);
msg->sid = session->Attr(buzz::QN_ID);
msg->initiator = session->Attr(QN_INITIATOR);
msg->action_elem = session;
if (msg->type == ACTION_UNKNOWN)
return BadParse("unknown action: " + type_string, error);
return true;
}
bool ParseJingleSessionMessage(const buzz::XmlElement* jingle,
SessionMessage* msg,
ParseError* error) {
msg->protocol = PROTOCOL_JINGLE;
std::string type_string = jingle->Attr(buzz::QN_ACTION);
msg->type = ToActionType(type_string);
msg->sid = jingle->Attr(QN_SID);
msg->initiator = GetXmlAttr(jingle, QN_INITIATOR, buzz::STR_EMPTY);
msg->action_elem = jingle;
if (msg->type == ACTION_UNKNOWN)
return BadParse("unknown action: " + type_string, error);
return true;
}
bool ParseHybridSessionMessage(const buzz::XmlElement* jingle,
SessionMessage* msg,
ParseError* error) {
if (!ParseJingleSessionMessage(jingle, msg, error))
return false;
msg->protocol = PROTOCOL_HYBRID;
return true;
}
bool ParseSessionMessage(const buzz::XmlElement* stanza,
SessionMessage* msg,
ParseError* error) {
msg->id = stanza->Attr(buzz::QN_ID);
msg->from = stanza->Attr(buzz::QN_FROM);
msg->to = stanza->Attr(buzz::QN_TO);
msg->stanza = stanza;
const buzz::XmlElement* jingle = stanza->FirstNamed(QN_JINGLE);
const buzz::XmlElement* session = stanza->FirstNamed(QN_GINGLE_SESSION);
if (jingle && session)
return ParseHybridSessionMessage(jingle, msg, error);
if (jingle != NULL)
return ParseJingleSessionMessage(jingle, msg, error);
if (session != NULL)
return ParseGingleSessionMessage(session, msg, error);
return false;
}
buzz::XmlElement* WriteGingleAction(const SessionMessage& msg,
const XmlElements& action_elems) {
buzz::XmlElement* session = new buzz::XmlElement(QN_GINGLE_SESSION, true);
session->AddAttr(buzz::QN_TYPE, ToGingleString(msg.type));
session->AddAttr(buzz::QN_ID, msg.sid);
session->AddAttr(QN_INITIATOR, msg.initiator);
AddXmlChildren(session, action_elems);
return session;
}
buzz::XmlElement* WriteJingleAction(const SessionMessage& msg,
const XmlElements& action_elems) {
buzz::XmlElement* jingle = new buzz::XmlElement(QN_JINGLE, true);
jingle->AddAttr(buzz::QN_ACTION, ToJingleString(msg.type));
jingle->AddAttr(QN_SID, msg.sid);
if (msg.type == ACTION_SESSION_INITIATE) {
jingle->AddAttr(QN_INITIATOR, msg.initiator);
}
AddXmlChildren(jingle, action_elems);
return jingle;
}
void WriteSessionMessage(const SessionMessage& msg,
const XmlElements& action_elems,
buzz::XmlElement* stanza) {
stanza->SetAttr(buzz::QN_TO, msg.to);
stanza->SetAttr(buzz::QN_TYPE, buzz::STR_SET);
if (msg.protocol == PROTOCOL_GINGLE) {
stanza->AddElement(WriteGingleAction(msg, action_elems));
} else {
stanza->AddElement(WriteJingleAction(msg, action_elems));
}
}
TransportParser* GetTransportParser(const TransportParserMap& trans_parsers,
const std::string& name) {
TransportParserMap::const_iterator map = trans_parsers.find(name);
if (map == trans_parsers.end()) {
return NULL;
} else {
return map->second;
}
}
bool ParseCandidates(SignalingProtocol protocol,
const buzz::XmlElement* candidates_elem,
const TransportParserMap& trans_parsers,
const std::string& transport_type,
Candidates* candidates,
ParseError* error) {
TransportParser* trans_parser =
GetTransportParser(trans_parsers, transport_type);
if (trans_parser == NULL)
return BadParse("unknown transport type: " + transport_type, error);
return trans_parser->ParseCandidates(protocol, candidates_elem,
candidates, error);
}
bool ParseGingleTransportInfos(const buzz::XmlElement* action_elem,
const ContentInfos& contents,
const TransportParserMap& trans_parsers,
TransportInfos* tinfos,
ParseError* error) {
TransportInfo tinfo(CN_OTHER, NS_GINGLE_P2P, Candidates());
if (!ParseCandidates(PROTOCOL_GINGLE, action_elem,
trans_parsers, NS_GINGLE_P2P,
&tinfo.candidates, error))
return false;
bool has_audio = FindContentInfoByName(contents, CN_AUDIO) != NULL;
bool has_video = FindContentInfoByName(contents, CN_VIDEO) != NULL;
// If we don't have media, no need to separate the candidates.
if (!has_audio && !has_video) {
tinfos->push_back(tinfo);
return true;
}
// If we have media, separate the candidates. Create the
// TransportInfo here to avoid copying the candidates.
TransportInfo audio_tinfo(CN_AUDIO, NS_GINGLE_P2P, Candidates());
TransportInfo video_tinfo(CN_VIDEO, NS_GINGLE_P2P, Candidates());
for (Candidates::iterator cand = tinfo.candidates.begin();
cand != tinfo.candidates.end(); cand++) {
if (cand->name() == GINGLE_CANDIDATE_NAME_RTP ||
cand->name() == GINGLE_CANDIDATE_NAME_RTCP) {
audio_tinfo.candidates.push_back(*cand);
} else if (cand->name() == GINGLE_CANDIDATE_NAME_VIDEO_RTP ||
cand->name() == GINGLE_CANDIDATE_NAME_VIDEO_RTCP) {
video_tinfo.candidates.push_back(*cand);
}
}
if (has_audio) {
tinfos->push_back(audio_tinfo);
}
if (has_video) {
tinfos->push_back(video_tinfo);
}
return true;
}
bool ParseJingleTransportInfo(const buzz::XmlElement* trans_elem,
const ContentInfo& content,
const TransportParserMap& trans_parsers,
TransportInfos* tinfos,
ParseError* error) {
std::string transport_type = trans_elem->Name().Namespace();
TransportInfo tinfo(content.name, transport_type, Candidates());
if (!ParseCandidates(PROTOCOL_JINGLE, trans_elem,
trans_parsers, transport_type,
&tinfo.candidates, error))
return false;
tinfos->push_back(tinfo);
return true;
}
bool ParseJingleTransportInfos(const buzz::XmlElement* jingle,
const ContentInfos& contents,
const TransportParserMap trans_parsers,
TransportInfos* tinfos,
ParseError* error) {
for (const buzz::XmlElement* pair_elem
= jingle->FirstNamed(QN_JINGLE_CONTENT);
pair_elem != NULL;
pair_elem = pair_elem->NextNamed(QN_JINGLE_CONTENT)) {
std::string content_name;
if (!RequireXmlAttr(pair_elem, QN_JINGLE_CONTENT_NAME,
&content_name, error))
return false;
const ContentInfo* content = FindContentInfoByName(contents, content_name);
if (!content)
return BadParse("Unknown content name: " + content_name, error);
const buzz::XmlElement* trans_elem;
if (!RequireXmlChild(pair_elem, LN_TRANSPORT, &trans_elem, error))
return false;
if (!ParseJingleTransportInfo(trans_elem, *content, trans_parsers,
tinfos, error))
return false;
}
return true;
}
buzz::XmlElement* NewTransportElement(const std::string& name) {
return new buzz::XmlElement(buzz::QName(name, LN_TRANSPORT), true);
}
bool WriteCandidates(SignalingProtocol protocol,
const std::string& trans_type,
const Candidates& candidates,
const TransportParserMap& trans_parsers,
XmlElements* elems,
WriteError* error) {
TransportParser* trans_parser = GetTransportParser(trans_parsers, trans_type);
if (trans_parser == NULL)
return BadWrite("unknown transport type: " + trans_type, error);
return trans_parser->WriteCandidates(protocol, candidates, elems, error);
}
bool WriteGingleTransportInfos(const TransportInfos& tinfos,
const TransportParserMap& trans_parsers,
XmlElements* elems,
WriteError* error) {
for (TransportInfos::const_iterator tinfo = tinfos.begin();
tinfo != tinfos.end(); ++tinfo) {
if (!WriteCandidates(PROTOCOL_GINGLE,
tinfo->transport_type, tinfo->candidates,
trans_parsers, elems, error))
return false;
}
return true;
}
bool WriteJingleTransportInfo(const TransportInfo& tinfo,
const TransportParserMap& trans_parsers,
XmlElements* elems,
WriteError* error) {
XmlElements candidate_elems;
if (!WriteCandidates(PROTOCOL_JINGLE,
tinfo.transport_type, tinfo.candidates, trans_parsers,
&candidate_elems, error))
return false;
buzz::XmlElement* trans_elem = NewTransportElement(tinfo.transport_type);
AddXmlChildren(trans_elem, candidate_elems);
elems->push_back(trans_elem);
return true;
}
void WriteJingleContentPair(const std::string name,
const XmlElements& pair_elems,
XmlElements* elems) {
buzz::XmlElement* pair_elem = new buzz::XmlElement(QN_JINGLE_CONTENT);
pair_elem->SetAttr(QN_JINGLE_CONTENT_NAME, name);
pair_elem->SetAttr(QN_CREATOR, LN_INITIATOR);
AddXmlChildren(pair_elem, pair_elems);
elems->push_back(pair_elem);
}
bool WriteJingleTransportInfos(const TransportInfos& tinfos,
const TransportParserMap& trans_parsers,
XmlElements* elems,
WriteError* error) {
for (TransportInfos::const_iterator tinfo = tinfos.begin();
tinfo != tinfos.end(); ++tinfo) {
XmlElements pair_elems;
if (!WriteJingleTransportInfo(*tinfo, trans_parsers,
&pair_elems, error))
return false;
WriteJingleContentPair(tinfo->content_name, pair_elems, elems);
}
return true;
}
ContentParser* GetContentParser(const ContentParserMap& content_parsers,
const std::string& type) {
ContentParserMap::const_iterator map = content_parsers.find(type);
if (map == content_parsers.end()) {
return NULL;
} else {
return map->second;
}
}
bool ParseContentInfo(SignalingProtocol protocol,
const std::string& name,
const std::string& type,
const buzz::XmlElement* elem,
const ContentParserMap& parsers,
ContentInfos* contents,
ParseError* error) {
ContentParser* parser = GetContentParser(parsers, type);
if (parser == NULL)
return BadParse("unknown application content: " + type, error);
const ContentDescription* desc;
if (!parser->ParseContent(protocol, elem, &desc, error))
return false;
contents->push_back(ContentInfo(name, type, desc));
return true;
}
bool ParseContentType(const buzz::XmlElement* parent_elem,
std::string* content_type,
const buzz::XmlElement** content_elem,
ParseError* error) {
if (!RequireXmlChild(parent_elem, LN_DESCRIPTION, content_elem, error))
return false;
*content_type = (*content_elem)->Name().Namespace();
return true;
}
bool ParseGingleContentInfos(const buzz::XmlElement* session,
const ContentParserMap& content_parsers,
ContentInfos* contents,
ParseError* error) {
std::string content_type;
const buzz::XmlElement* content_elem;
if (!ParseContentType(session, &content_type, &content_elem, error))
return false;
if (content_type == NS_GINGLE_VIDEO) {
// A parser parsing audio or video content should look at the
// namespace and only parse the codecs relevant to that namespace.
// We use this to control which codecs get parsed: first audio,
// then video.
talk_base::scoped_ptr<buzz::XmlElement> audio_elem(
new buzz::XmlElement(QN_GINGLE_AUDIO_CONTENT));
CopyXmlChildren(content_elem, audio_elem.get());
if (!ParseContentInfo(PROTOCOL_GINGLE, CN_AUDIO, NS_JINGLE_RTP,
audio_elem.get(), content_parsers,
contents, error))
return false;
if (!ParseContentInfo(PROTOCOL_GINGLE, CN_VIDEO, NS_JINGLE_RTP,
content_elem, content_parsers,
contents, error))
return false;
} else if (content_type == NS_GINGLE_AUDIO) {
if (!ParseContentInfo(PROTOCOL_GINGLE, CN_AUDIO, NS_JINGLE_RTP,
content_elem, content_parsers,
contents, error))
return false;
} else {
if (!ParseContentInfo(PROTOCOL_GINGLE, CN_OTHER, content_type,
content_elem, content_parsers,
contents, error))
return false;
}
return true;
}
bool ParseJingleContentInfos(const buzz::XmlElement* jingle,
const ContentParserMap& content_parsers,
ContentInfos* contents,
ParseError* error) {
for (const buzz::XmlElement* pair_elem
= jingle->FirstNamed(QN_JINGLE_CONTENT);
pair_elem != NULL;
pair_elem = pair_elem->NextNamed(QN_JINGLE_CONTENT)) {
std::string content_name;
if (!RequireXmlAttr(pair_elem, QN_JINGLE_CONTENT_NAME,
&content_name, error))
return false;
std::string content_type;
const buzz::XmlElement* content_elem;
if (!ParseContentType(pair_elem, &content_type, &content_elem, error))
return false;
if (!ParseContentInfo(PROTOCOL_JINGLE, content_name, content_type,
content_elem, content_parsers,
contents, error))
return false;
}
return true;
}
bool ParseJingleGroupInfos(const buzz::XmlElement* jingle,
ContentGroups* groups,
ParseError* error) {
for (const buzz::XmlElement* pair_elem
= jingle->FirstNamed(QN_JINGLE_DRAFT_GROUP);
pair_elem != NULL;
pair_elem = pair_elem->NextNamed(QN_JINGLE_DRAFT_GROUP)) {
std::string group_name;
if (!RequireXmlAttr(pair_elem, QN_JINGLE_DRAFT_GROUP_TYPE,
&group_name, error))
return false;
ContentGroup group(group_name);
for (const buzz::XmlElement* child_elem
= pair_elem->FirstNamed(QN_JINGLE_CONTENT);
child_elem != NULL;
child_elem = child_elem->NextNamed(QN_JINGLE_CONTENT)) {
std::string content_name;
if (!RequireXmlAttr(child_elem, QN_JINGLE_CONTENT_NAME,
&content_name, error))
return false;
group.AddContentName(content_name);
}
groups->push_back(group);
}
return true;
}
buzz::XmlElement* WriteContentInfo(SignalingProtocol protocol,
const ContentInfo& content,
const ContentParserMap& parsers,
WriteError* error) {
ContentParser* parser = GetContentParser(parsers, content.type);
if (parser == NULL) {
BadWrite("unknown content type: " + content.type, error);
return NULL;
}
buzz::XmlElement* elem = NULL;
if (!parser->WriteContent(protocol, content.description, &elem, error))
return NULL;
return elem;
}
bool WriteGingleContentInfos(const ContentInfos& contents,
const ContentParserMap& parsers,
XmlElements* elems,
WriteError* error) {
if (contents.size() == 1) {
buzz::XmlElement* elem = WriteContentInfo(
PROTOCOL_GINGLE, contents.front(), parsers, error);
if (!elem)
return false;
elems->push_back(elem);
} else if (contents.size() == 2 &&
contents.at(0).type == NS_JINGLE_RTP &&
contents.at(1).type == NS_JINGLE_RTP) {
// Special-case audio + video contents so that they are "merged"
// into one "video" content.
buzz::XmlElement* audio = WriteContentInfo(
PROTOCOL_GINGLE, contents.at(0), parsers, error);
if (!audio)
return false;
buzz::XmlElement* video = WriteContentInfo(
PROTOCOL_GINGLE, contents.at(1), parsers, error);
if (!video) {
delete audio;
return false;
}
CopyXmlChildren(audio, video);
elems->push_back(video);
delete audio;
} else {
return BadWrite("Gingle protocol may only have one content.", error);
}
return true;
}
const TransportInfo* GetTransportInfoByContentName(
const TransportInfos& tinfos, const std::string& content_name) {
for (TransportInfos::const_iterator tinfo = tinfos.begin();
tinfo != tinfos.end(); ++tinfo) {
if (content_name == tinfo->content_name) {
return &*tinfo;
}
}
return NULL;
}
bool WriteJingleContentPairs(const ContentInfos& contents,
const ContentParserMap& content_parsers,
const TransportInfos& tinfos,
const TransportParserMap& trans_parsers,
XmlElements* elems,
WriteError* error) {
for (ContentInfos::const_iterator content = contents.begin();
content != contents.end(); ++content) {
const TransportInfo* tinfo =
GetTransportInfoByContentName(tinfos, content->name);
if (!tinfo)
return BadWrite("No transport for content: " + content->name, error);
XmlElements pair_elems;
buzz::XmlElement* elem = WriteContentInfo(
PROTOCOL_JINGLE, *content, content_parsers, error);
if (!elem)
return false;
pair_elems.push_back(elem);
if (!WriteJingleTransportInfo(*tinfo, trans_parsers,
&pair_elems, error))
return false;
WriteJingleContentPair(content->name, pair_elems, elems);
}
return true;
}
bool WriteJingleGroupInfo(const ContentInfos& contents,
const ContentGroups& groups,
XmlElements* elems,
WriteError* error) {
if (!groups.empty()) {
buzz::XmlElement* pair_elem = new buzz::XmlElement(QN_JINGLE_DRAFT_GROUP);
pair_elem->SetAttr(QN_JINGLE_DRAFT_GROUP_TYPE, GROUP_TYPE_BUNDLE);
XmlElements pair_elems;
for (ContentInfos::const_iterator content = contents.begin();
content != contents.end(); ++content) {
buzz::XmlElement* child_elem =
new buzz::XmlElement(QN_JINGLE_CONTENT, false);
child_elem->SetAttr(QN_JINGLE_CONTENT_NAME, content->name);
pair_elems.push_back(child_elem);
}
AddXmlChildren(pair_elem, pair_elems);
elems->push_back(pair_elem);
}
return true;
}
bool ParseContentType(SignalingProtocol protocol,
const buzz::XmlElement* action_elem,
std::string* content_type,
ParseError* error) {
const buzz::XmlElement* content_elem;
if (protocol == PROTOCOL_GINGLE) {
if (!ParseContentType(action_elem, content_type, &content_elem, error))
return false;
// Internally, we only use NS_JINGLE_RTP.
if (*content_type == NS_GINGLE_AUDIO ||
*content_type == NS_GINGLE_VIDEO)
*content_type = NS_JINGLE_RTP;
} else {
const buzz::XmlElement* pair_elem
= action_elem->FirstNamed(QN_JINGLE_CONTENT);
if (pair_elem == NULL)
return BadParse("No contents found", error);
if (!ParseContentType(pair_elem, content_type, &content_elem, error))
return false;
// If there is more than one content type, return an error.
for (; pair_elem != NULL;
pair_elem = pair_elem->NextNamed(QN_JINGLE_CONTENT)) {
std::string content_type2;
if (!ParseContentType(pair_elem, &content_type2, &content_elem, error))
return false;
if (content_type2 != *content_type)
return BadParse("More than one content type found", error);
}
}
return true;
}
static bool ParseContentMessage(
SignalingProtocol protocol,
const buzz::XmlElement* action_elem,
bool expect_transports,
const ContentParserMap& content_parsers,
const TransportParserMap& trans_parsers,
SessionInitiate* init,
ParseError* error) {
init->owns_contents = true;
if (protocol == PROTOCOL_GINGLE) {
if (!ParseGingleContentInfos(action_elem, content_parsers,
&init->contents, error))
return false;
if (expect_transports &&
!ParseGingleTransportInfos(action_elem, init->contents, trans_parsers,
&init->transports, error))
return false;
} else {
if (!ParseJingleContentInfos(action_elem, content_parsers,
&init->contents, error))
return false;
if (!ParseJingleGroupInfos(action_elem, &init->groups, error))
return false;
if (expect_transports &&
!ParseJingleTransportInfos(action_elem, init->contents, trans_parsers,
&init->transports, error))
return false;
}
return true;
}
static bool WriteContentMessage(
SignalingProtocol protocol,
const ContentInfos& contents,
const TransportInfos& tinfos,
const ContentParserMap& content_parsers,
const TransportParserMap& transport_parsers,
const ContentGroups& groups,
XmlElements* elems,
WriteError* error) {
if (protocol == PROTOCOL_GINGLE) {
if (!WriteGingleContentInfos(contents, content_parsers, elems, error))
return false;
if (!WriteGingleTransportInfos(tinfos, transport_parsers,
elems, error))
return false;
} else {
if (!WriteJingleContentPairs(contents, content_parsers,
tinfos, transport_parsers,
elems, error))
return false;
if (!WriteJingleGroupInfo(contents, groups, elems, error))
return false;
}
return true;
}
bool ParseSessionInitiate(SignalingProtocol protocol,
const buzz::XmlElement* action_elem,
const ContentParserMap& content_parsers,
const TransportParserMap& trans_parsers,
SessionInitiate* init,
ParseError* error) {
bool expect_transports = true;
return ParseContentMessage(protocol, action_elem, expect_transports,
content_parsers, trans_parsers,
init, error);
}
bool WriteSessionInitiate(SignalingProtocol protocol,
const ContentInfos& contents,
const TransportInfos& tinfos,
const ContentParserMap& content_parsers,
const TransportParserMap& transport_parsers,
const ContentGroups& groups,
XmlElements* elems,
WriteError* error) {
return WriteContentMessage(protocol, contents, tinfos,
content_parsers, transport_parsers, groups,
elems, error);
}
bool ParseSessionAccept(SignalingProtocol protocol,
const buzz::XmlElement* action_elem,
const ContentParserMap& content_parsers,
const TransportParserMap& transport_parsers,
SessionAccept* accept,
ParseError* error) {
bool expect_transports = true;
return ParseContentMessage(protocol, action_elem, expect_transports,
content_parsers, transport_parsers,
accept, error);
}
bool WriteSessionAccept(SignalingProtocol protocol,
const ContentInfos& contents,
const TransportInfos& tinfos,
const ContentParserMap& content_parsers,
const TransportParserMap& transport_parsers,
const ContentGroups& groups,
XmlElements* elems,
WriteError* error) {
return WriteContentMessage(protocol, contents, tinfos,
content_parsers, transport_parsers, groups,
elems, error);
}
bool ParseSessionTerminate(SignalingProtocol protocol,
const buzz::XmlElement* action_elem,
SessionTerminate* term,
ParseError* error) {
if (protocol == PROTOCOL_GINGLE) {
const buzz::XmlElement* reason_elem = action_elem->FirstElement();
if (reason_elem != NULL) {
term->reason = reason_elem->Name().LocalPart();
const buzz::XmlElement *debug_elem = reason_elem->FirstElement();
if (debug_elem != NULL) {
term->debug_reason = debug_elem->Name().LocalPart();
}
}
return true;
} else {
const buzz::XmlElement* reason_elem =
action_elem->FirstNamed(QN_JINGLE_REASON);
if (reason_elem) {
reason_elem = reason_elem->FirstElement();
if (reason_elem) {
term->reason = reason_elem->Name().LocalPart();
}
}
return true;
}
}
void WriteSessionTerminate(SignalingProtocol protocol,
const SessionTerminate& term,
XmlElements* elems) {
if (protocol == PROTOCOL_GINGLE) {
elems->push_back(new buzz::XmlElement(buzz::QName(NS_GINGLE, term.reason)));
} else {
if (!term.reason.empty()) {
buzz::XmlElement* reason_elem = new buzz::XmlElement(QN_JINGLE_REASON);
reason_elem->AddElement(new buzz::XmlElement(
buzz::QName(NS_JINGLE, term.reason)));
elems->push_back(reason_elem);
}
}
}
bool ParseDescriptionInfo(SignalingProtocol protocol,
const buzz::XmlElement* action_elem,
const ContentParserMap& content_parsers,
const TransportParserMap& transport_parsers,
DescriptionInfo* description_info,
ParseError* error) {
bool expect_transports = false;
return ParseContentMessage(protocol, action_elem, expect_transports,
content_parsers, transport_parsers,
description_info, error);
}
bool ParseTransportInfos(SignalingProtocol protocol,
const buzz::XmlElement* action_elem,
const ContentInfos& contents,
const TransportParserMap& trans_parsers,
TransportInfos* tinfos,
ParseError* error) {
if (protocol == PROTOCOL_GINGLE) {
return ParseGingleTransportInfos(
action_elem, contents, trans_parsers, tinfos, error);
} else {
return ParseJingleTransportInfos(
action_elem, contents, trans_parsers, tinfos, error);
}
}
bool WriteTransportInfos(SignalingProtocol protocol,
const TransportInfos& tinfos,
const TransportParserMap& trans_parsers,
XmlElements* elems,
WriteError* error) {
if (protocol == PROTOCOL_GINGLE) {
return WriteGingleTransportInfos(tinfos, trans_parsers,
elems, error);
} else {
return WriteJingleTransportInfos(tinfos, trans_parsers,
elems, error);
}
}
bool GetUriTarget(const std::string& prefix, const std::string& str,
std::string* after) {
size_t pos = str.find(prefix);
if (pos == std::string::npos)
return false;
*after = str.substr(pos + prefix.size(), std::string::npos);
return true;
}
bool FindSessionRedirect(const buzz::XmlElement* stanza,
SessionRedirect* redirect) {
const buzz::XmlElement* error_elem = GetXmlChild(stanza, LN_ERROR);
if (error_elem == NULL)
return false;
const buzz::XmlElement* redirect_elem =
error_elem->FirstNamed(QN_GINGLE_REDIRECT);
if (redirect_elem == NULL)
redirect_elem = error_elem->FirstNamed(buzz::QN_STANZA_REDIRECT);
if (redirect_elem == NULL)
return false;
if (!GetUriTarget(STR_REDIRECT_PREFIX, redirect_elem->BodyText(),
&redirect->target))
return false;
return true;
}
} // namespace cricket
| muzili/libjingle-0.6.14 | talk/p2p/base/sessionmessages.cc | C++ | bsd-3-clause | 34,550 |
autocommit off;
create table t (a int);
create view v1 as select * from t where a > 10 with check option;
create view v as select * from v1 where a > 5 with cascaded check option;
insert into v values (7);
rollback;
| CUBRID/cubrid-testcases | medium/_05_err_x/cases/check6.sql | SQL | bsd-3-clause | 216 |
from __future__ import division, absolute_import, print_function
import collections
import tempfile
import sys
import shutil
import warnings
import operator
import io
import itertools
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin__ as builtins
from decimal import Decimal
import numpy as np
from nose import SkipTest
from numpy.compat import asbytes, getexception, strchar, unicode, sixu
from test_print import in_foreign_locale
from numpy.core.multiarray_tests import (
test_neighborhood_iterator, test_neighborhood_iterator_oob,
test_pydatamem_seteventhook_start, test_pydatamem_seteventhook_end,
test_inplace_increment, get_buffer_info, test_as_c_array
)
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_raises,
assert_equal, assert_almost_equal, assert_array_equal,
assert_array_almost_equal, assert_allclose,
assert_array_less, runstring, dec
)
# Need to test an object that does not fully implement math interface
from datetime import timedelta
if sys.version_info[:2] > (3, 2):
# In Python 3.3 the representation of empty shape, strides and suboffsets
# is an empty tuple instead of None.
# http://docs.python.org/dev/whatsnew/3.3.html#api-changes
EMPTY = ()
else:
EMPTY = None
class TestFlags(TestCase):
def setUp(self):
self.a = np.arange(10)
def test_writeable(self):
mydict = locals()
self.a.flags.writeable = False
self.assertRaises(ValueError, runstring, 'self.a[0] = 3', mydict)
self.assertRaises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict)
self.a.flags.writeable = True
self.a[0] = 5
self.a[0] = 0
def test_otherflags(self):
assert_equal(self.a.flags.carray, True)
assert_equal(self.a.flags.farray, False)
assert_equal(self.a.flags.behaved, True)
assert_equal(self.a.flags.fnc, False)
assert_equal(self.a.flags.forc, True)
assert_equal(self.a.flags.owndata, True)
assert_equal(self.a.flags.writeable, True)
assert_equal(self.a.flags.aligned, True)
assert_equal(self.a.flags.updateifcopy, False)
def test_string_align(self):
a = np.zeros(4, dtype=np.dtype('|S4'))
assert_(a.flags.aligned)
# not power of two are accessed bytewise and thus considered aligned
a = np.zeros(5, dtype=np.dtype('|S4'))
assert_(a.flags.aligned)
def test_void_align(self):
a = np.zeros(4, dtype=np.dtype([("a", "i4"), ("b", "i4")]))
assert_(a.flags.aligned)
class TestHash(TestCase):
# see #3793
def test_int(self):
for st, ut, s in [(np.int8, np.uint8, 8),
(np.int16, np.uint16, 16),
(np.int32, np.uint32, 32),
(np.int64, np.uint64, 64)]:
for i in range(1, s):
assert_equal(hash(st(-2**i)), hash(-2**i),
err_msg="%r: -2**%d" % (st, i))
assert_equal(hash(st(2**(i - 1))), hash(2**(i - 1)),
err_msg="%r: 2**%d" % (st, i - 1))
assert_equal(hash(st(2**i - 1)), hash(2**i - 1),
err_msg="%r: 2**%d - 1" % (st, i))
i = max(i - 1, 1)
assert_equal(hash(ut(2**(i - 1))), hash(2**(i - 1)),
err_msg="%r: 2**%d" % (ut, i - 1))
assert_equal(hash(ut(2**i - 1)), hash(2**i - 1),
err_msg="%r: 2**%d - 1" % (ut, i))
class TestAttributes(TestCase):
def setUp(self):
self.one = np.arange(10)
self.two = np.arange(20).reshape(4, 5)
self.three = np.arange(60, dtype=np.float64).reshape(2, 5, 6)
def test_attributes(self):
assert_equal(self.one.shape, (10,))
assert_equal(self.two.shape, (4, 5))
assert_equal(self.three.shape, (2, 5, 6))
self.three.shape = (10, 3, 2)
assert_equal(self.three.shape, (10, 3, 2))
self.three.shape = (2, 5, 6)
assert_equal(self.one.strides, (self.one.itemsize,))
num = self.two.itemsize
assert_equal(self.two.strides, (5*num, num))
num = self.three.itemsize
assert_equal(self.three.strides, (30*num, 6*num, num))
assert_equal(self.one.ndim, 1)
assert_equal(self.two.ndim, 2)
assert_equal(self.three.ndim, 3)
num = self.two.itemsize
assert_equal(self.two.size, 20)
assert_equal(self.two.nbytes, 20*num)
assert_equal(self.two.itemsize, self.two.dtype.itemsize)
assert_equal(self.two.base, np.arange(20))
def test_dtypeattr(self):
assert_equal(self.one.dtype, np.dtype(np.int_))
assert_equal(self.three.dtype, np.dtype(np.float_))
assert_equal(self.one.dtype.char, 'l')
assert_equal(self.three.dtype.char, 'd')
self.assertTrue(self.three.dtype.str[0] in '<>')
assert_equal(self.one.dtype.str[1], 'i')
assert_equal(self.three.dtype.str[1], 'f')
def test_int_subclassing(self):
# Regression test for https://github.com/numpy/numpy/pull/3526
numpy_int = np.int_(0)
if sys.version_info[0] >= 3:
# On Py3k int_ should not inherit from int, because it's not fixed-width anymore
assert_equal(isinstance(numpy_int, int), False)
else:
# Otherwise, it should inherit from int...
assert_equal(isinstance(numpy_int, int), True)
# ... and fast-path checks on C-API level should also work
from numpy.core.multiarray_tests import test_int_subclass
assert_equal(test_int_subclass(numpy_int), True)
def test_stridesattr(self):
x = self.one
def make_array(size, offset, strides):
return np.ndarray(size, buffer=x, dtype=int,
offset=offset*x.itemsize,
strides=strides*x.itemsize)
assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1]))
self.assertRaises(ValueError, make_array, 4, 4, -2)
self.assertRaises(ValueError, make_array, 4, 2, -1)
self.assertRaises(ValueError, make_array, 8, 3, 1)
assert_equal(make_array(8, 3, 0), np.array([3]*8))
# Check behavior reported in gh-2503:
self.assertRaises(ValueError, make_array, (2, 3), 5, np.array([-2, -3]))
make_array(0, 0, 10)
def test_set_stridesattr(self):
x = self.one
def make_array(size, offset, strides):
try:
r = np.ndarray([size], dtype=int, buffer=x, offset=offset*x.itemsize)
except:
raise RuntimeError(getexception())
r.strides = strides = strides*x.itemsize
return r
assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1]))
assert_equal(make_array(7, 3, 1), np.array([3, 4, 5, 6, 7, 8, 9]))
self.assertRaises(ValueError, make_array, 4, 4, -2)
self.assertRaises(ValueError, make_array, 4, 2, -1)
self.assertRaises(RuntimeError, make_array, 8, 3, 1)
# Check that the true extent of the array is used.
# Test relies on as_strided base not exposing a buffer.
x = np.lib.stride_tricks.as_strided(np.arange(1), (10, 10), (0, 0))
def set_strides(arr, strides):
arr.strides = strides
self.assertRaises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize))
# Test for offset calculations:
x = np.lib.stride_tricks.as_strided(np.arange(10, dtype=np.int8)[-1],
shape=(10,), strides=(-1,))
self.assertRaises(ValueError, set_strides, x[::-1], -1)
a = x[::-1]
a.strides = 1
a[::2].strides = 2
def test_fill(self):
for t in "?bhilqpBHILQPfdgFDGO":
x = np.empty((3, 2, 1), t)
y = np.empty((3, 2, 1), t)
x.fill(1)
y[...] = 1
assert_equal(x, y)
def test_fill_max_uint64(self):
x = np.empty((3, 2, 1), dtype=np.uint64)
y = np.empty((3, 2, 1), dtype=np.uint64)
value = 2**64 - 1
y[...] = value
x.fill(value)
assert_array_equal(x, y)
def test_fill_struct_array(self):
# Filling from a scalar
x = np.array([(0, 0.0), (1, 1.0)], dtype='i4,f8')
x.fill(x[0])
assert_equal(x['f1'][1], x['f1'][0])
# Filling from a tuple that can be converted
# to a scalar
x = np.zeros(2, dtype=[('a', 'f8'), ('b', 'i4')])
x.fill((3.5, -2))
assert_array_equal(x['a'], [3.5, 3.5])
assert_array_equal(x['b'], [-2, -2])
class TestArrayConstruction(TestCase):
def test_array(self):
d = np.ones(6)
r = np.array([d, d])
assert_equal(r, np.ones((2, 6)))
d = np.ones(6)
tgt = np.ones((2, 6))
r = np.array([d, d])
assert_equal(r, tgt)
tgt[1] = 2
r = np.array([d, d + 1])
assert_equal(r, tgt)
d = np.ones(6)
r = np.array([[d, d]])
assert_equal(r, np.ones((1, 2, 6)))
d = np.ones(6)
r = np.array([[d, d], [d, d]])
assert_equal(r, np.ones((2, 2, 6)))
d = np.ones((6, 6))
r = np.array([d, d])
assert_equal(r, np.ones((2, 6, 6)))
d = np.ones((6, ))
r = np.array([[d, d + 1], d + 2])
assert_equal(len(r), 2)
assert_equal(r[0], [d, d + 1])
assert_equal(r[1], d + 2)
tgt = np.ones((2, 3), dtype=np.bool)
tgt[0, 2] = False
tgt[1, 0:2] = False
r = np.array([[True, True, False], [False, False, True]])
assert_equal(r, tgt)
r = np.array([[True, False], [True, False], [False, True]])
assert_equal(r, tgt.T)
def test_array_empty(self):
assert_raises(TypeError, np.array)
def test_array_copy_false(self):
d = np.array([1, 2, 3])
e = np.array(d, copy=False)
d[1] = 3
assert_array_equal(e, [1, 3, 3])
e = np.array(d, copy=False, order='F')
d[1] = 4
assert_array_equal(e, [1, 4, 3])
e[2] = 7
assert_array_equal(d, [1, 4, 7])
def test_array_copy_true(self):
d = np.array([[1,2,3], [1, 2, 3]])
e = np.array(d, copy=True)
d[0, 1] = 3
e[0, 2] = -7
assert_array_equal(e, [[1, 2, -7], [1, 2, 3]])
assert_array_equal(d, [[1, 3, 3], [1, 2, 3]])
e = np.array(d, copy=True, order='F')
d[0, 1] = 5
e[0, 2] = 7
assert_array_equal(e, [[1, 3, 7], [1, 2, 3]])
assert_array_equal(d, [[1, 5, 3], [1,2,3]])
def test_array_cont(self):
d = np.ones(10)[::2]
assert_(np.ascontiguousarray(d).flags.c_contiguous)
assert_(np.ascontiguousarray(d).flags.f_contiguous)
assert_(np.asfortranarray(d).flags.c_contiguous)
assert_(np.asfortranarray(d).flags.f_contiguous)
d = np.ones((10, 10))[::2,::2]
assert_(np.ascontiguousarray(d).flags.c_contiguous)
assert_(np.asfortranarray(d).flags.f_contiguous)
class TestAssignment(TestCase):
def test_assignment_broadcasting(self):
a = np.arange(6).reshape(2, 3)
# Broadcasting the input to the output
a[...] = np.arange(3)
assert_equal(a, [[0, 1, 2], [0, 1, 2]])
a[...] = np.arange(2).reshape(2, 1)
assert_equal(a, [[0, 0, 0], [1, 1, 1]])
# For compatibility with <= 1.5, a limited version of broadcasting
# the output to the input.
#
# This behavior is inconsistent with NumPy broadcasting
# in general, because it only uses one of the two broadcasting
# rules (adding a new "1" dimension to the left of the shape),
# applied to the output instead of an input. In NumPy 2.0, this kind
# of broadcasting assignment will likely be disallowed.
a[...] = np.arange(6)[::-1].reshape(1, 2, 3)
assert_equal(a, [[5, 4, 3], [2, 1, 0]])
# The other type of broadcasting would require a reduction operation.
def assign(a, b):
a[...] = b
assert_raises(ValueError, assign, a, np.arange(12).reshape(2, 2, 3))
def test_assignment_errors(self):
# Address issue #2276
class C:
pass
a = np.zeros(1)
def assign(v):
a[0] = v
assert_raises((AttributeError, TypeError), assign, C())
assert_raises(ValueError, assign, [1])
class TestDtypedescr(TestCase):
def test_construction(self):
d1 = np.dtype('i4')
assert_equal(d1, np.dtype(np.int32))
d2 = np.dtype('f8')
assert_equal(d2, np.dtype(np.float64))
def test_byteorders(self):
self.assertNotEqual(np.dtype('<i4'), np.dtype('>i4'))
self.assertNotEqual(np.dtype([('a', '<i4')]), np.dtype([('a', '>i4')]))
class TestZeroRank(TestCase):
def setUp(self):
self.d = np.array(0), np.array('x', object)
def test_ellipsis_subscript(self):
a, b = self.d
self.assertEqual(a[...], 0)
self.assertEqual(b[...], 'x')
self.assertTrue(a[...].base is a) # `a[...] is a` in numpy <1.9.
self.assertTrue(b[...].base is b) # `b[...] is b` in numpy <1.9.
def test_empty_subscript(self):
a, b = self.d
self.assertEqual(a[()], 0)
self.assertEqual(b[()], 'x')
self.assertTrue(type(a[()]) is a.dtype.type)
self.assertTrue(type(b[()]) is str)
def test_invalid_subscript(self):
a, b = self.d
self.assertRaises(IndexError, lambda x: x[0], a)
self.assertRaises(IndexError, lambda x: x[0], b)
self.assertRaises(IndexError, lambda x: x[np.array([], int)], a)
self.assertRaises(IndexError, lambda x: x[np.array([], int)], b)
def test_ellipsis_subscript_assignment(self):
a, b = self.d
a[...] = 42
self.assertEqual(a, 42)
b[...] = ''
self.assertEqual(b.item(), '')
def test_empty_subscript_assignment(self):
a, b = self.d
a[()] = 42
self.assertEqual(a, 42)
b[()] = ''
self.assertEqual(b.item(), '')
def test_invalid_subscript_assignment(self):
a, b = self.d
def assign(x, i, v):
x[i] = v
self.assertRaises(IndexError, assign, a, 0, 42)
self.assertRaises(IndexError, assign, b, 0, '')
self.assertRaises(ValueError, assign, a, (), '')
def test_newaxis(self):
a, b = self.d
self.assertEqual(a[np.newaxis].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ...].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1))
self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10)
def test_invalid_newaxis(self):
a, b = self.d
def subscript(x, i):
x[i]
self.assertRaises(IndexError, subscript, a, (np.newaxis, 0))
self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50)
def test_constructor(self):
x = np.ndarray(())
x[()] = 5
self.assertEqual(x[()], 5)
y = np.ndarray((), buffer=x)
y[()] = 6
self.assertEqual(x[()], 6)
def test_output(self):
x = np.array(2)
self.assertRaises(ValueError, np.add, x, [1], x)
class TestScalarIndexing(TestCase):
def setUp(self):
self.d = np.array([0, 1])[0]
def test_ellipsis_subscript(self):
a = self.d
self.assertEqual(a[...], 0)
self.assertEqual(a[...].shape, ())
def test_empty_subscript(self):
a = self.d
self.assertEqual(a[()], 0)
self.assertEqual(a[()].shape, ())
def test_invalid_subscript(self):
a = self.d
self.assertRaises(IndexError, lambda x: x[0], a)
self.assertRaises(IndexError, lambda x: x[np.array([], int)], a)
def test_invalid_subscript_assignment(self):
a = self.d
def assign(x, i, v):
x[i] = v
self.assertRaises(TypeError, assign, a, 0, 42)
def test_newaxis(self):
a = self.d
self.assertEqual(a[np.newaxis].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ...].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1))
self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10)
def test_invalid_newaxis(self):
a = self.d
def subscript(x, i):
x[i]
self.assertRaises(IndexError, subscript, a, (np.newaxis, 0))
self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50)
def test_overlapping_assignment(self):
# With positive strides
a = np.arange(4)
a[:-1] = a[1:]
assert_equal(a, [1, 2, 3, 3])
a = np.arange(4)
a[1:] = a[:-1]
assert_equal(a, [0, 0, 1, 2])
# With positive and negative strides
a = np.arange(4)
a[:] = a[::-1]
assert_equal(a, [3, 2, 1, 0])
a = np.arange(6).reshape(2, 3)
a[::-1,:] = a[:, ::-1]
assert_equal(a, [[5, 4, 3], [2, 1, 0]])
a = np.arange(6).reshape(2, 3)
a[::-1, ::-1] = a[:, ::-1]
assert_equal(a, [[3, 4, 5], [0, 1, 2]])
# With just one element overlapping
a = np.arange(5)
a[:3] = a[2:]
assert_equal(a, [2, 3, 4, 3, 4])
a = np.arange(5)
a[2:] = a[:3]
assert_equal(a, [0, 1, 0, 1, 2])
a = np.arange(5)
a[2::-1] = a[2:]
assert_equal(a, [4, 3, 2, 3, 4])
a = np.arange(5)
a[2:] = a[2::-1]
assert_equal(a, [0, 1, 2, 1, 0])
a = np.arange(5)
a[2::-1] = a[:1:-1]
assert_equal(a, [2, 3, 4, 3, 4])
a = np.arange(5)
a[:1:-1] = a[2::-1]
assert_equal(a, [0, 1, 0, 1, 2])
class TestCreation(TestCase):
def test_from_attribute(self):
class x(object):
def __array__(self, dtype=None):
pass
self.assertRaises(ValueError, np.array, x())
def test_from_string(self):
types = np.typecodes['AllInteger'] + np.typecodes['Float']
nstr = ['123', '123']
result = np.array([123, 123], dtype=int)
for type in types:
msg = 'String conversion for %s' % type
assert_equal(np.array(nstr, dtype=type), result, err_msg=msg)
def test_void(self):
arr = np.array([], dtype='V')
assert_equal(arr.dtype.kind, 'V')
def test_zeros(self):
types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
for dt in types:
d = np.zeros((13,), dtype=dt)
assert_equal(np.count_nonzero(d), 0)
# true for ieee floats
assert_equal(d.sum(), 0)
assert_(not d.any())
d = np.zeros(2, dtype='(2,4)i4')
assert_equal(np.count_nonzero(d), 0)
assert_equal(d.sum(), 0)
assert_(not d.any())
d = np.zeros(2, dtype='4i4')
assert_equal(np.count_nonzero(d), 0)
assert_equal(d.sum(), 0)
assert_(not d.any())
d = np.zeros(2, dtype='(2,4)i4, (2,4)i4')
assert_equal(np.count_nonzero(d), 0)
@dec.slow
def test_zeros_big(self):
# test big array as they might be allocated different by the sytem
types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
for dt in types:
d = np.zeros((30 * 1024**2,), dtype=dt)
assert_(not d.any())
def test_zeros_obj(self):
# test initialization from PyLong(0)
d = np.zeros((13,), dtype=object)
assert_array_equal(d, [0] * 13)
assert_equal(np.count_nonzero(d), 0)
def test_zeros_obj_obj(self):
d = np.zeros(10, dtype=[('k', object, 2)])
assert_array_equal(d['k'], 0)
def test_zeros_like_like_zeros(self):
# test zeros_like returns the same as zeros
for c in np.typecodes['All']:
if c == 'V':
continue
d = np.zeros((3,3), dtype=c)
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
# explicitly check some special cases
d = np.zeros((3,3), dtype='S5')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='U5')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='<i4')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='>i4')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='<M8[s]')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='>M8[s]')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='f4,f4')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
def test_empty_unicode(self):
# don't throw decode errors on garbage memory
for i in range(5, 100, 5):
d = np.empty(i, dtype='U')
str(d)
def test_sequence_non_homogenous(self):
assert_equal(np.array([4, 2**80]).dtype, np.object)
assert_equal(np.array([4, 2**80, 4]).dtype, np.object)
assert_equal(np.array([2**80, 4]).dtype, np.object)
assert_equal(np.array([2**80] * 3).dtype, np.object)
assert_equal(np.array([[1, 1],[1j, 1j]]).dtype, np.complex)
assert_equal(np.array([[1j, 1j],[1, 1]]).dtype, np.complex)
assert_equal(np.array([[1, 1, 1],[1, 1j, 1.], [1, 1, 1]]).dtype, np.complex)
@dec.skipif(sys.version_info[0] >= 3)
def test_sequence_long(self):
assert_equal(np.array([long(4), long(4)]).dtype, np.long)
assert_equal(np.array([long(4), 2**80]).dtype, np.object)
assert_equal(np.array([long(4), 2**80, long(4)]).dtype, np.object)
assert_equal(np.array([2**80, long(4)]).dtype, np.object)
def test_non_sequence_sequence(self):
"""Should not segfault.
Class Fail breaks the sequence protocol for new style classes, i.e.,
those derived from object. Class Map is a mapping type indicated by
raising a ValueError. At some point we may raise a warning instead
of an error in the Fail case.
"""
class Fail(object):
def __len__(self):
return 1
def __getitem__(self, index):
raise ValueError()
class Map(object):
def __len__(self):
return 1
def __getitem__(self, index):
raise KeyError()
a = np.array([Map()])
assert_(a.shape == (1,))
assert_(a.dtype == np.dtype(object))
assert_raises(ValueError, np.array, [Fail()])
def test_no_len_object_type(self):
# gh-5100, want object array from iterable object without len()
class Point2:
def __init__(self):
pass
def __getitem__(self, ind):
if ind in [0, 1]:
return ind
else:
raise IndexError()
d = np.array([Point2(), Point2(), Point2()])
assert_equal(d.dtype, np.dtype(object))
class TestStructured(TestCase):
def test_subarray_field_access(self):
a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))])
a['a'] = np.arange(60).reshape(3, 5, 2, 2)
# Since the subarray is always in C-order, a transpose
# does not swap the subarray:
assert_array_equal(a.T['a'], a['a'].transpose(1, 0, 2, 3))
# In Fortran order, the subarray gets appended
# like in all other cases, not prepended as a special case
b = a.copy(order='F')
assert_equal(a['a'].shape, b['a'].shape)
assert_equal(a.T['a'].shape, a.T.copy()['a'].shape)
def test_subarray_comparison(self):
# Check that comparisons between record arrays with
# multi-dimensional field types work properly
a = np.rec.fromrecords(
[([1, 2, 3], 'a', [[1, 2], [3, 4]]), ([3, 3, 3], 'b', [[0, 0], [0, 0]])],
dtype=[('a', ('f4', 3)), ('b', np.object), ('c', ('i4', (2, 2)))])
b = a.copy()
assert_equal(a == b, [True, True])
assert_equal(a != b, [False, False])
b[1].b = 'c'
assert_equal(a == b, [True, False])
assert_equal(a != b, [False, True])
for i in range(3):
b[0].a = a[0].a
b[0].a[i] = 5
assert_equal(a == b, [False, False])
assert_equal(a != b, [True, True])
for i in range(2):
for j in range(2):
b = a.copy()
b[0].c[i, j] = 10
assert_equal(a == b, [False, True])
assert_equal(a != b, [True, False])
# Check that broadcasting with a subarray works
a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8')])
b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8')])
assert_equal(a == b, [[True, True, False], [False, False, True]])
assert_equal(b == a, [[True, True, False], [False, False, True]])
a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8', (1,))])
b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8', (1,))])
assert_equal(a == b, [[True, True, False], [False, False, True]])
assert_equal(b == a, [[True, True, False], [False, False, True]])
a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))])
b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))])
assert_equal(a == b, [[True, False, False], [False, False, True]])
assert_equal(b == a, [[True, False, False], [False, False, True]])
# Check that broadcasting Fortran-style arrays with a subarray work
a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))], order='F')
b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))])
assert_equal(a == b, [[True, False, False], [False, False, True]])
assert_equal(b == a, [[True, False, False], [False, False, True]])
# Check that incompatible sub-array shapes don't result to broadcasting
x = np.zeros((1,), dtype=[('a', ('f4', (1, 2))), ('b', 'i1')])
y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')])
# This comparison invokes deprecated behaviour, and will probably
# start raising an error eventually. What we really care about in this
# test is just that it doesn't return True.
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
assert_equal(x == y, False)
x = np.zeros((1,), dtype=[('a', ('f4', (2, 1))), ('b', 'i1')])
y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')])
# This comparison invokes deprecated behaviour, and will probably
# start raising an error eventually. What we really care about in this
# test is just that it doesn't return True.
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
assert_equal(x == y, False)
# Check that structured arrays that are different only in
# byte-order work
a = np.array([(5, 42), (10, 1)], dtype=[('a', '>i8'), ('b', '<f8')])
b = np.array([(5, 43), (10, 1)], dtype=[('a', '<i8'), ('b', '>f8')])
assert_equal(a == b, [False, True])
def test_casting(self):
# Check that casting a structured array to change its byte order
# works
a = np.array([(1,)], dtype=[('a', '<i4')])
assert_(np.can_cast(a.dtype, [('a', '>i4')], casting='unsafe'))
b = a.astype([('a', '>i4')])
assert_equal(b, a.byteswap().newbyteorder())
assert_equal(a['a'][0], b['a'][0])
# Check that equality comparison works on structured arrays if
# they are 'equiv'-castable
a = np.array([(5, 42), (10, 1)], dtype=[('a', '>i4'), ('b', '<f8')])
b = np.array([(42, 5), (1, 10)], dtype=[('b', '>f8'), ('a', '<i4')])
assert_(np.can_cast(a.dtype, b.dtype, casting='equiv'))
assert_equal(a == b, [True, True])
# Check that 'equiv' casting can reorder fields and change byte
# order
assert_(np.can_cast(a.dtype, b.dtype, casting='equiv'))
c = a.astype(b.dtype, casting='equiv')
assert_equal(a == c, [True, True])
# Check that 'safe' casting can change byte order and up-cast
# fields
t = [('a', '<i8'), ('b', '>f8')]
assert_(np.can_cast(a.dtype, t, casting='safe'))
c = a.astype(t, casting='safe')
assert_equal((c == np.array([(5, 42), (10, 1)], dtype=t)),
[True, True])
# Check that 'same_kind' casting can change byte order and
# change field widths within a "kind"
t = [('a', '<i4'), ('b', '>f4')]
assert_(np.can_cast(a.dtype, t, casting='same_kind'))
c = a.astype(t, casting='same_kind')
assert_equal((c == np.array([(5, 42), (10, 1)], dtype=t)),
[True, True])
# Check that casting fails if the casting rule should fail on
# any of the fields
t = [('a', '>i8'), ('b', '<f4')]
assert_(not np.can_cast(a.dtype, t, casting='safe'))
assert_raises(TypeError, a.astype, t, casting='safe')
t = [('a', '>i2'), ('b', '<f8')]
assert_(not np.can_cast(a.dtype, t, casting='equiv'))
assert_raises(TypeError, a.astype, t, casting='equiv')
t = [('a', '>i8'), ('b', '<i2')]
assert_(not np.can_cast(a.dtype, t, casting='same_kind'))
assert_raises(TypeError, a.astype, t, casting='same_kind')
assert_(not np.can_cast(a.dtype, b.dtype, casting='no'))
assert_raises(TypeError, a.astype, b.dtype, casting='no')
# Check that non-'unsafe' casting can't change the set of field names
for casting in ['no', 'safe', 'equiv', 'same_kind']:
t = [('a', '>i4')]
assert_(not np.can_cast(a.dtype, t, casting=casting))
t = [('a', '>i4'), ('b', '<f8'), ('c', 'i4')]
assert_(not np.can_cast(a.dtype, t, casting=casting))
def test_objview(self):
# https://github.com/numpy/numpy/issues/3286
a = np.array([], dtype=[('a', 'f'), ('b', 'f'), ('c', 'O')])
a[['a', 'b']] # TypeError?
# https://github.com/numpy/numpy/issues/3253
dat2 = np.zeros(3, [('A', 'i'), ('B', '|O')])
dat2[['B', 'A']] # TypeError?
def test_setfield(self):
# https://github.com/numpy/numpy/issues/3126
struct_dt = np.dtype([('elem', 'i4', 5),])
dt = np.dtype([('field', 'i4', 10),('struct', struct_dt)])
x = np.zeros(1, dt)
x[0]['field'] = np.ones(10, dtype='i4')
x[0]['struct'] = np.ones(1, dtype=struct_dt)
assert_equal(x[0]['field'], np.ones(10, dtype='i4'))
def test_setfield_object(self):
# make sure object field assignment with ndarray value
# on void scalar mimics setitem behavior
b = np.zeros(1, dtype=[('x', 'O')])
# next line should work identically to b['x'][0] = np.arange(3)
b[0]['x'] = np.arange(3)
assert_equal(b[0]['x'], np.arange(3))
#check that broadcasting check still works
c = np.zeros(1, dtype=[('x', 'O', 5)])
def testassign():
c[0]['x'] = np.arange(3)
assert_raises(ValueError, testassign)
class TestBool(TestCase):
def test_test_interning(self):
a0 = np.bool_(0)
b0 = np.bool_(False)
self.assertTrue(a0 is b0)
a1 = np.bool_(1)
b1 = np.bool_(True)
self.assertTrue(a1 is b1)
self.assertTrue(np.array([True])[0] is a1)
self.assertTrue(np.array(True)[()] is a1)
def test_sum(self):
d = np.ones(101, dtype=np.bool)
assert_equal(d.sum(), d.size)
assert_equal(d[::2].sum(), d[::2].size)
assert_equal(d[::-2].sum(), d[::-2].size)
d = np.frombuffer(b'\xff\xff' * 100, dtype=bool)
assert_equal(d.sum(), d.size)
assert_equal(d[::2].sum(), d[::2].size)
assert_equal(d[::-2].sum(), d[::-2].size)
def check_count_nonzero(self, power, length):
powers = [2 ** i for i in range(length)]
for i in range(2**power):
l = [(i & x) != 0 for x in powers]
a = np.array(l, dtype=np.bool)
c = builtins.sum(l)
self.assertEqual(np.count_nonzero(a), c)
av = a.view(np.uint8)
av *= 3
self.assertEqual(np.count_nonzero(a), c)
av *= 4
self.assertEqual(np.count_nonzero(a), c)
av[av != 0] = 0xFF
self.assertEqual(np.count_nonzero(a), c)
def test_count_nonzero(self):
# check all 12 bit combinations in a length 17 array
# covers most cases of the 16 byte unrolled code
self.check_count_nonzero(12, 17)
@dec.slow
def test_count_nonzero_all(self):
# check all combinations in a length 17 array
# covers all cases of the 16 byte unrolled code
self.check_count_nonzero(17, 17)
def test_count_nonzero_unaligned(self):
# prevent mistakes as e.g. gh-4060
for o in range(7):
a = np.zeros((18,), dtype=np.bool)[o+1:]
a[:o] = True
self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist()))
a = np.ones((18,), dtype=np.bool)[o+1:]
a[:o] = False
self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist()))
class TestMethods(TestCase):
def test_round(self):
def check_round(arr, expected, *round_args):
assert_equal(arr.round(*round_args), expected)
# With output array
out = np.zeros_like(arr)
res = arr.round(*round_args, out=out)
assert_equal(out, expected)
assert_equal(out, res)
check_round(np.array([1.2, 1.5]), [1, 2])
check_round(np.array(1.5), 2)
check_round(np.array([12.2, 15.5]), [10, 20], -1)
check_round(np.array([12.15, 15.51]), [12.2, 15.5], 1)
# Complex rounding
check_round(np.array([4.5 + 1.5j]), [4 + 2j])
check_round(np.array([12.5 + 15.5j]), [10 + 20j], -1)
def test_transpose(self):
a = np.array([[1, 2], [3, 4]])
assert_equal(a.transpose(), [[1, 3], [2, 4]])
self.assertRaises(ValueError, lambda: a.transpose(0))
self.assertRaises(ValueError, lambda: a.transpose(0, 0))
self.assertRaises(ValueError, lambda: a.transpose(0, 1, 2))
def test_sort(self):
# test ordering for floats and complex containing nans. It is only
# necessary to check the lessthan comparison, so sorts that
# only follow the insertion sort path are sufficient. We only
# test doubles and complex doubles as the logic is the same.
# check doubles
msg = "Test real sort order with nans"
a = np.array([np.nan, 1, 0])
b = np.sort(a)
assert_equal(b, a[::-1], msg)
# check complex
msg = "Test complex sort order with nans"
a = np.zeros(9, dtype=np.complex128)
a.real += [np.nan, np.nan, np.nan, 1, 0, 1, 1, 0, 0]
a.imag += [np.nan, 1, 0, np.nan, np.nan, 1, 0, 1, 0]
b = np.sort(a)
assert_equal(b, a[::-1], msg)
# all c scalar sorts use the same code with different types
# so it suffices to run a quick check with one type. The number
# of sorted items must be greater than ~50 to check the actual
# algorithm because quick and merge sort fall over to insertion
# sort for small arrays.
a = np.arange(101)
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "scalar sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test complex sorts. These use the same code as the scalars
# but the compare function differs.
ai = a*1j + 1
bi = b*1j + 1
for kind in ['q', 'm', 'h']:
msg = "complex sort, real part == 1, kind=%s" % kind
c = ai.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
c = bi.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
ai = a + 1j
bi = b + 1j
for kind in ['q', 'm', 'h']:
msg = "complex sort, imag part == 1, kind=%s" % kind
c = ai.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
c = bi.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
# test sorting of complex arrays requiring byte-swapping, gh-5441
for endianess in '<>':
for dt in np.typecodes['Complex']:
arr = np.array([1+3.j, 2+2.j, 3+1.j], dtype=endianess + dt)
c = arr.copy()
c.sort()
msg = 'byte-swapped complex sort, dtype={0}'.format(dt)
assert_equal(c, arr, msg)
# test string sorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)])
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "string sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test unicode sorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode)
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "unicode sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test object array sorts.
a = np.empty((101,), dtype=np.object)
a[:] = list(range(101))
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "object sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test record array sorts.
dt = np.dtype([('f', float), ('i', int)])
a = np.array([(i, i) for i in range(101)], dtype=dt)
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "object sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test datetime64 sorts.
a = np.arange(0, 101, dtype='datetime64[D]')
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "datetime64 sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test timedelta64 sorts.
a = np.arange(0, 101, dtype='timedelta64[D]')
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "timedelta64 sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# check axis handling. This should be the same for all type
# specific sorts, so we only check it for one type and one kind
a = np.array([[3, 2], [1, 0]])
b = np.array([[1, 0], [3, 2]])
c = np.array([[2, 3], [0, 1]])
d = a.copy()
d.sort(axis=0)
assert_equal(d, b, "test sort with axis=0")
d = a.copy()
d.sort(axis=1)
assert_equal(d, c, "test sort with axis=1")
d = a.copy()
d.sort()
assert_equal(d, c, "test sort with default axis")
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array sort with axis={0}'.format(axis)
assert_equal(np.sort(a, axis=axis), a, msg)
msg = 'test empty array sort with axis=None'
assert_equal(np.sort(a, axis=None), a.ravel(), msg)
def test_copy(self):
def assert_fortran(arr):
assert_(arr.flags.fortran)
assert_(arr.flags.f_contiguous)
assert_(not arr.flags.c_contiguous)
def assert_c(arr):
assert_(not arr.flags.fortran)
assert_(not arr.flags.f_contiguous)
assert_(arr.flags.c_contiguous)
a = np.empty((2, 2), order='F')
# Test copying a Fortran array
assert_c(a.copy())
assert_c(a.copy('C'))
assert_fortran(a.copy('F'))
assert_fortran(a.copy('A'))
# Now test starting with a C array.
a = np.empty((2, 2), order='C')
assert_c(a.copy())
assert_c(a.copy('C'))
assert_fortran(a.copy('F'))
assert_c(a.copy('A'))
def test_sort_order(self):
# Test sorting an array with fields
x1 = np.array([21, 32, 14])
x2 = np.array(['my', 'first', 'name'])
x3 = np.array([3.1, 4.5, 6.2])
r = np.rec.fromarrays([x1, x2, x3], names='id,word,number')
r.sort(order=['id'])
assert_equal(r.id, np.array([14, 21, 32]))
assert_equal(r.word, np.array(['name', 'my', 'first']))
assert_equal(r.number, np.array([6.2, 3.1, 4.5]))
r.sort(order=['word'])
assert_equal(r.id, np.array([32, 21, 14]))
assert_equal(r.word, np.array(['first', 'my', 'name']))
assert_equal(r.number, np.array([4.5, 3.1, 6.2]))
r.sort(order=['number'])
assert_equal(r.id, np.array([21, 32, 14]))
assert_equal(r.word, np.array(['my', 'first', 'name']))
assert_equal(r.number, np.array([3.1, 4.5, 6.2]))
if sys.byteorder == 'little':
strtype = '>i2'
else:
strtype = '<i2'
mydtype = [('name', strchar + '5'), ('col2', strtype)]
r = np.array([('a', 1), ('b', 255), ('c', 3), ('d', 258)],
dtype=mydtype)
r.sort(order='col2')
assert_equal(r['col2'], [1, 3, 255, 258])
assert_equal(r, np.array([('a', 1), ('c', 3), ('b', 255), ('d', 258)],
dtype=mydtype))
def test_argsort(self):
# all c scalar argsorts use the same code with different types
# so it suffices to run a quick check with one type. The number
# of sorted items must be greater than ~50 to check the actual
# algorithm because quick and merge sort fall over to insertion
# sort for small arrays.
a = np.arange(101)
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "scalar argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), a, msg)
assert_equal(b.copy().argsort(kind=kind), b, msg)
# test complex argsorts. These use the same code as the scalars
# but the compare fuction differs.
ai = a*1j + 1
bi = b*1j + 1
for kind in ['q', 'm', 'h']:
msg = "complex argsort, kind=%s" % kind
assert_equal(ai.copy().argsort(kind=kind), a, msg)
assert_equal(bi.copy().argsort(kind=kind), b, msg)
ai = a + 1j
bi = b + 1j
for kind in ['q', 'm', 'h']:
msg = "complex argsort, kind=%s" % kind
assert_equal(ai.copy().argsort(kind=kind), a, msg)
assert_equal(bi.copy().argsort(kind=kind), b, msg)
# test argsort of complex arrays requiring byte-swapping, gh-5441
for endianess in '<>':
for dt in np.typecodes['Complex']:
arr = np.array([1+3.j, 2+2.j, 3+1.j], dtype=endianess + dt)
msg = 'byte-swapped complex argsort, dtype={0}'.format(dt)
assert_equal(arr.argsort(),
np.arange(len(arr), dtype=np.intp), msg)
# test string argsorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)])
b = a[::-1].copy()
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "string argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test unicode argsorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode)
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "unicode argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test object array argsorts.
a = np.empty((101,), dtype=np.object)
a[:] = list(range(101))
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "object argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test structured array argsorts.
dt = np.dtype([('f', float), ('i', int)])
a = np.array([(i, i) for i in range(101)], dtype=dt)
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "structured array argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test datetime64 argsorts.
a = np.arange(0, 101, dtype='datetime64[D]')
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'h', 'm']:
msg = "datetime64 argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test timedelta64 argsorts.
a = np.arange(0, 101, dtype='timedelta64[D]')
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'h', 'm']:
msg = "timedelta64 argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# check axis handling. This should be the same for all type
# specific argsorts, so we only check it for one type and one kind
a = np.array([[3, 2], [1, 0]])
b = np.array([[1, 1], [0, 0]])
c = np.array([[1, 0], [1, 0]])
assert_equal(a.copy().argsort(axis=0), b)
assert_equal(a.copy().argsort(axis=1), c)
assert_equal(a.copy().argsort(), c)
# using None is known fail at this point
#assert_equal(a.copy().argsort(axis=None, c)
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array argsort with axis={0}'.format(axis)
assert_equal(np.argsort(a, axis=axis),
np.zeros_like(a, dtype=np.intp), msg)
msg = 'test empty array argsort with axis=None'
assert_equal(np.argsort(a, axis=None),
np.zeros_like(a.ravel(), dtype=np.intp), msg)
# check that stable argsorts are stable
r = np.arange(100)
# scalars
a = np.zeros(100)
assert_equal(a.argsort(kind='m'), r)
# complex
a = np.zeros(100, dtype=np.complex)
assert_equal(a.argsort(kind='m'), r)
# string
a = np.array(['aaaaaaaaa' for i in range(100)])
assert_equal(a.argsort(kind='m'), r)
# unicode
a = np.array(['aaaaaaaaa' for i in range(100)], dtype=np.unicode)
assert_equal(a.argsort(kind='m'), r)
def test_sort_unicode_kind(self):
d = np.arange(10)
k = b'\xc3\xa4'.decode("UTF8")
assert_raises(ValueError, d.sort, kind=k)
assert_raises(ValueError, d.argsort, kind=k)
def test_searchsorted(self):
# test for floats and complex containing nans. The logic is the
# same for all float types so only test double types for now.
# The search sorted routines use the compare functions for the
# array type, so this checks if that is consistent with the sort
# order.
# check double
a = np.array([0, 1, np.nan])
msg = "Test real searchsorted with nans, side='l'"
b = a.searchsorted(a, side='l')
assert_equal(b, np.arange(3), msg)
msg = "Test real searchsorted with nans, side='r'"
b = a.searchsorted(a, side='r')
assert_equal(b, np.arange(1, 4), msg)
# check double complex
a = np.zeros(9, dtype=np.complex128)
a.real += [0, 0, 1, 1, 0, 1, np.nan, np.nan, np.nan]
a.imag += [0, 1, 0, 1, np.nan, np.nan, 0, 1, np.nan]
msg = "Test complex searchsorted with nans, side='l'"
b = a.searchsorted(a, side='l')
assert_equal(b, np.arange(9), msg)
msg = "Test complex searchsorted with nans, side='r'"
b = a.searchsorted(a, side='r')
assert_equal(b, np.arange(1, 10), msg)
msg = "Test searchsorted with little endian, side='l'"
a = np.array([0, 128], dtype='<i4')
b = a.searchsorted(np.array(128, dtype='<i4'))
assert_equal(b, 1, msg)
msg = "Test searchsorted with big endian, side='l'"
a = np.array([0, 128], dtype='>i4')
b = a.searchsorted(np.array(128, dtype='>i4'))
assert_equal(b, 1, msg)
# Check 0 elements
a = np.ones(0)
b = a.searchsorted([0, 1, 2], 'l')
assert_equal(b, [0, 0, 0])
b = a.searchsorted([0, 1, 2], 'r')
assert_equal(b, [0, 0, 0])
a = np.ones(1)
# Check 1 element
b = a.searchsorted([0, 1, 2], 'l')
assert_equal(b, [0, 0, 1])
b = a.searchsorted([0, 1, 2], 'r')
assert_equal(b, [0, 1, 1])
# Check all elements equal
a = np.ones(2)
b = a.searchsorted([0, 1, 2], 'l')
assert_equal(b, [0, 0, 2])
b = a.searchsorted([0, 1, 2], 'r')
assert_equal(b, [0, 2, 2])
# Test searching unaligned array
a = np.arange(10)
aligned = np.empty(a.itemsize * a.size + 1, 'uint8')
unaligned = aligned[1:].view(a.dtype)
unaligned[:] = a
# Test searching unaligned array
b = unaligned.searchsorted(a, 'l')
assert_equal(b, a)
b = unaligned.searchsorted(a, 'r')
assert_equal(b, a + 1)
# Test searching for unaligned keys
b = a.searchsorted(unaligned, 'l')
assert_equal(b, a)
b = a.searchsorted(unaligned, 'r')
assert_equal(b, a + 1)
# Test smart resetting of binsearch indices
a = np.arange(5)
b = a.searchsorted([6, 5, 4], 'l')
assert_equal(b, [5, 5, 4])
b = a.searchsorted([6, 5, 4], 'r')
assert_equal(b, [5, 5, 5])
# Test all type specific binary search functions
types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'],
np.typecodes['Datetime'], '?O'))
for dt in types:
if dt == 'M':
dt = 'M8[D]'
if dt == '?':
a = np.arange(2, dtype=dt)
out = np.arange(2)
else:
a = np.arange(0, 5, dtype=dt)
out = np.arange(5)
b = a.searchsorted(a, 'l')
assert_equal(b, out)
b = a.searchsorted(a, 'r')
assert_equal(b, out + 1)
def test_searchsorted_unicode(self):
# Test searchsorted on unicode strings.
# 1.6.1 contained a string length miscalculation in
# arraytypes.c.src:UNICODE_compare() which manifested as
# incorrect/inconsistent results from searchsorted.
a = np.array(['P:\\20x_dapi_cy3\\20x_dapi_cy3_20100185_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100186_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100187_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100189_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100190_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100191_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100192_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100193_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100194_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100195_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100196_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100197_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100198_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100199_1'],
dtype=np.unicode)
ind = np.arange(len(a))
assert_equal([a.searchsorted(v, 'left') for v in a], ind)
assert_equal([a.searchsorted(v, 'right') for v in a], ind + 1)
assert_equal([a.searchsorted(a[i], 'left') for i in ind], ind)
assert_equal([a.searchsorted(a[i], 'right') for i in ind], ind + 1)
def test_searchsorted_with_sorter(self):
a = np.array([5, 2, 1, 3, 4])
s = np.argsort(a)
assert_raises(TypeError, np.searchsorted, a, 0, sorter=(1, (2, 3)))
assert_raises(TypeError, np.searchsorted, a, 0, sorter=[1.1])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4, 5, 6])
# bounds check
assert_raises(ValueError, np.searchsorted, a, 4, sorter=[0, 1, 2, 3, 5])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[-1, 0, 1, 2, 3])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[4, 0, -1, 2, 3])
a = np.random.rand(300)
s = a.argsort()
b = np.sort(a)
k = np.linspace(0, 1, 20)
assert_equal(b.searchsorted(k), a.searchsorted(k, sorter=s))
a = np.array([0, 1, 2, 3, 5]*20)
s = a.argsort()
k = [0, 1, 2, 3, 5]
expected = [0, 20, 40, 60, 80]
assert_equal(a.searchsorted(k, side='l', sorter=s), expected)
expected = [20, 40, 60, 80, 100]
assert_equal(a.searchsorted(k, side='r', sorter=s), expected)
# Test searching unaligned array
keys = np.arange(10)
a = keys.copy()
np.random.shuffle(s)
s = a.argsort()
aligned = np.empty(a.itemsize * a.size + 1, 'uint8')
unaligned = aligned[1:].view(a.dtype)
# Test searching unaligned array
unaligned[:] = a
b = unaligned.searchsorted(keys, 'l', s)
assert_equal(b, keys)
b = unaligned.searchsorted(keys, 'r', s)
assert_equal(b, keys + 1)
# Test searching for unaligned keys
unaligned[:] = keys
b = a.searchsorted(unaligned, 'l', s)
assert_equal(b, keys)
b = a.searchsorted(unaligned, 'r', s)
assert_equal(b, keys + 1)
# Test all type specific indirect binary search functions
types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'],
np.typecodes['Datetime'], '?O'))
for dt in types:
if dt == 'M':
dt = 'M8[D]'
if dt == '?':
a = np.array([1, 0], dtype=dt)
# We want the sorter array to be of a type that is different
# from np.intp in all platforms, to check for #4698
s = np.array([1, 0], dtype=np.int16)
out = np.array([1, 0])
else:
a = np.array([3, 4, 1, 2, 0], dtype=dt)
# We want the sorter array to be of a type that is different
# from np.intp in all platforms, to check for #4698
s = np.array([4, 2, 3, 0, 1], dtype=np.int16)
out = np.array([3, 4, 1, 2, 0], dtype=np.intp)
b = a.searchsorted(a, 'l', s)
assert_equal(b, out)
b = a.searchsorted(a, 'r', s)
assert_equal(b, out + 1)
# Test non-contiguous sorter array
a = np.array([3, 4, 1, 2, 0])
srt = np.empty((10,), dtype=np.intp)
srt[1::2] = -1
srt[::2] = [4, 2, 3, 0, 1]
s = srt[::2]
out = np.array([3, 4, 1, 2, 0], dtype=np.intp)
b = a.searchsorted(a, 'l', s)
assert_equal(b, out)
b = a.searchsorted(a, 'r', s)
assert_equal(b, out + 1)
def test_argpartition_out_of_range(self):
# Test out of range values in kth raise an error, gh-5469
d = np.arange(10)
assert_raises(ValueError, d.argpartition, 10)
assert_raises(ValueError, d.argpartition, -11)
# Test also for generic type argpartition, which uses sorting
# and used to not bound check kth
d_obj = np.arange(10, dtype=object)
assert_raises(ValueError, d_obj.argpartition, 10)
assert_raises(ValueError, d_obj.argpartition, -11)
def test_partition_out_of_range(self):
# Test out of range values in kth raise an error, gh-5469
d = np.arange(10)
assert_raises(ValueError, d.partition, 10)
assert_raises(ValueError, d.partition, -11)
# Test also for generic type partition, which uses sorting
# and used to not bound check kth
d_obj = np.arange(10, dtype=object)
assert_raises(ValueError, d_obj.partition, 10)
assert_raises(ValueError, d_obj.partition, -11)
def test_partition_empty_array(self):
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array partition with axis={0}'.format(axis)
assert_equal(np.partition(a, 0, axis=axis), a, msg)
msg = 'test empty array partition with axis=None'
assert_equal(np.partition(a, 0, axis=None), a.ravel(), msg)
def test_argpartition_empty_array(self):
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array argpartition with axis={0}'.format(axis)
assert_equal(np.partition(a, 0, axis=axis),
np.zeros_like(a, dtype=np.intp), msg)
msg = 'test empty array argpartition with axis=None'
assert_equal(np.partition(a, 0, axis=None),
np.zeros_like(a.ravel(), dtype=np.intp), msg)
def test_partition(self):
d = np.arange(10)
assert_raises(TypeError, np.partition, d, 2, kind=1)
assert_raises(ValueError, np.partition, d, 2, kind="nonsense")
assert_raises(ValueError, np.argpartition, d, 2, kind="nonsense")
assert_raises(ValueError, d.partition, 2, axis=0, kind="nonsense")
assert_raises(ValueError, d.argpartition, 2, axis=0, kind="nonsense")
for k in ("introselect",):
d = np.array([])
assert_array_equal(np.partition(d, 0, kind=k), d)
assert_array_equal(np.argpartition(d, 0, kind=k), d)
d = np.ones((1))
assert_array_equal(np.partition(d, 0, kind=k)[0], d)
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
# kth not modified
kth = np.array([30, 15, 5])
okth = kth.copy()
np.partition(np.arange(40), kth)
assert_array_equal(kth, okth)
for r in ([2, 1], [1, 2], [1, 1]):
d = np.array(r)
tgt = np.sort(d)
assert_array_equal(np.partition(d, 0, kind=k)[0], tgt[0])
assert_array_equal(np.partition(d, 1, kind=k)[1], tgt[1])
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
assert_array_equal(d[np.argpartition(d, 1, kind=k)],
np.partition(d, 1, kind=k))
for i in range(d.size):
d[i:].partition(0, kind=k)
assert_array_equal(d, tgt)
for r in ([3, 2, 1], [1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 1, 1], [1, 2, 2], [2, 2, 1], [1, 2, 1]):
d = np.array(r)
tgt = np.sort(d)
assert_array_equal(np.partition(d, 0, kind=k)[0], tgt[0])
assert_array_equal(np.partition(d, 1, kind=k)[1], tgt[1])
assert_array_equal(np.partition(d, 2, kind=k)[2], tgt[2])
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
assert_array_equal(d[np.argpartition(d, 1, kind=k)],
np.partition(d, 1, kind=k))
assert_array_equal(d[np.argpartition(d, 2, kind=k)],
np.partition(d, 2, kind=k))
for i in range(d.size):
d[i:].partition(0, kind=k)
assert_array_equal(d, tgt)
d = np.ones((50))
assert_array_equal(np.partition(d, 0, kind=k), d)
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
# sorted
d = np.arange((49))
self.assertEqual(np.partition(d, 5, kind=k)[5], 5)
self.assertEqual(np.partition(d, 15, kind=k)[15], 15)
assert_array_equal(d[np.argpartition(d, 5, kind=k)],
np.partition(d, 5, kind=k))
assert_array_equal(d[np.argpartition(d, 15, kind=k)],
np.partition(d, 15, kind=k))
# rsorted
d = np.arange((47))[::-1]
self.assertEqual(np.partition(d, 6, kind=k)[6], 6)
self.assertEqual(np.partition(d, 16, kind=k)[16], 16)
assert_array_equal(d[np.argpartition(d, 6, kind=k)],
np.partition(d, 6, kind=k))
assert_array_equal(d[np.argpartition(d, 16, kind=k)],
np.partition(d, 16, kind=k))
assert_array_equal(np.partition(d, -6, kind=k),
np.partition(d, 41, kind=k))
assert_array_equal(np.partition(d, -16, kind=k),
np.partition(d, 31, kind=k))
assert_array_equal(d[np.argpartition(d, -6, kind=k)],
np.partition(d, 41, kind=k))
# median of 3 killer, O(n^2) on pure median 3 pivot quickselect
# exercises the median of median of 5 code used to keep O(n)
d = np.arange(1000000)
x = np.roll(d, d.size // 2)
mid = x.size // 2 + 1
assert_equal(np.partition(x, mid)[mid], mid)
d = np.arange(1000001)
x = np.roll(d, d.size // 2 + 1)
mid = x.size // 2 + 1
assert_equal(np.partition(x, mid)[mid], mid)
# max
d = np.ones(10)
d[1] = 4
assert_equal(np.partition(d, (2, -1))[-1], 4)
assert_equal(np.partition(d, (2, -1))[2], 1)
assert_equal(d[np.argpartition(d, (2, -1))][-1], 4)
assert_equal(d[np.argpartition(d, (2, -1))][2], 1)
d[1] = np.nan
assert_(np.isnan(d[np.argpartition(d, (2, -1))][-1]))
assert_(np.isnan(np.partition(d, (2, -1))[-1]))
# equal elements
d = np.arange((47)) % 7
tgt = np.sort(np.arange((47)) % 7)
np.random.shuffle(d)
for i in range(d.size):
self.assertEqual(np.partition(d, i, kind=k)[i], tgt[i])
assert_array_equal(d[np.argpartition(d, 6, kind=k)],
np.partition(d, 6, kind=k))
assert_array_equal(d[np.argpartition(d, 16, kind=k)],
np.partition(d, 16, kind=k))
for i in range(d.size):
d[i:].partition(0, kind=k)
assert_array_equal(d, tgt)
d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 9])
kth = [0, 3, 19, 20]
assert_equal(np.partition(d, kth, kind=k)[kth], (0, 3, 7, 7))
assert_equal(d[np.argpartition(d, kth, kind=k)][kth], (0, 3, 7, 7))
d = np.array([2, 1])
d.partition(0, kind=k)
assert_raises(ValueError, d.partition, 2)
assert_raises(ValueError, d.partition, 3, axis=1)
assert_raises(ValueError, np.partition, d, 2)
assert_raises(ValueError, np.partition, d, 2, axis=1)
assert_raises(ValueError, d.argpartition, 2)
assert_raises(ValueError, d.argpartition, 3, axis=1)
assert_raises(ValueError, np.argpartition, d, 2)
assert_raises(ValueError, np.argpartition, d, 2, axis=1)
d = np.arange(10).reshape((2, 5))
d.partition(1, axis=0, kind=k)
d.partition(4, axis=1, kind=k)
np.partition(d, 1, axis=0, kind=k)
np.partition(d, 4, axis=1, kind=k)
np.partition(d, 1, axis=None, kind=k)
np.partition(d, 9, axis=None, kind=k)
d.argpartition(1, axis=0, kind=k)
d.argpartition(4, axis=1, kind=k)
np.argpartition(d, 1, axis=0, kind=k)
np.argpartition(d, 4, axis=1, kind=k)
np.argpartition(d, 1, axis=None, kind=k)
np.argpartition(d, 9, axis=None, kind=k)
assert_raises(ValueError, d.partition, 2, axis=0)
assert_raises(ValueError, d.partition, 11, axis=1)
assert_raises(TypeError, d.partition, 2, axis=None)
assert_raises(ValueError, np.partition, d, 9, axis=1)
assert_raises(ValueError, np.partition, d, 11, axis=None)
assert_raises(ValueError, d.argpartition, 2, axis=0)
assert_raises(ValueError, d.argpartition, 11, axis=1)
assert_raises(ValueError, np.argpartition, d, 9, axis=1)
assert_raises(ValueError, np.argpartition, d, 11, axis=None)
td = [(dt, s) for dt in [np.int32, np.float32, np.complex64]
for s in (9, 16)]
for dt, s in td:
aae = assert_array_equal
at = self.assertTrue
d = np.arange(s, dtype=dt)
np.random.shuffle(d)
d1 = np.tile(np.arange(s, dtype=dt), (4, 1))
map(np.random.shuffle, d1)
d0 = np.transpose(d1)
for i in range(d.size):
p = np.partition(d, i, kind=k)
self.assertEqual(p[i], i)
# all before are smaller
assert_array_less(p[:i], p[i])
# all after are larger
assert_array_less(p[i], p[i + 1:])
aae(p, d[np.argpartition(d, i, kind=k)])
p = np.partition(d1, i, axis=1, kind=k)
aae(p[:, i], np.array([i] * d1.shape[0], dtype=dt))
# array_less does not seem to work right
at((p[:, :i].T <= p[:, i]).all(),
msg="%d: %r <= %r" % (i, p[:, i], p[:, :i].T))
at((p[:, i + 1:].T > p[:, i]).all(),
msg="%d: %r < %r" % (i, p[:, i], p[:, i + 1:].T))
aae(p, d1[np.arange(d1.shape[0])[:, None],
np.argpartition(d1, i, axis=1, kind=k)])
p = np.partition(d0, i, axis=0, kind=k)
aae(p[i,:], np.array([i] * d1.shape[0],
dtype=dt))
# array_less does not seem to work right
at((p[:i,:] <= p[i,:]).all(),
msg="%d: %r <= %r" % (i, p[i,:], p[:i,:]))
at((p[i + 1:,:] > p[i,:]).all(),
msg="%d: %r < %r" % (i, p[i,:], p[:, i + 1:]))
aae(p, d0[np.argpartition(d0, i, axis=0, kind=k),
np.arange(d0.shape[1])[None,:]])
# check inplace
dc = d.copy()
dc.partition(i, kind=k)
assert_equal(dc, np.partition(d, i, kind=k))
dc = d0.copy()
dc.partition(i, axis=0, kind=k)
assert_equal(dc, np.partition(d0, i, axis=0, kind=k))
dc = d1.copy()
dc.partition(i, axis=1, kind=k)
assert_equal(dc, np.partition(d1, i, axis=1, kind=k))
def assert_partitioned(self, d, kth):
prev = 0
for k in np.sort(kth):
assert_array_less(d[prev:k], d[k], err_msg='kth %d' % k)
assert_((d[k:] >= d[k]).all(),
msg="kth %d, %r not greater equal %d" % (k, d[k:], d[k]))
prev = k + 1
def test_partition_iterative(self):
d = np.arange(17)
kth = (0, 1, 2, 429, 231)
assert_raises(ValueError, d.partition, kth)
assert_raises(ValueError, d.argpartition, kth)
d = np.arange(10).reshape((2, 5))
assert_raises(ValueError, d.partition, kth, axis=0)
assert_raises(ValueError, d.partition, kth, axis=1)
assert_raises(ValueError, np.partition, d, kth, axis=1)
assert_raises(ValueError, np.partition, d, kth, axis=None)
d = np.array([3, 4, 2, 1])
p = np.partition(d, (0, 3))
self.assert_partitioned(p, (0, 3))
self.assert_partitioned(d[np.argpartition(d, (0, 3))], (0, 3))
assert_array_equal(p, np.partition(d, (-3, -1)))
assert_array_equal(p, d[np.argpartition(d, (-3, -1))])
d = np.arange(17)
np.random.shuffle(d)
d.partition(range(d.size))
assert_array_equal(np.arange(17), d)
np.random.shuffle(d)
assert_array_equal(np.arange(17), d[d.argpartition(range(d.size))])
# test unsorted kth
d = np.arange(17)
np.random.shuffle(d)
keys = np.array([1, 3, 8, -2])
np.random.shuffle(d)
p = np.partition(d, keys)
self.assert_partitioned(p, keys)
p = d[np.argpartition(d, keys)]
self.assert_partitioned(p, keys)
np.random.shuffle(keys)
assert_array_equal(np.partition(d, keys), p)
assert_array_equal(d[np.argpartition(d, keys)], p)
# equal kth
d = np.arange(20)[::-1]
self.assert_partitioned(np.partition(d, [5]*4), [5])
self.assert_partitioned(np.partition(d, [5]*4 + [6, 13]),
[5]*4 + [6, 13])
self.assert_partitioned(d[np.argpartition(d, [5]*4)], [5])
self.assert_partitioned(d[np.argpartition(d, [5]*4 + [6, 13])],
[5]*4 + [6, 13])
d = np.arange(12)
np.random.shuffle(d)
d1 = np.tile(np.arange(12), (4, 1))
map(np.random.shuffle, d1)
d0 = np.transpose(d1)
kth = (1, 6, 7, -1)
p = np.partition(d1, kth, axis=1)
pa = d1[np.arange(d1.shape[0])[:, None],
d1.argpartition(kth, axis=1)]
assert_array_equal(p, pa)
for i in range(d1.shape[0]):
self.assert_partitioned(p[i,:], kth)
p = np.partition(d0, kth, axis=0)
pa = d0[np.argpartition(d0, kth, axis=0),
np.arange(d0.shape[1])[None,:]]
assert_array_equal(p, pa)
for i in range(d0.shape[1]):
self.assert_partitioned(p[:, i], kth)
def test_partition_cdtype(self):
d = np.array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
('Lancelot', 1.9, 38)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
tgt = np.sort(d, order=['age', 'height'])
assert_array_equal(np.partition(d, range(d.size),
order=['age', 'height']),
tgt)
assert_array_equal(d[np.argpartition(d, range(d.size),
order=['age', 'height'])],
tgt)
for k in range(d.size):
assert_equal(np.partition(d, k, order=['age', 'height'])[k],
tgt[k])
assert_equal(d[np.argpartition(d, k, order=['age', 'height'])][k],
tgt[k])
d = np.array(['Galahad', 'Arthur', 'zebra', 'Lancelot'])
tgt = np.sort(d)
assert_array_equal(np.partition(d, range(d.size)), tgt)
for k in range(d.size):
assert_equal(np.partition(d, k)[k], tgt[k])
assert_equal(d[np.argpartition(d, k)][k], tgt[k])
def test_partition_unicode_kind(self):
d = np.arange(10)
k = b'\xc3\xa4'.decode("UTF8")
assert_raises(ValueError, d.partition, 2, kind=k)
assert_raises(ValueError, d.argpartition, 2, kind=k)
def test_partition_fuzz(self):
# a few rounds of random data testing
for j in range(10, 30):
for i in range(1, j - 2):
d = np.arange(j)
np.random.shuffle(d)
d = d % np.random.randint(2, 30)
idx = np.random.randint(d.size)
kth = [0, idx, i, i + 1]
tgt = np.sort(d)[kth]
assert_array_equal(np.partition(d, kth)[kth], tgt,
err_msg="data: %r\n kth: %r" % (d, kth))
def test_argpartition_gh5524(self):
# A test for functionality of argpartition on lists.
d = [6,7,3,2,9,0]
p = np.argpartition(d,1)
self.assert_partitioned(np.array(d)[p],[1])
def test_flatten(self):
x0 = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
x1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], np.int32)
y0 = np.array([1, 2, 3, 4, 5, 6], np.int32)
y0f = np.array([1, 4, 2, 5, 3, 6], np.int32)
y1 = np.array([1, 2, 3, 4, 5, 6, 7, 8], np.int32)
y1f = np.array([1, 5, 3, 7, 2, 6, 4, 8], np.int32)
assert_equal(x0.flatten(), y0)
assert_equal(x0.flatten('F'), y0f)
assert_equal(x0.flatten('F'), x0.T.flatten())
assert_equal(x1.flatten(), y1)
assert_equal(x1.flatten('F'), y1f)
assert_equal(x1.flatten('F'), x1.T.flatten())
def test_dot(self):
a = np.array([[1, 0], [0, 1]])
b = np.array([[0, 1], [1, 0]])
c = np.array([[9, 1], [1, -9]])
assert_equal(np.dot(a, b), a.dot(b))
assert_equal(np.dot(np.dot(a, b), c), a.dot(b).dot(c))
# test passing in an output array
c = np.zeros_like(a)
a.dot(b, c)
assert_equal(c, np.dot(a, b))
# test keyword args
c = np.zeros_like(a)
a.dot(b=b, out=c)
assert_equal(c, np.dot(a, b))
def test_dot_override(self):
class A(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return "A"
class B(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return NotImplemented
a = A()
b = B()
c = np.array([[1]])
assert_equal(np.dot(a, b), "A")
assert_equal(c.dot(a), "A")
assert_raises(TypeError, np.dot, b, c)
assert_raises(TypeError, c.dot, b)
def test_diagonal(self):
a = np.arange(12).reshape((3, 4))
assert_equal(a.diagonal(), [0, 5, 10])
assert_equal(a.diagonal(0), [0, 5, 10])
assert_equal(a.diagonal(1), [1, 6, 11])
assert_equal(a.diagonal(-1), [4, 9])
b = np.arange(8).reshape((2, 2, 2))
assert_equal(b.diagonal(), [[0, 6], [1, 7]])
assert_equal(b.diagonal(0), [[0, 6], [1, 7]])
assert_equal(b.diagonal(1), [[2], [3]])
assert_equal(b.diagonal(-1), [[4], [5]])
assert_raises(ValueError, b.diagonal, axis1=0, axis2=0)
assert_equal(b.diagonal(0, 1, 2), [[0, 3], [4, 7]])
assert_equal(b.diagonal(0, 0, 1), [[0, 6], [1, 7]])
assert_equal(b.diagonal(offset=1, axis1=0, axis2=2), [[1], [3]])
# Order of axis argument doesn't matter:
assert_equal(b.diagonal(0, 2, 1), [[0, 3], [4, 7]])
def test_diagonal_view_notwriteable(self):
# this test is only for 1.9, the diagonal view will be
# writeable in 1.10.
a = np.eye(3).diagonal()
assert_(not a.flags.writeable)
assert_(not a.flags.owndata)
a = np.diagonal(np.eye(3))
assert_(not a.flags.writeable)
assert_(not a.flags.owndata)
a = np.diag(np.eye(3))
assert_(not a.flags.writeable)
assert_(not a.flags.owndata)
def test_diagonal_memleak(self):
# Regression test for a bug that crept in at one point
a = np.zeros((100, 100))
assert_(sys.getrefcount(a) < 50)
for i in range(100):
a.diagonal()
assert_(sys.getrefcount(a) < 50)
def test_put(self):
icodes = np.typecodes['AllInteger']
fcodes = np.typecodes['AllFloat']
for dt in icodes + fcodes + 'O':
tgt = np.array([0, 1, 0, 3, 0, 5], dtype=dt)
# test 1-d
a = np.zeros(6, dtype=dt)
a.put([1, 3, 5], [1, 3, 5])
assert_equal(a, tgt)
# test 2-d
a = np.zeros((2, 3), dtype=dt)
a.put([1, 3, 5], [1, 3, 5])
assert_equal(a, tgt.reshape(2, 3))
for dt in '?':
tgt = np.array([False, True, False, True, False, True], dtype=dt)
# test 1-d
a = np.zeros(6, dtype=dt)
a.put([1, 3, 5], [True]*3)
assert_equal(a, tgt)
# test 2-d
a = np.zeros((2, 3), dtype=dt)
a.put([1, 3, 5], [True]*3)
assert_equal(a, tgt.reshape(2, 3))
# check must be writeable
a = np.zeros(6)
a.flags.writeable = False
assert_raises(ValueError, a.put, [1, 3, 5], [1, 3, 5])
def test_ravel(self):
a = np.array([[0, 1], [2, 3]])
assert_equal(a.ravel(), [0, 1, 2, 3])
assert_(not a.ravel().flags.owndata)
assert_equal(a.ravel('F'), [0, 2, 1, 3])
assert_equal(a.ravel(order='C'), [0, 1, 2, 3])
assert_equal(a.ravel(order='F'), [0, 2, 1, 3])
assert_equal(a.ravel(order='A'), [0, 1, 2, 3])
assert_(not a.ravel(order='A').flags.owndata)
assert_equal(a.ravel(order='K'), [0, 1, 2, 3])
assert_(not a.ravel(order='K').flags.owndata)
assert_equal(a.ravel(), a.reshape(-1))
a = np.array([[0, 1], [2, 3]], order='F')
assert_equal(a.ravel(), [0, 1, 2, 3])
assert_equal(a.ravel(order='A'), [0, 2, 1, 3])
assert_equal(a.ravel(order='K'), [0, 2, 1, 3])
assert_(not a.ravel(order='A').flags.owndata)
assert_(not a.ravel(order='K').flags.owndata)
assert_equal(a.ravel(), a.reshape(-1))
assert_equal(a.ravel(order='A'), a.reshape(-1, order='A'))
a = np.array([[0, 1], [2, 3]])[::-1, :]
assert_equal(a.ravel(), [2, 3, 0, 1])
assert_equal(a.ravel(order='C'), [2, 3, 0, 1])
assert_equal(a.ravel(order='F'), [2, 0, 3, 1])
assert_equal(a.ravel(order='A'), [2, 3, 0, 1])
# 'K' doesn't reverse the axes of negative strides
assert_equal(a.ravel(order='K'), [2, 3, 0, 1])
assert_(a.ravel(order='K').flags.owndata)
# Not contiguous and 1-sized axis with non matching stride
a = np.arange(2**3 * 2)[::2]
a = a.reshape(2, 1, 2, 2).swapaxes(-1, -2)
strides = list(a.strides)
strides[1] = 123
a.strides = strides
assert_(np.may_share_memory(a.ravel(order='K'), a))
assert_equal(a.ravel('K'), np.arange(0, 15, 2))
# General case of possible ravel that is not contiguous but
# works and includes a 1-sized axis with non matching stride
a = a.swapaxes(-1, -2) # swap back to C-order
assert_(np.may_share_memory(a.ravel(order='C'), a))
assert_(np.may_share_memory(a.ravel(order='K'), a))
a = a.T # swap all to Fortran order
assert_(np.may_share_memory(a.ravel(order='F'), a))
assert_(np.may_share_memory(a.ravel(order='K'), a))
# Test negative strides:
a = np.arange(4)[::-1].reshape(2, 2)
assert_(np.may_share_memory(a.ravel(order='C'), a))
assert_(np.may_share_memory(a.ravel(order='K'), a))
assert_equal(a.ravel('C'), [3, 2, 1, 0])
assert_equal(a.ravel('K'), [3, 2, 1, 0])
# Test keeporder with weirdly strided 1-sized dims (1-d first stride)
a = np.arange(8)[::2].reshape(1, 2, 2, 1) # neither C, nor F order
strides = list(a.strides)
strides[0] = -12
strides[-1] = 0
a.strides = strides
assert_(np.may_share_memory(a.ravel(order='K'), a))
assert_equal(a.ravel('K'), a.ravel('C'))
# 1-element tidy strides test (NPY_RELAXED_STRIDES_CHECKING):
a = np.array([[1]])
a.strides = (123, 432)
# If the stride is not 8, NPY_RELAXED_STRIDES_CHECKING is messing
# them up on purpose:
if np.ones(1).strides == (8,):
assert_(np.may_share_memory(a.ravel('K'), a))
assert_equal(a.ravel('K').strides, (a.dtype.itemsize,))
for order in ('C', 'F', 'A', 'K'):
# 0-d corner case:
a = np.array(0)
assert_equal(a.ravel(order), [0])
assert_(np.may_share_memory(a.ravel(order), a))
#Test that certain non-inplace ravels work right (mostly) for 'K':
b = np.arange(2**4 * 2)[::2].reshape(2, 2, 2, 2)
a = b[..., ::2]
assert_equal(a.ravel('K'), [0, 4, 8, 12, 16, 20, 24, 28])
assert_equal(a.ravel('C'), [0, 4, 8, 12, 16, 20, 24, 28])
assert_equal(a.ravel('A'), [0, 4, 8, 12, 16, 20, 24, 28])
assert_equal(a.ravel('F'), [0, 16, 8, 24, 4, 20, 12, 28])
a = b[::2, ...]
assert_equal(a.ravel('K'), [0, 2, 4, 6, 8, 10, 12, 14])
assert_equal(a.ravel('C'), [0, 2, 4, 6, 8, 10, 12, 14])
assert_equal(a.ravel('A'), [0, 2, 4, 6, 8, 10, 12, 14])
assert_equal(a.ravel('F'), [0, 8, 4, 12, 2, 10, 6, 14])
def test_swapaxes(self):
a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy()
idx = np.indices(a.shape)
assert_(a.flags['OWNDATA'])
b = a.copy()
# check exceptions
assert_raises(ValueError, a.swapaxes, -5, 0)
assert_raises(ValueError, a.swapaxes, 4, 0)
assert_raises(ValueError, a.swapaxes, 0, -5)
assert_raises(ValueError, a.swapaxes, 0, 4)
for i in range(-4, 4):
for j in range(-4, 4):
for k, src in enumerate((a, b)):
c = src.swapaxes(i, j)
# check shape
shape = list(src.shape)
shape[i] = src.shape[j]
shape[j] = src.shape[i]
assert_equal(c.shape, shape, str((i, j, k)))
# check array contents
i0, i1, i2, i3 = [dim-1 for dim in c.shape]
j0, j1, j2, j3 = [dim-1 for dim in src.shape]
assert_equal(src[idx[j0], idx[j1], idx[j2], idx[j3]],
c[idx[i0], idx[i1], idx[i2], idx[i3]],
str((i, j, k)))
# check a view is always returned, gh-5260
assert_(not c.flags['OWNDATA'], str((i, j, k)))
# check on non-contiguous input array
if k == 1:
b = c
def test_conjugate(self):
a = np.array([1-1j, 1+1j, 23+23.0j])
ac = a.conj()
assert_equal(a.real, ac.real)
assert_equal(a.imag, -ac.imag)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1-1j, 1+1j, 23+23.0j], 'F')
ac = a.conj()
assert_equal(a.real, ac.real)
assert_equal(a.imag, -ac.imag)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1, 2, 3])
ac = a.conj()
assert_equal(a, ac)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1.0, 2.0, 3.0])
ac = a.conj()
assert_equal(a, ac)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1-1j, 1+1j, 1, 2.0], object)
ac = a.conj()
assert_equal(ac, [k.conjugate() for k in a])
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1-1j, 1, 2.0, 'f'], object)
assert_raises(AttributeError, lambda: a.conj())
assert_raises(AttributeError, lambda: a.conjugate())
class TestBinop(object):
def test_inplace(self):
# test refcount 1 inplace conversion
assert_array_almost_equal(np.array([0.5]) * np.array([1.0, 2.0]),
[0.5, 1.0])
d = np.array([0.5, 0.5])[::2]
assert_array_almost_equal(d * (d * np.array([1.0, 2.0])),
[0.25, 0.5])
a = np.array([0.5])
b = np.array([0.5])
c = a + b
c = a - b
c = a * b
c = a / b
assert_equal(a, b)
assert_almost_equal(c, 1.)
c = a + b * 2. / b * a - a / b
assert_equal(a, b)
assert_equal(c, 0.5)
# true divide
a = np.array([5])
b = np.array([3])
c = (a * a) / b
assert_almost_equal(c, 25 / 3)
assert_equal(a, 5)
assert_equal(b, 3)
def test_extension_incref_elide(self):
# test extension (e.g. cython) calling PyNumber_* slots without
# increasing the reference counts
#
# def incref_elide(a):
# d = input.copy() # refcount 1
# return d, d + d # PyNumber_Add without increasing refcount
from numpy.core.multiarray_tests import incref_elide
d = np.ones(5)
orig, res = incref_elide(d)
# the return original should not be changed to an inplace operation
assert_array_equal(orig, d)
assert_array_equal(res, d + d)
def test_extension_incref_elide_stack(self):
# scanning if the refcount == 1 object is on the python stack to check
# that we are called directly from python is flawed as object may still
# be above the stack pointer and we have no access to the top of it
#
# def incref_elide_l(d):
# return l[4] + l[4] # PyNumber_Add without increasing refcount
from numpy.core.multiarray_tests import incref_elide_l
# padding with 1 makes sure the object on the stack is not overwriten
l = [1, 1, 1, 1, np.ones(5)]
res = incref_elide_l(l)
# the return original should not be changed to an inplace operation
assert_array_equal(l[4], np.ones(5))
assert_array_equal(res, l[4] + l[4])
def test_ufunc_override_rop_precedence(self):
# Check that __rmul__ and other right-hand operations have
# precedence over __numpy_ufunc__
ops = {
'__add__': ('__radd__', np.add, True),
'__sub__': ('__rsub__', np.subtract, True),
'__mul__': ('__rmul__', np.multiply, True),
'__truediv__': ('__rtruediv__', np.true_divide, True),
'__floordiv__': ('__rfloordiv__', np.floor_divide, True),
'__mod__': ('__rmod__', np.remainder, True),
'__divmod__': ('__rdivmod__', None, False),
'__pow__': ('__rpow__', np.power, True),
'__lshift__': ('__rlshift__', np.left_shift, True),
'__rshift__': ('__rrshift__', np.right_shift, True),
'__and__': ('__rand__', np.bitwise_and, True),
'__xor__': ('__rxor__', np.bitwise_xor, True),
'__or__': ('__ror__', np.bitwise_or, True),
'__ge__': ('__le__', np.less_equal, False),
'__gt__': ('__lt__', np.less, False),
'__le__': ('__ge__', np.greater_equal, False),
'__lt__': ('__gt__', np.greater, False),
'__eq__': ('__eq__', np.equal, False),
'__ne__': ('__ne__', np.not_equal, False),
}
class OtherNdarraySubclass(np.ndarray):
pass
class OtherNdarraySubclassWithOverride(np.ndarray):
def __numpy_ufunc__(self, *a, **kw):
raise AssertionError(("__numpy_ufunc__ %r %r shouldn't have "
"been called!") % (a, kw))
def check(op_name, ndsubclass):
rop_name, np_op, has_iop = ops[op_name]
if has_iop:
iop_name = '__i' + op_name[2:]
iop = getattr(operator, iop_name)
if op_name == "__divmod__":
op = divmod
else:
op = getattr(operator, op_name)
# Dummy class
def __init__(self, *a, **kw):
pass
def __numpy_ufunc__(self, *a, **kw):
raise AssertionError(("__numpy_ufunc__ %r %r shouldn't have "
"been called!") % (a, kw))
def __op__(self, *other):
return "op"
def __rop__(self, *other):
return "rop"
if ndsubclass:
bases = (np.ndarray,)
else:
bases = (object,)
dct = {'__init__': __init__,
'__numpy_ufunc__': __numpy_ufunc__,
op_name: __op__}
if op_name != rop_name:
dct[rop_name] = __rop__
cls = type("Rop" + rop_name, bases, dct)
# Check behavior against both bare ndarray objects and a
# ndarray subclasses with and without their own override
obj = cls((1,), buffer=np.ones(1,))
arr_objs = [np.array([1]),
np.array([2]).view(OtherNdarraySubclass),
np.array([3]).view(OtherNdarraySubclassWithOverride),
]
for arr in arr_objs:
err_msg = "%r %r" % (op_name, arr,)
# Check that ndarray op gives up if it sees a non-subclass
if not isinstance(obj, arr.__class__):
assert_equal(getattr(arr, op_name)(obj),
NotImplemented, err_msg=err_msg)
# Check that the Python binops have priority
assert_equal(op(obj, arr), "op", err_msg=err_msg)
if op_name == rop_name:
assert_equal(op(arr, obj), "op", err_msg=err_msg)
else:
assert_equal(op(arr, obj), "rop", err_msg=err_msg)
# Check that Python binops have priority also for in-place ops
if has_iop:
assert_equal(getattr(arr, iop_name)(obj),
NotImplemented, err_msg=err_msg)
if op_name != "__pow__":
# inplace pow requires the other object to be
# integer-like?
assert_equal(iop(arr, obj), "rop", err_msg=err_msg)
# Check that ufunc call __numpy_ufunc__ normally
if np_op is not None:
assert_raises(AssertionError, np_op, arr, obj,
err_msg=err_msg)
assert_raises(AssertionError, np_op, obj, arr,
err_msg=err_msg)
# Check all binary operations
for op_name in sorted(ops.keys()):
yield check, op_name, True
yield check, op_name, False
def test_ufunc_override_rop_simple(self):
# Check parts of the binary op overriding behavior in an
# explicit test case that is easier to understand.
class SomeClass(object):
def __numpy_ufunc__(self, *a, **kw):
return "ufunc"
def __mul__(self, other):
return 123
def __rmul__(self, other):
return 321
def __rsub__(self, other):
return "no subs for me"
def __gt__(self, other):
return "yep"
def __lt__(self, other):
return "nope"
class SomeClass2(SomeClass, np.ndarray):
def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw):
if ufunc is np.multiply or ufunc is np.bitwise_and:
return "ufunc"
else:
inputs = list(inputs)
inputs[i] = np.asarray(self)
func = getattr(ufunc, method)
r = func(*inputs, **kw)
if 'out' in kw:
return r
else:
x = self.__class__(r.shape, dtype=r.dtype)
x[...] = r
return x
class SomeClass3(SomeClass2):
def __rsub__(self, other):
return "sub for me"
arr = np.array([0])
obj = SomeClass()
obj2 = SomeClass2((1,), dtype=np.int_)
obj2[0] = 9
obj3 = SomeClass3((1,), dtype=np.int_)
obj3[0] = 4
# obj is first, so should get to define outcome.
assert_equal(obj * arr, 123)
# obj is second, but has __numpy_ufunc__ and defines __rmul__.
assert_equal(arr * obj, 321)
# obj is second, but has __numpy_ufunc__ and defines __rsub__.
assert_equal(arr - obj, "no subs for me")
# obj is second, but has __numpy_ufunc__ and defines __lt__.
assert_equal(arr > obj, "nope")
# obj is second, but has __numpy_ufunc__ and defines __gt__.
assert_equal(arr < obj, "yep")
# Called as a ufunc, obj.__numpy_ufunc__ is used.
assert_equal(np.multiply(arr, obj), "ufunc")
# obj is second, but has __numpy_ufunc__ and defines __rmul__.
arr *= obj
assert_equal(arr, 321)
# obj2 is an ndarray subclass, so CPython takes care of the same rules.
assert_equal(obj2 * arr, 123)
assert_equal(arr * obj2, 321)
assert_equal(arr - obj2, "no subs for me")
assert_equal(arr > obj2, "nope")
assert_equal(arr < obj2, "yep")
# Called as a ufunc, obj2.__numpy_ufunc__ is called.
assert_equal(np.multiply(arr, obj2), "ufunc")
# Also when the method is not overridden.
assert_equal(arr & obj2, "ufunc")
arr *= obj2
assert_equal(arr, 321)
obj2 += 33
assert_equal(obj2[0], 42)
assert_equal(obj2.sum(), 42)
assert_(isinstance(obj2, SomeClass2))
# Obj3 is subclass that defines __rsub__. CPython calls it.
assert_equal(arr - obj3, "sub for me")
assert_equal(obj2 - obj3, "sub for me")
# obj3 is a subclass that defines __rmul__. CPython calls it.
assert_equal(arr * obj3, 321)
# But not here, since obj3.__rmul__ is obj2.__rmul__.
assert_equal(obj2 * obj3, 123)
# And of course, here obj3.__mul__ should be called.
assert_equal(obj3 * obj2, 123)
# obj3 defines __numpy_ufunc__ but obj3.__radd__ is obj2.__radd__.
# (and both are just ndarray.__radd__); see #4815.
res = obj2 + obj3
assert_equal(res, 46)
assert_(isinstance(res, SomeClass2))
# Since obj3 is a subclass, it should have precedence, like CPython
# would give, even though obj2 has __numpy_ufunc__ and __radd__.
# See gh-4815 and gh-5747.
res = obj3 + obj2
assert_equal(res, 46)
assert_(isinstance(res, SomeClass3))
def test_ufunc_override_normalize_signature(self):
# gh-5674
class SomeClass(object):
def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw):
return kw
a = SomeClass()
kw = np.add(a, [1])
assert_('sig' not in kw and 'signature' not in kw)
kw = np.add(a, [1], sig='ii->i')
assert_('sig' not in kw and 'signature' in kw)
assert_equal(kw['signature'], 'ii->i')
kw = np.add(a, [1], signature='ii->i')
assert_('sig' not in kw and 'signature' in kw)
assert_equal(kw['signature'], 'ii->i')
class TestCAPI(TestCase):
def test_IsPythonScalar(self):
from numpy.core.multiarray_tests import IsPythonScalar
assert_(IsPythonScalar(b'foobar'))
assert_(IsPythonScalar(1))
assert_(IsPythonScalar(2**80))
assert_(IsPythonScalar(2.))
assert_(IsPythonScalar("a"))
class TestSubscripting(TestCase):
def test_test_zero_rank(self):
x = np.array([1, 2, 3])
self.assertTrue(isinstance(x[0], np.int_))
if sys.version_info[0] < 3:
self.assertTrue(isinstance(x[0], int))
self.assertTrue(type(x[0, ...]) is np.ndarray)
class TestPickling(TestCase):
def test_roundtrip(self):
import pickle
carray = np.array([[2, 9], [7, 0], [3, 8]])
DATA = [
carray,
np.transpose(carray),
np.array([('xxx', 1, 2.0)], dtype=[('a', (str, 3)), ('b', int),
('c', float)])
]
for a in DATA:
assert_equal(a, pickle.loads(a.dumps()), err_msg="%r" % a)
def _loads(self, obj):
if sys.version_info[0] >= 3:
return np.loads(obj, encoding='latin1')
else:
return np.loads(obj)
# version 0 pickles, using protocol=2 to pickle
# version 0 doesn't have a version field
def test_version0_int8(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.'
a = np.array([1, 2, 3, 4], dtype=np.int8)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version0_float32(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.'
a = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version0_object(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.'
a = np.array([{'a':1}, {'b':2}])
p = self._loads(asbytes(s))
assert_equal(a, p)
# version 1 pickles, using protocol=2 to pickle
def test_version1_int8(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.'
a = np.array([1, 2, 3, 4], dtype=np.int8)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version1_float32(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(K\x01U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.'
a = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version1_object(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.'
a = np.array([{'a':1}, {'b':2}])
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_subarray_int_shape(self):
s = "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'V6'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'a'\np12\ng3\ntp13\n(dp14\ng12\n(g7\n(S'V4'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'|'\np18\n(g7\n(S'i1'\np19\nI0\nI1\ntp20\nRp21\n(I3\nS'|'\np22\nNNNI-1\nI-1\nI0\ntp23\nb(I2\nI2\ntp24\ntp25\nNNI4\nI1\nI0\ntp26\nbI0\ntp27\nsg3\n(g7\n(S'V2'\np28\nI0\nI1\ntp29\nRp30\n(I3\nS'|'\np31\n(g21\nI2\ntp32\nNNI2\nI1\nI0\ntp33\nbI4\ntp34\nsI6\nI1\nI0\ntp35\nbI00\nS'\\x01\\x01\\x01\\x01\\x01\\x02'\np36\ntp37\nb."
a = np.array([(1, (1, 2))], dtype=[('a', 'i1', (2, 2)), ('b', 'i1', 2)])
p = self._loads(asbytes(s))
assert_equal(a, p)
class TestFancyIndexing(TestCase):
def test_list(self):
x = np.ones((1, 1))
x[:, [0]] = 2.0
assert_array_equal(x, np.array([[2.0]]))
x = np.ones((1, 1, 1))
x[:,:, [0]] = 2.0
assert_array_equal(x, np.array([[[2.0]]]))
def test_tuple(self):
x = np.ones((1, 1))
x[:, (0,)] = 2.0
assert_array_equal(x, np.array([[2.0]]))
x = np.ones((1, 1, 1))
x[:,:, (0,)] = 2.0
assert_array_equal(x, np.array([[[2.0]]]))
def test_mask(self):
x = np.array([1, 2, 3, 4])
m = np.array([0, 1, 0, 0], bool)
assert_array_equal(x[m], np.array([2]))
def test_mask2(self):
x = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
m = np.array([0, 1], bool)
m2 = np.array([[0, 1, 0, 0], [1, 0, 0, 0]], bool)
m3 = np.array([[0, 1, 0, 0], [0, 0, 0, 0]], bool)
assert_array_equal(x[m], np.array([[5, 6, 7, 8]]))
assert_array_equal(x[m2], np.array([2, 5]))
assert_array_equal(x[m3], np.array([2]))
def test_assign_mask(self):
x = np.array([1, 2, 3, 4])
m = np.array([0, 1, 0, 0], bool)
x[m] = 5
assert_array_equal(x, np.array([1, 5, 3, 4]))
def test_assign_mask2(self):
xorig = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
m = np.array([0, 1], bool)
m2 = np.array([[0, 1, 0, 0], [1, 0, 0, 0]], bool)
m3 = np.array([[0, 1, 0, 0], [0, 0, 0, 0]], bool)
x = xorig.copy()
x[m] = 10
assert_array_equal(x, np.array([[1, 2, 3, 4], [10, 10, 10, 10]]))
x = xorig.copy()
x[m2] = 10
assert_array_equal(x, np.array([[1, 10, 3, 4], [10, 6, 7, 8]]))
x = xorig.copy()
x[m3] = 10
assert_array_equal(x, np.array([[1, 10, 3, 4], [5, 6, 7, 8]]))
class TestStringCompare(TestCase):
def test_string(self):
g1 = np.array(["This", "is", "example"])
g2 = np.array(["This", "was", "example"])
assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]])
def test_mixed(self):
g1 = np.array(["spam", "spa", "spammer", "and eggs"])
g2 = "spam"
assert_array_equal(g1 == g2, [x == g2 for x in g1])
assert_array_equal(g1 != g2, [x != g2 for x in g1])
assert_array_equal(g1 < g2, [x < g2 for x in g1])
assert_array_equal(g1 > g2, [x > g2 for x in g1])
assert_array_equal(g1 <= g2, [x <= g2 for x in g1])
assert_array_equal(g1 >= g2, [x >= g2 for x in g1])
def test_unicode(self):
g1 = np.array([sixu("This"), sixu("is"), sixu("example")])
g2 = np.array([sixu("This"), sixu("was"), sixu("example")])
assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]])
class TestArgmax(TestCase):
nan_arr = [
([0, 1, 2, 3, np.nan], 4),
([0, 1, 2, np.nan, 3], 3),
([np.nan, 0, 1, 2, 3], 0),
([np.nan, 0, np.nan, 2, 3], 0),
([0, 1, 2, 3, complex(0, np.nan)], 4),
([0, 1, 2, 3, complex(np.nan, 0)], 4),
([0, 1, 2, complex(np.nan, 0), 3], 3),
([0, 1, 2, complex(0, np.nan), 3], 3),
([complex(0, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0),
([complex(0, 0), complex(0, 2), complex(0, 1)], 1),
([complex(1, 0), complex(0, 2), complex(0, 1)], 0),
([complex(1, 0), complex(0, 2), complex(1, 1)], 2),
([np.datetime64('1923-04-14T12:43:12'),
np.datetime64('1994-06-21T14:43:15'),
np.datetime64('2001-10-15T04:10:32'),
np.datetime64('1995-11-25T16:02:16'),
np.datetime64('2005-01-04T03:14:12'),
np.datetime64('2041-12-03T14:05:03')], 5),
([np.datetime64('1935-09-14T04:40:11'),
np.datetime64('1949-10-12T12:32:11'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('2015-11-20T12:20:59'),
np.datetime64('1932-09-23T10:10:13'),
np.datetime64('2014-10-10T03:50:30')], 3),
# Assorted tests with NaTs
([np.datetime64('NaT'),
np.datetime64('NaT'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('NaT'),
np.datetime64('2015-09-23T10:10:13'),
np.datetime64('1932-10-10T03:50:30')], 4),
([np.datetime64('2059-03-14T12:43:12'),
np.datetime64('1996-09-21T14:43:15'),
np.datetime64('NaT'),
np.datetime64('2022-12-25T16:02:16'),
np.datetime64('1963-10-04T03:14:12'),
np.datetime64('2013-05-08T18:15:23')], 0),
([np.timedelta64(2, 's'),
np.timedelta64(1, 's'),
np.timedelta64('NaT', 's'),
np.timedelta64(3, 's')], 3),
([np.timedelta64('NaT', 's')] * 3, 0),
([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35),
timedelta(days=-1, seconds=23)], 0),
([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5),
timedelta(days=5, seconds=14)], 1),
([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5),
timedelta(days=10, seconds=43)], 2),
([False, False, False, False, True], 4),
([False, False, False, True, False], 3),
([True, False, False, False, False], 0),
([True, False, True, False, False], 0),
# Can't reduce a "flexible type"
#(['a', 'z', 'aa', 'zz'], 3),
#(['zz', 'a', 'aa', 'a'], 0),
#(['aa', 'z', 'zz', 'a'], 2),
]
def test_all(self):
a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
for i in range(a.ndim):
amax = a.max(i)
aargmax = a.argmax(i)
axes = list(range(a.ndim))
axes.remove(i)
assert_(np.all(amax == aargmax.choose(*a.transpose(i,*axes))))
def test_combinations(self):
for arr, pos in self.nan_arr:
assert_equal(np.argmax(arr), pos, err_msg="%r" % arr)
assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r" % arr)
def test_output_shape(self):
# see also gh-616
a = np.ones((10, 5))
# Check some simple shape mismatches
out = np.ones(11, dtype=np.int_)
assert_raises(ValueError, a.argmax, -1, out)
out = np.ones((2, 5), dtype=np.int_)
assert_raises(ValueError, a.argmax, -1, out)
# these could be relaxed possibly (used to allow even the previous)
out = np.ones((1, 10), dtype=np.int_)
assert_raises(ValueError, a.argmax, -1, np.ones((1, 10)))
out = np.ones(10, dtype=np.int_)
a.argmax(-1, out=out)
assert_equal(out, a.argmax(-1))
def test_argmax_unicode(self):
d = np.zeros(6031, dtype='<U9')
d[5942] = "as"
assert_equal(d.argmax(), 5942)
def test_np_vs_ndarray(self):
# make sure both ndarray.argmax and numpy.argmax support out/axis args
a = np.random.normal(size=(2,3))
#check positional args
out1 = np.zeros(2, dtype=int)
out2 = np.zeros(2, dtype=int)
assert_equal(a.argmax(1, out1), np.argmax(a, 1, out2))
assert_equal(out1, out2)
#check keyword args
out1 = np.zeros(3, dtype=int)
out2 = np.zeros(3, dtype=int)
assert_equal(a.argmax(out=out1, axis=0), np.argmax(a, out=out2, axis=0))
assert_equal(out1, out2)
class TestArgmin(TestCase):
nan_arr = [
([0, 1, 2, 3, np.nan], 4),
([0, 1, 2, np.nan, 3], 3),
([np.nan, 0, 1, 2, 3], 0),
([np.nan, 0, np.nan, 2, 3], 0),
([0, 1, 2, 3, complex(0, np.nan)], 4),
([0, 1, 2, 3, complex(np.nan, 0)], 4),
([0, 1, 2, complex(np.nan, 0), 3], 3),
([0, 1, 2, complex(0, np.nan), 3], 3),
([complex(0, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0),
([complex(0, 0), complex(0, 2), complex(0, 1)], 0),
([complex(1, 0), complex(0, 2), complex(0, 1)], 2),
([complex(1, 0), complex(0, 2), complex(1, 1)], 1),
([np.datetime64('1923-04-14T12:43:12'),
np.datetime64('1994-06-21T14:43:15'),
np.datetime64('2001-10-15T04:10:32'),
np.datetime64('1995-11-25T16:02:16'),
np.datetime64('2005-01-04T03:14:12'),
np.datetime64('2041-12-03T14:05:03')], 0),
([np.datetime64('1935-09-14T04:40:11'),
np.datetime64('1949-10-12T12:32:11'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('2014-11-20T12:20:59'),
np.datetime64('2015-09-23T10:10:13'),
np.datetime64('1932-10-10T03:50:30')], 5),
# Assorted tests with NaTs
([np.datetime64('NaT'),
np.datetime64('NaT'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('NaT'),
np.datetime64('2015-09-23T10:10:13'),
np.datetime64('1932-10-10T03:50:30')], 5),
([np.datetime64('2059-03-14T12:43:12'),
np.datetime64('1996-09-21T14:43:15'),
np.datetime64('NaT'),
np.datetime64('2022-12-25T16:02:16'),
np.datetime64('1963-10-04T03:14:12'),
np.datetime64('2013-05-08T18:15:23')], 4),
([np.timedelta64(2, 's'),
np.timedelta64(1, 's'),
np.timedelta64('NaT', 's'),
np.timedelta64(3, 's')], 1),
([np.timedelta64('NaT', 's')] * 3, 0),
([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35),
timedelta(days=-1, seconds=23)], 2),
([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5),
timedelta(days=5, seconds=14)], 0),
([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5),
timedelta(days=10, seconds=43)], 1),
([True, True, True, True, False], 4),
([True, True, True, False, True], 3),
([False, True, True, True, True], 0),
([False, True, False, True, True], 0),
# Can't reduce a "flexible type"
#(['a', 'z', 'aa', 'zz'], 0),
#(['zz', 'a', 'aa', 'a'], 1),
#(['aa', 'z', 'zz', 'a'], 3),
]
def test_all(self):
a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
for i in range(a.ndim):
amin = a.min(i)
aargmin = a.argmin(i)
axes = list(range(a.ndim))
axes.remove(i)
assert_(np.all(amin == aargmin.choose(*a.transpose(i,*axes))))
def test_combinations(self):
for arr, pos in self.nan_arr:
assert_equal(np.argmin(arr), pos, err_msg="%r" % arr)
assert_equal(arr[np.argmin(arr)], np.min(arr), err_msg="%r" % arr)
def test_minimum_signed_integers(self):
a = np.array([1, -2**7, -2**7 + 1], dtype=np.int8)
assert_equal(np.argmin(a), 1)
a = np.array([1, -2**15, -2**15 + 1], dtype=np.int16)
assert_equal(np.argmin(a), 1)
a = np.array([1, -2**31, -2**31 + 1], dtype=np.int32)
assert_equal(np.argmin(a), 1)
a = np.array([1, -2**63, -2**63 + 1], dtype=np.int64)
assert_equal(np.argmin(a), 1)
def test_output_shape(self):
# see also gh-616
a = np.ones((10, 5))
# Check some simple shape mismatches
out = np.ones(11, dtype=np.int_)
assert_raises(ValueError, a.argmin, -1, out)
out = np.ones((2, 5), dtype=np.int_)
assert_raises(ValueError, a.argmin, -1, out)
# these could be relaxed possibly (used to allow even the previous)
out = np.ones((1, 10), dtype=np.int_)
assert_raises(ValueError, a.argmin, -1, np.ones((1, 10)))
out = np.ones(10, dtype=np.int_)
a.argmin(-1, out=out)
assert_equal(out, a.argmin(-1))
def test_argmin_unicode(self):
d = np.ones(6031, dtype='<U9')
d[6001] = "0"
assert_equal(d.argmin(), 6001)
def test_np_vs_ndarray(self):
# make sure both ndarray.argmin and numpy.argmin support out/axis args
a = np.random.normal(size=(2,3))
#check positional args
out1 = np.zeros(2, dtype=int)
out2 = np.ones(2, dtype=int)
assert_equal(a.argmin(1, out1), np.argmin(a, 1, out2))
assert_equal(out1, out2)
#check keyword args
out1 = np.zeros(3, dtype=int)
out2 = np.ones(3, dtype=int)
assert_equal(a.argmin(out=out1, axis=0), np.argmin(a, out=out2, axis=0))
assert_equal(out1, out2)
class TestMinMax(TestCase):
def test_scalar(self):
assert_raises(ValueError, np.amax, 1, 1)
assert_raises(ValueError, np.amin, 1, 1)
assert_equal(np.amax(1, axis=0), 1)
assert_equal(np.amin(1, axis=0), 1)
assert_equal(np.amax(1, axis=None), 1)
assert_equal(np.amin(1, axis=None), 1)
def test_axis(self):
assert_raises(ValueError, np.amax, [1, 2, 3], 1000)
assert_equal(np.amax([[1, 2, 3]], axis=1), 3)
def test_datetime(self):
# NaTs are ignored
for dtype in ('m8[s]', 'm8[Y]'):
a = np.arange(10).astype(dtype)
a[3] = 'NaT'
assert_equal(np.amin(a), a[0])
assert_equal(np.amax(a), a[9])
a[0] = 'NaT'
assert_equal(np.amin(a), a[1])
assert_equal(np.amax(a), a[9])
a.fill('NaT')
assert_equal(np.amin(a), a[0])
assert_equal(np.amax(a), a[0])
class TestNewaxis(TestCase):
def test_basic(self):
sk = np.array([0, -0.1, 0.1])
res = 250*sk[:, np.newaxis]
assert_almost_equal(res.ravel(), 250*sk)
class TestClip(TestCase):
def _check_range(self, x, cmin, cmax):
assert_(np.all(x >= cmin))
assert_(np.all(x <= cmax))
def _clip_type(self, type_group, array_max,
clip_min, clip_max, inplace=False,
expected_min=None, expected_max=None):
if expected_min is None:
expected_min = clip_min
if expected_max is None:
expected_max = clip_max
for T in np.sctypes[type_group]:
if sys.byteorder == 'little':
byte_orders = ['=', '>']
else:
byte_orders = ['<', '=']
for byteorder in byte_orders:
dtype = np.dtype(T).newbyteorder(byteorder)
x = (np.random.random(1000) * array_max).astype(dtype)
if inplace:
x.clip(clip_min, clip_max, x)
else:
x = x.clip(clip_min, clip_max)
byteorder = '='
if x.dtype.byteorder == '|':
byteorder = '|'
assert_equal(x.dtype.byteorder, byteorder)
self._check_range(x, expected_min, expected_max)
return x
def test_basic(self):
for inplace in [False, True]:
self._clip_type(
'float', 1024, -12.8, 100.2, inplace=inplace)
self._clip_type(
'float', 1024, 0, 0, inplace=inplace)
self._clip_type(
'int', 1024, -120, 100.5, inplace=inplace)
self._clip_type(
'int', 1024, 0, 0, inplace=inplace)
self._clip_type(
'uint', 1024, 0, 0, inplace=inplace)
self._clip_type(
'uint', 1024, -120, 100, inplace=inplace, expected_min=0)
def test_record_array(self):
rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
y = rec['x'].clip(-0.3, 0.5)
self._check_range(y, -0.3, 0.5)
def test_max_or_min(self):
val = np.array([0, 1, 2, 3, 4, 5, 6, 7])
x = val.clip(3)
assert_(np.all(x >= 3))
x = val.clip(min=3)
assert_(np.all(x >= 3))
x = val.clip(max=4)
assert_(np.all(x <= 4))
class TestPutmask(object):
def tst_basic(self, x, T, mask, val):
np.putmask(x, mask, val)
assert_(np.all(x[mask] == T(val)))
assert_(x.dtype == T)
def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(1000)*100
mask = x < 40
for val in [-100, 0, 15]:
for types in np.sctypes.values():
for T in types:
if T not in unchecked_types:
yield self.tst_basic, x.copy().astype(T), T, mask, val
def test_mask_size(self):
assert_raises(ValueError, np.putmask, np.array([1, 2, 3]), [True], 5)
def tst_byteorder(self, dtype):
x = np.array([1, 2, 3], dtype)
np.putmask(x, [True, False, True], -1)
assert_array_equal(x, [-1, 2, -1])
def test_ip_byteorder(self):
for dtype in ('>i4', '<i4'):
yield self.tst_byteorder, dtype
def test_record_array(self):
# Note mixed byteorder.
rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)],
dtype=[('x', '<f8'), ('y', '>f8'), ('z', '<f8')])
np.putmask(rec['x'], [True, False], 10)
assert_array_equal(rec['x'], [10, 5])
assert_array_equal(rec['y'], [2, 4])
assert_array_equal(rec['z'], [3, 3])
np.putmask(rec['y'], [True, False], 11)
assert_array_equal(rec['x'], [10, 5])
assert_array_equal(rec['y'], [11, 4])
assert_array_equal(rec['z'], [3, 3])
def test_masked_array(self):
## x = np.array([1,2,3])
## z = np.ma.array(x,mask=[True,False,False])
## np.putmask(z,[True,True,True],3)
pass
class TestTake(object):
def tst_basic(self, x):
ind = list(range(x.shape[0]))
assert_array_equal(x.take(ind, axis=0), x)
def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(24)*100
x.shape = 2, 3, 4
for types in np.sctypes.values():
for T in types:
if T not in unchecked_types:
yield self.tst_basic, x.copy().astype(T)
def test_raise(self):
x = np.random.random(24)*100
x.shape = 2, 3, 4
assert_raises(IndexError, x.take, [0, 1, 2], axis=0)
assert_raises(IndexError, x.take, [-3], axis=0)
assert_array_equal(x.take([-1], axis=0)[0], x[1])
def test_clip(self):
x = np.random.random(24)*100
x.shape = 2, 3, 4
assert_array_equal(x.take([-1], axis=0, mode='clip')[0], x[0])
assert_array_equal(x.take([2], axis=0, mode='clip')[0], x[1])
def test_wrap(self):
x = np.random.random(24)*100
x.shape = 2, 3, 4
assert_array_equal(x.take([-1], axis=0, mode='wrap')[0], x[1])
assert_array_equal(x.take([2], axis=0, mode='wrap')[0], x[0])
assert_array_equal(x.take([3], axis=0, mode='wrap')[0], x[1])
def tst_byteorder(self, dtype):
x = np.array([1, 2, 3], dtype)
assert_array_equal(x.take([0, 2, 1]), [1, 3, 2])
def test_ip_byteorder(self):
for dtype in ('>i4', '<i4'):
yield self.tst_byteorder, dtype
def test_record_array(self):
# Note mixed byteorder.
rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)],
dtype=[('x', '<f8'), ('y', '>f8'), ('z', '<f8')])
rec1 = rec.take([1])
assert_(rec1['x'] == 5.0 and rec1['y'] == 4.0)
class TestLexsort(TestCase):
def test_basic(self):
a = [1, 2, 1, 3, 1, 5]
b = [0, 4, 5, 6, 2, 3]
idx = np.lexsort((b, a))
expected_idx = np.array([0, 4, 2, 1, 3, 5])
assert_array_equal(idx, expected_idx)
x = np.vstack((b, a))
idx = np.lexsort(x)
assert_array_equal(idx, expected_idx)
assert_array_equal(x[1][idx], np.sort(x[1]))
def test_datetime(self):
a = np.array([0,0,0], dtype='datetime64[D]')
b = np.array([2,1,0], dtype='datetime64[D]')
idx = np.lexsort((b, a))
expected_idx = np.array([2, 1, 0])
assert_array_equal(idx, expected_idx)
a = np.array([0,0,0], dtype='timedelta64[D]')
b = np.array([2,1,0], dtype='timedelta64[D]')
idx = np.lexsort((b, a))
expected_idx = np.array([2, 1, 0])
assert_array_equal(idx, expected_idx)
class TestIO(object):
"""Test tofile, fromfile, tobytes, and fromstring"""
def setUp(self):
shape = (2, 4, 3)
rand = np.random.random
self.x = rand(shape) + rand(shape).astype(np.complex)*1j
self.x[0,:, 1] = [np.nan, np.inf, -np.inf, np.nan]
self.dtype = self.x.dtype
self.tempdir = tempfile.mkdtemp()
self.filename = tempfile.mktemp(dir=self.tempdir)
def tearDown(self):
shutil.rmtree(self.tempdir)
def test_bool_fromstring(self):
v = np.array([True, False, True, False], dtype=np.bool_)
y = np.fromstring('1 0 -2.3 0.0', sep=' ', dtype=np.bool_)
assert_array_equal(v, y)
def test_uint64_fromstring(self):
d = np.fromstring("9923372036854775807 104783749223640",
dtype=np.uint64, sep=' ')
e = np.array([9923372036854775807, 104783749223640], dtype=np.uint64)
assert_array_equal(d, e)
def test_int64_fromstring(self):
d = np.fromstring("-25041670086757 104783749223640",
dtype=np.int64, sep=' ')
e = np.array([-25041670086757, 104783749223640], dtype=np.int64)
assert_array_equal(d, e)
def test_empty_files_binary(self):
f = open(self.filename, 'w')
f.close()
y = np.fromfile(self.filename)
assert_(y.size == 0, "Array not empty")
def test_empty_files_text(self):
f = open(self.filename, 'w')
f.close()
y = np.fromfile(self.filename, sep=" ")
assert_(y.size == 0, "Array not empty")
def test_roundtrip_file(self):
f = open(self.filename, 'wb')
self.x.tofile(f)
f.close()
# NB. doesn't work with flush+seek, due to use of C stdio
f = open(self.filename, 'rb')
y = np.fromfile(f, dtype=self.dtype)
f.close()
assert_array_equal(y, self.x.flat)
def test_roundtrip_filename(self):
self.x.tofile(self.filename)
y = np.fromfile(self.filename, dtype=self.dtype)
assert_array_equal(y, self.x.flat)
def test_roundtrip_binary_str(self):
s = self.x.tobytes()
y = np.fromstring(s, dtype=self.dtype)
assert_array_equal(y, self.x.flat)
s = self.x.tobytes('F')
y = np.fromstring(s, dtype=self.dtype)
assert_array_equal(y, self.x.flatten('F'))
def test_roundtrip_str(self):
x = self.x.real.ravel()
s = "@".join(map(str, x))
y = np.fromstring(s, sep="@")
# NB. str imbues less precision
nan_mask = ~np.isfinite(x)
assert_array_equal(x[nan_mask], y[nan_mask])
assert_array_almost_equal(x[~nan_mask], y[~nan_mask], decimal=5)
def test_roundtrip_repr(self):
x = self.x.real.ravel()
s = "@".join(map(repr, x))
y = np.fromstring(s, sep="@")
assert_array_equal(x, y)
def test_file_position_after_fromfile(self):
# gh-4118
sizes = [io.DEFAULT_BUFFER_SIZE//8,
io.DEFAULT_BUFFER_SIZE,
io.DEFAULT_BUFFER_SIZE*8]
for size in sizes:
f = open(self.filename, 'wb')
f.seek(size-1)
f.write(b'\0')
f.close()
for mode in ['rb', 'r+b']:
err_msg = "%d %s" % (size, mode)
f = open(self.filename, mode)
f.read(2)
np.fromfile(f, dtype=np.float64, count=1)
pos = f.tell()
f.close()
assert_equal(pos, 10, err_msg=err_msg)
def test_file_position_after_tofile(self):
# gh-4118
sizes = [io.DEFAULT_BUFFER_SIZE//8,
io.DEFAULT_BUFFER_SIZE,
io.DEFAULT_BUFFER_SIZE*8]
for size in sizes:
err_msg = "%d" % (size,)
f = open(self.filename, 'wb')
f.seek(size-1)
f.write(b'\0')
f.seek(10)
f.write(b'12')
np.array([0], dtype=np.float64).tofile(f)
pos = f.tell()
f.close()
assert_equal(pos, 10 + 2 + 8, err_msg=err_msg)
f = open(self.filename, 'r+b')
f.read(2)
f.seek(0, 1) # seek between read&write required by ANSI C
np.array([0], dtype=np.float64).tofile(f)
pos = f.tell()
f.close()
assert_equal(pos, 10, err_msg=err_msg)
def _check_from(self, s, value, **kw):
y = np.fromstring(asbytes(s), **kw)
assert_array_equal(y, value)
f = open(self.filename, 'wb')
f.write(asbytes(s))
f.close()
y = np.fromfile(self.filename, **kw)
assert_array_equal(y, value)
def test_nan(self):
self._check_from(
"nan +nan -nan NaN nan(foo) +NaN(BAR) -NAN(q_u_u_x_)",
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
sep=' ')
def test_inf(self):
self._check_from(
"inf +inf -inf infinity -Infinity iNfInItY -inF",
[np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf],
sep=' ')
def test_numbers(self):
self._check_from("1.234 -1.234 .3 .3e55 -123133.1231e+133",
[1.234, -1.234, .3, .3e55, -123133.1231e+133], sep=' ')
def test_binary(self):
self._check_from('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@',
np.array([1, 2, 3, 4]),
dtype='<f4')
@dec.slow # takes > 1 minute on mechanical hard drive
def test_big_binary(self):
"""Test workarounds for 32-bit limited fwrite, fseek, and ftell
calls in windows. These normally would hang doing something like this.
See http://projects.scipy.org/numpy/ticket/1660"""
if sys.platform != 'win32':
return
try:
# before workarounds, only up to 2**32-1 worked
fourgbplus = 2**32 + 2**16
testbytes = np.arange(8, dtype=np.int8)
n = len(testbytes)
flike = tempfile.NamedTemporaryFile()
f = flike.file
np.tile(testbytes, fourgbplus // testbytes.nbytes).tofile(f)
flike.seek(0)
a = np.fromfile(f, dtype=np.int8)
flike.close()
assert_(len(a) == fourgbplus)
# check only start and end for speed:
assert_((a[:n] == testbytes).all())
assert_((a[-n:] == testbytes).all())
except (MemoryError, ValueError):
pass
def test_string(self):
self._check_from('1,2,3,4', [1., 2., 3., 4.], sep=',')
def test_counted_string(self):
self._check_from('1,2,3,4', [1., 2., 3., 4.], count=4, sep=',')
self._check_from('1,2,3,4', [1., 2., 3.], count=3, sep=',')
self._check_from('1,2,3,4', [1., 2., 3., 4.], count=-1, sep=',')
def test_string_with_ws(self):
self._check_from('1 2 3 4 ', [1, 2, 3, 4], dtype=int, sep=' ')
def test_counted_string_with_ws(self):
self._check_from('1 2 3 4 ', [1, 2, 3], count=3, dtype=int,
sep=' ')
def test_ascii(self):
self._check_from('1 , 2 , 3 , 4', [1., 2., 3., 4.], sep=',')
self._check_from('1,2,3,4', [1., 2., 3., 4.], dtype=float, sep=',')
def test_malformed(self):
self._check_from('1.234 1,234', [1.234, 1.], sep=' ')
def test_long_sep(self):
self._check_from('1_x_3_x_4_x_5', [1, 3, 4, 5], sep='_x_')
def test_dtype(self):
v = np.array([1, 2, 3, 4], dtype=np.int_)
self._check_from('1,2,3,4', v, sep=',', dtype=np.int_)
def test_dtype_bool(self):
# can't use _check_from because fromstring can't handle True/False
v = np.array([True, False, True, False], dtype=np.bool_)
s = '1,0,-2.3,0'
f = open(self.filename, 'wb')
f.write(asbytes(s))
f.close()
y = np.fromfile(self.filename, sep=',', dtype=np.bool_)
assert_(y.dtype == '?')
assert_array_equal(y, v)
def test_tofile_sep(self):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
f = open(self.filename, 'w')
x.tofile(f, sep=',')
f.close()
f = open(self.filename, 'r')
s = f.read()
f.close()
assert_equal(s, '1.51,2.0,3.51,4.0')
def test_tofile_format(self):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
f = open(self.filename, 'w')
x.tofile(f, sep=',', format='%.2f')
f.close()
f = open(self.filename, 'r')
s = f.read()
f.close()
assert_equal(s, '1.51,2.00,3.51,4.00')
def test_locale(self):
in_foreign_locale(self.test_numbers)()
in_foreign_locale(self.test_nan)()
in_foreign_locale(self.test_inf)()
in_foreign_locale(self.test_counted_string)()
in_foreign_locale(self.test_ascii)()
in_foreign_locale(self.test_malformed)()
in_foreign_locale(self.test_tofile_sep)()
in_foreign_locale(self.test_tofile_format)()
class TestFromBuffer(object):
def tst_basic(self, buffer, expected, kwargs):
assert_array_equal(np.frombuffer(buffer,**kwargs), expected)
def test_ip_basic(self):
for byteorder in ['<', '>']:
for dtype in [float, int, np.complex]:
dt = np.dtype(dtype).newbyteorder(byteorder)
x = (np.random.random((4, 7))*5).astype(dt)
buf = x.tobytes()
yield self.tst_basic, buf, x.flat, {'dtype':dt}
def test_empty(self):
yield self.tst_basic, asbytes(''), np.array([]), {}
class TestFlat(TestCase):
def setUp(self):
a0 = np.arange(20.0)
a = a0.reshape(4, 5)
a0.shape = (4, 5)
a.flags.writeable = False
self.a = a
self.b = a[::2, ::2]
self.a0 = a0
self.b0 = a0[::2, ::2]
def test_contiguous(self):
testpassed = False
try:
self.a.flat[12] = 100.0
except ValueError:
testpassed = True
assert testpassed
assert self.a.flat[12] == 12.0
def test_discontiguous(self):
testpassed = False
try:
self.b.flat[4] = 100.0
except ValueError:
testpassed = True
assert testpassed
assert self.b.flat[4] == 12.0
def test___array__(self):
c = self.a.flat.__array__()
d = self.b.flat.__array__()
e = self.a0.flat.__array__()
f = self.b0.flat.__array__()
assert c.flags.writeable is False
assert d.flags.writeable is False
assert e.flags.writeable is True
assert f.flags.writeable is True
assert c.flags.updateifcopy is False
assert d.flags.updateifcopy is False
assert e.flags.updateifcopy is False
assert f.flags.updateifcopy is True
assert f.base is self.b0
class TestResize(TestCase):
def test_basic(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
x.resize((5, 5))
assert_array_equal(x.flat[:9],
np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).flat)
assert_array_equal(x[9:].flat, 0)
def test_check_reference(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
y = x
self.assertRaises(ValueError, x.resize, (5, 1))
del y # avoid pyflakes unused variable warning.
def test_int_shape(self):
x = np.eye(3)
x.resize(3)
assert_array_equal(x, np.eye(3)[0,:])
def test_none_shape(self):
x = np.eye(3)
x.resize(None)
assert_array_equal(x, np.eye(3))
x.resize()
assert_array_equal(x, np.eye(3))
def test_invalid_arguements(self):
self.assertRaises(TypeError, np.eye(3).resize, 'hi')
self.assertRaises(ValueError, np.eye(3).resize, -1)
self.assertRaises(TypeError, np.eye(3).resize, order=1)
self.assertRaises(TypeError, np.eye(3).resize, refcheck='hi')
def test_freeform_shape(self):
x = np.eye(3)
x.resize(3, 2, 1)
assert_(x.shape == (3, 2, 1))
def test_zeros_appended(self):
x = np.eye(3)
x.resize(2, 3, 3)
assert_array_equal(x[0], np.eye(3))
assert_array_equal(x[1], np.zeros((3, 3)))
def test_obj_obj(self):
# check memory is initialized on resize, gh-4857
a = np.ones(10, dtype=[('k', object, 2)])
a.resize(15,)
assert_equal(a.shape, (15,))
assert_array_equal(a['k'][-5:], 0)
assert_array_equal(a['k'][:-5], 1)
class TestRecord(TestCase):
def test_field_rename(self):
dt = np.dtype([('f', float), ('i', int)])
dt.names = ['p', 'q']
assert_equal(dt.names, ['p', 'q'])
if sys.version_info[0] >= 3:
def test_bytes_fields(self):
# Bytes are not allowed in field names and not recognized in titles
# on Py3
assert_raises(TypeError, np.dtype, [(asbytes('a'), int)])
assert_raises(TypeError, np.dtype, [(('b', asbytes('a')), int)])
dt = np.dtype([((asbytes('a'), 'b'), int)])
assert_raises(ValueError, dt.__getitem__, asbytes('a'))
x = np.array([(1,), (2,), (3,)], dtype=dt)
assert_raises(IndexError, x.__getitem__, asbytes('a'))
y = x[0]
assert_raises(IndexError, y.__getitem__, asbytes('a'))
else:
def test_unicode_field_titles(self):
# Unicode field titles are added to field dict on Py2
title = unicode('b')
dt = np.dtype([((title, 'a'), int)])
dt[title]
dt['a']
x = np.array([(1,), (2,), (3,)], dtype=dt)
x[title]
x['a']
y = x[0]
y[title]
y['a']
def test_unicode_field_names(self):
# Unicode field names are not allowed on Py2
title = unicode('b')
assert_raises(TypeError, np.dtype, [(title, int)])
assert_raises(TypeError, np.dtype, [(('a', title), int)])
def test_field_names(self):
# Test unicode and 8-bit / byte strings can be used
a = np.zeros((1,), dtype=[('f1', 'i4'),
('f2', 'i4'),
('f3', [('sf1', 'i4')])])
is_py3 = sys.version_info[0] >= 3
if is_py3:
funcs = (str,)
# byte string indexing fails gracefully
assert_raises(IndexError, a.__setitem__, asbytes('f1'), 1)
assert_raises(IndexError, a.__getitem__, asbytes('f1'))
assert_raises(IndexError, a['f1'].__setitem__, asbytes('sf1'), 1)
assert_raises(IndexError, a['f1'].__getitem__, asbytes('sf1'))
else:
funcs = (str, unicode)
for func in funcs:
b = a.copy()
fn1 = func('f1')
b[fn1] = 1
assert_equal(b[fn1], 1)
fnn = func('not at all')
assert_raises(ValueError, b.__setitem__, fnn, 1)
assert_raises(ValueError, b.__getitem__, fnn)
b[0][fn1] = 2
assert_equal(b[fn1], 2)
# Subfield
assert_raises(IndexError, b[0].__setitem__, fnn, 1)
assert_raises(IndexError, b[0].__getitem__, fnn)
# Subfield
fn3 = func('f3')
sfn1 = func('sf1')
b[fn3][sfn1] = 1
assert_equal(b[fn3][sfn1], 1)
assert_raises(ValueError, b[fn3].__setitem__, fnn, 1)
assert_raises(ValueError, b[fn3].__getitem__, fnn)
# multiple Subfields
fn2 = func('f2')
b[fn2] = 3
assert_equal(b[['f1', 'f2']][0].tolist(), (2, 3))
assert_equal(b[['f2', 'f1']][0].tolist(), (3, 2))
assert_equal(b[['f1', 'f3']][0].tolist(), (2, (1,)))
# view of subfield view/copy
assert_equal(b[['f1', 'f2']][0].view(('i4', 2)).tolist(), (2, 3))
assert_equal(b[['f2', 'f1']][0].view(('i4', 2)).tolist(), (3, 2))
view_dtype = [('f1', 'i4'), ('f3', [('', 'i4')])]
assert_equal(b[['f1', 'f3']][0].view(view_dtype).tolist(), (2, (1,)))
# non-ascii unicode field indexing is well behaved
if not is_py3:
raise SkipTest('non ascii unicode field indexing skipped; '
'raises segfault on python 2.x')
else:
assert_raises(ValueError, a.__setitem__, sixu('\u03e0'), 1)
assert_raises(ValueError, a.__getitem__, sixu('\u03e0'))
def test_field_names_deprecation(self):
def collect_warnings(f, *args, **kwargs):
with warnings.catch_warnings(record=True) as log:
warnings.simplefilter("always")
f(*args, **kwargs)
return [w.category for w in log]
a = np.zeros((1,), dtype=[('f1', 'i4'),
('f2', 'i4'),
('f3', [('sf1', 'i4')])])
a['f1'][0] = 1
a['f2'][0] = 2
a['f3'][0] = (3,)
b = np.zeros((1,), dtype=[('f1', 'i4'),
('f2', 'i4'),
('f3', [('sf1', 'i4')])])
b['f1'][0] = 1
b['f2'][0] = 2
b['f3'][0] = (3,)
# All the different functions raise a warning, but not an error, and
# 'a' is not modified:
assert_equal(collect_warnings(a[['f1', 'f2']].__setitem__, 0, (10, 20)),
[FutureWarning])
assert_equal(a, b)
# Views also warn
subset = a[['f1', 'f2']]
subset_view = subset.view()
assert_equal(collect_warnings(subset_view['f1'].__setitem__, 0, 10),
[FutureWarning])
# But the write goes through:
assert_equal(subset['f1'][0], 10)
# Only one warning per multiple field indexing, though (even if there
# are multiple views involved):
assert_equal(collect_warnings(subset['f1'].__setitem__, 0, 10), [])
def test_record_hash(self):
a = np.array([(1, 2), (1, 2)], dtype='i1,i2')
a.flags.writeable = False
b = np.array([(1, 2), (3, 4)], dtype=[('num1', 'i1'), ('num2', 'i2')])
b.flags.writeable = False
c = np.array([(1, 2), (3, 4)], dtype='i1,i2')
c.flags.writeable = False
self.assertTrue(hash(a[0]) == hash(a[1]))
self.assertTrue(hash(a[0]) == hash(b[0]))
self.assertTrue(hash(a[0]) != hash(b[1]))
self.assertTrue(hash(c[0]) == hash(a[0]) and c[0] == a[0])
def test_record_no_hash(self):
a = np.array([(1, 2), (1, 2)], dtype='i1,i2')
self.assertRaises(TypeError, hash, a[0])
def test_empty_structure_creation(self):
# make sure these do not raise errors (gh-5631)
np.array([()], dtype={'names': [], 'formats': [],
'offsets': [], 'itemsize': 12})
np.array([(), (), (), (), ()], dtype={'names': [], 'formats': [],
'offsets': [], 'itemsize': 12})
class TestView(TestCase):
def test_basic(self):
x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)],
dtype=[('r', np.int8), ('g', np.int8),
('b', np.int8), ('a', np.int8)])
# We must be specific about the endianness here:
y = x.view(dtype='<i4')
# ... and again without the keyword.
z = x.view('<i4')
assert_array_equal(y, z)
assert_array_equal(y, [67305985, 134678021])
def _mean(a, **args):
return a.mean(**args)
def _var(a, **args):
return a.var(**args)
def _std(a, **args):
return a.std(**args)
class TestStats(TestCase):
funcs = [_mean, _var, _std]
def setUp(self):
np.random.seed(range(3))
self.rmat = np.random.random((4, 5))
self.cmat = self.rmat + 1j * self.rmat
self.omat = np.array([Decimal(repr(r)) for r in self.rmat.flat])
self.omat = self.omat.reshape(4, 5)
def test_keepdims(self):
mat = np.eye(3)
for f in self.funcs:
for axis in [0, 1]:
res = f(mat, axis=axis, keepdims=True)
assert_(res.ndim == mat.ndim)
assert_(res.shape[axis] == 1)
for axis in [None]:
res = f(mat, axis=axis, keepdims=True)
assert_(res.shape == (1, 1))
def test_out(self):
mat = np.eye(3)
for f in self.funcs:
out = np.zeros(3)
tgt = f(mat, axis=1)
res = f(mat, axis=1, out=out)
assert_almost_equal(res, out)
assert_almost_equal(res, tgt)
out = np.empty(2)
assert_raises(ValueError, f, mat, axis=1, out=out)
out = np.empty((2, 2))
assert_raises(ValueError, f, mat, axis=1, out=out)
def test_dtype_from_input(self):
icodes = np.typecodes['AllInteger']
fcodes = np.typecodes['AllFloat']
# object type
for f in self.funcs:
mat = np.array([[Decimal(1)]*3]*3)
tgt = mat.dtype.type
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = type(f(mat, axis=None))
assert_(res is Decimal)
# integer types
for f in self.funcs:
for c in icodes:
mat = np.eye(3, dtype=c)
tgt = np.float64
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None).dtype.type
assert_(res is tgt)
# mean for float types
for f in [_mean]:
for c in fcodes:
mat = np.eye(3, dtype=c)
tgt = mat.dtype.type
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None).dtype.type
assert_(res is tgt)
# var, std for float types
for f in [_var, _std]:
for c in fcodes:
mat = np.eye(3, dtype=c)
# deal with complex types
tgt = mat.real.dtype.type
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None).dtype.type
assert_(res is tgt)
def test_dtype_from_dtype(self):
mat = np.eye(3)
# stats for integer types
# FIXME:
# this needs definition as there are lots places along the line
# where type casting may take place.
#for f in self.funcs:
# for c in np.typecodes['AllInteger']:
# tgt = np.dtype(c).type
# res = f(mat, axis=1, dtype=c).dtype.type
# assert_(res is tgt)
# # scalar case
# res = f(mat, axis=None, dtype=c).dtype.type
# assert_(res is tgt)
# stats for float types
for f in self.funcs:
for c in np.typecodes['AllFloat']:
tgt = np.dtype(c).type
res = f(mat, axis=1, dtype=c).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None, dtype=c).dtype.type
assert_(res is tgt)
def test_ddof(self):
for f in [_var]:
for ddof in range(3):
dim = self.rmat.shape[1]
tgt = f(self.rmat, axis=1) * dim
res = f(self.rmat, axis=1, ddof=ddof) * (dim - ddof)
for f in [_std]:
for ddof in range(3):
dim = self.rmat.shape[1]
tgt = f(self.rmat, axis=1) * np.sqrt(dim)
res = f(self.rmat, axis=1, ddof=ddof) * np.sqrt(dim - ddof)
assert_almost_equal(res, tgt)
assert_almost_equal(res, tgt)
def test_ddof_too_big(self):
dim = self.rmat.shape[1]
for f in [_var, _std]:
for ddof in range(dim, dim + 2):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
res = f(self.rmat, axis=1, ddof=ddof)
assert_(not (res < 0).any())
assert_(len(w) > 0)
assert_(issubclass(w[0].category, RuntimeWarning))
def test_empty(self):
A = np.zeros((0, 3))
for f in self.funcs:
for axis in [0, None]:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
assert_(np.isnan(f(A, axis=axis)).all())
assert_(len(w) > 0)
assert_(issubclass(w[0].category, RuntimeWarning))
for axis in [1]:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
assert_equal(f(A, axis=axis), np.zeros([]))
def test_mean_values(self):
for mat in [self.rmat, self.cmat, self.omat]:
for axis in [0, 1]:
tgt = mat.sum(axis=axis)
res = _mean(mat, axis=axis) * mat.shape[axis]
assert_almost_equal(res, tgt)
for axis in [None]:
tgt = mat.sum(axis=axis)
res = _mean(mat, axis=axis) * np.prod(mat.shape)
assert_almost_equal(res, tgt)
def test_var_values(self):
for mat in [self.rmat, self.cmat, self.omat]:
for axis in [0, 1, None]:
msqr = _mean(mat * mat.conj(), axis=axis)
mean = _mean(mat, axis=axis)
tgt = msqr - mean * mean.conjugate()
res = _var(mat, axis=axis)
assert_almost_equal(res, tgt)
def test_std_values(self):
for mat in [self.rmat, self.cmat, self.omat]:
for axis in [0, 1, None]:
tgt = np.sqrt(_var(mat, axis=axis))
res = _std(mat, axis=axis)
assert_almost_equal(res, tgt)
def test_subclass(self):
class TestArray(np.ndarray):
def __new__(cls, data, info):
result = np.array(data)
result = result.view(cls)
result.info = info
return result
def __array_finalize__(self, obj):
self.info = getattr(obj, "info", '')
dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba')
res = dat.mean(1)
assert_(res.info == dat.info)
res = dat.std(1)
assert_(res.info == dat.info)
res = dat.var(1)
assert_(res.info == dat.info)
class TestVdot(TestCase):
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_array_order(self):
a = np.array([[1, 2], [3, 4]], order='C')
b = np.array([[1, 2], [3, 4]], order='F')
res = np.vdot(a, a)
# integer arrays are exact
assert_equal(np.vdot(a, b), res)
assert_equal(np.vdot(b, a), res)
assert_equal(np.vdot(b, b), res)
class TestDot(TestCase):
def setUp(self):
np.random.seed(128)
self.A = np.random.rand(4, 2)
self.b1 = np.random.rand(2, 1)
self.b2 = np.random.rand(2)
self.b3 = np.random.rand(1, 2)
self.b4 = np.random.rand(4)
self.N = 7
def test_dotmatmat(self):
A = self.A
res = np.dot(A.transpose(), A)
tgt = np.array([[1.45046013, 0.86323640],
[0.86323640, 0.84934569]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotmatvec(self):
A, b1 = self.A, self.b1
res = np.dot(A, b1)
tgt = np.array([[0.32114320], [0.04889721],
[0.15696029], [0.33612621]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotmatvec2(self):
A, b2 = self.A, self.b2
res = np.dot(A, b2)
tgt = np.array([0.29677940, 0.04518649, 0.14468333, 0.31039293])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecmat(self):
A, b4 = self.A, self.b4
res = np.dot(b4, A)
tgt = np.array([1.23495091, 1.12222648])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecmat2(self):
b3, A = self.b3, self.A
res = np.dot(b3, A.transpose())
tgt = np.array([[0.58793804, 0.08957460, 0.30605758, 0.62716383]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecmat3(self):
A, b4 = self.A, self.b4
res = np.dot(A.transpose(), b4)
tgt = np.array([1.23495091, 1.12222648])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecvecouter(self):
b1, b3 = self.b1, self.b3
res = np.dot(b1, b3)
tgt = np.array([[0.20128610, 0.08400440], [0.07190947, 0.03001058]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecvecinner(self):
b1, b3 = self.b1, self.b3
res = np.dot(b3, b1)
tgt = np.array([[ 0.23129668]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotcolumnvect1(self):
b1 = np.ones((3, 1))
b2 = [5.3]
res = np.dot(b1, b2)
tgt = np.array([5.3, 5.3, 5.3])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotcolumnvect2(self):
b1 = np.ones((3, 1)).transpose()
b2 = [6.2]
res = np.dot(b2, b1)
tgt = np.array([6.2, 6.2, 6.2])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecscalar(self):
np.random.seed(100)
b1 = np.random.rand(1, 1)
b2 = np.random.rand(1, 4)
res = np.dot(b1, b2)
tgt = np.array([[0.15126730, 0.23068496, 0.45905553, 0.00256425]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecscalar2(self):
np.random.seed(100)
b1 = np.random.rand(4, 1)
b2 = np.random.rand(1, 1)
res = np.dot(b1, b2)
tgt = np.array([[0.00256425],[0.00131359],[0.00200324],[ 0.00398638]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_all(self):
dims = [(), (1,), (1, 1)]
dout = [(), (1,), (1, 1), (1,), (), (1,), (1, 1), (1,), (1, 1)]
for dim, (dim1, dim2) in zip(dout, itertools.product(dims, dims)):
b1 = np.zeros(dim1)
b2 = np.zeros(dim2)
res = np.dot(b1, b2)
tgt = np.zeros(dim)
assert_(res.shape == tgt.shape)
assert_almost_equal(res, tgt, decimal=self.N)
def test_vecobject(self):
class Vec(object):
def __init__(self, sequence=None):
if sequence is None:
sequence = []
self.array = np.array(sequence)
def __add__(self, other):
out = Vec()
out.array = self.array + other.array
return out
def __sub__(self, other):
out = Vec()
out.array = self.array - other.array
return out
def __mul__(self, other): # with scalar
out = Vec(self.array.copy())
out.array *= other
return out
def __rmul__(self, other):
return self*other
U_non_cont = np.transpose([[1., 1.], [1., 2.]])
U_cont = np.ascontiguousarray(U_non_cont)
x = np.array([Vec([1., 0.]), Vec([0., 1.])])
zeros = np.array([Vec([0., 0.]), Vec([0., 0.])])
zeros_test = np.dot(U_cont, x) - np.dot(U_non_cont, x)
assert_equal(zeros[0].array, zeros_test[0].array)
assert_equal(zeros[1].array, zeros_test[1].array)
def test_dot_2args(self):
from numpy.core.multiarray import dot
a = np.array([[1, 2], [3, 4]], dtype=float)
b = np.array([[1, 0], [1, 1]], dtype=float)
c = np.array([[3, 2], [7, 4]], dtype=float)
d = dot(a, b)
assert_allclose(c, d)
def test_dot_3args(self):
from numpy.core.multiarray import dot
np.random.seed(22)
f = np.random.random_sample((1024, 16))
v = np.random.random_sample((16, 32))
r = np.empty((1024, 32))
for i in range(12):
dot(f, v, r)
assert_equal(sys.getrefcount(r), 2)
r2 = dot(f, v, out=None)
assert_array_equal(r2, r)
assert_(r is dot(f, v, out=r))
v = v[:, 0].copy() # v.shape == (16,)
r = r[:, 0].copy() # r.shape == (1024,)
r2 = dot(f, v)
assert_(r is dot(f, v, r))
assert_array_equal(r2, r)
def test_dot_3args_errors(self):
from numpy.core.multiarray import dot
np.random.seed(22)
f = np.random.random_sample((1024, 16))
v = np.random.random_sample((16, 32))
r = np.empty((1024, 31))
assert_raises(ValueError, dot, f, v, r)
r = np.empty((1024,))
assert_raises(ValueError, dot, f, v, r)
r = np.empty((32,))
assert_raises(ValueError, dot, f, v, r)
r = np.empty((32, 1024))
assert_raises(ValueError, dot, f, v, r)
assert_raises(ValueError, dot, f, v, r.T)
r = np.empty((1024, 64))
assert_raises(ValueError, dot, f, v, r[:, ::2])
assert_raises(ValueError, dot, f, v, r[:, :32])
r = np.empty((1024, 32), dtype=np.float32)
assert_raises(ValueError, dot, f, v, r)
r = np.empty((1024, 32), dtype=int)
assert_raises(ValueError, dot, f, v, r)
def test_dot_array_order(self):
a = np.array([[1, 2], [3, 4]], order='C')
b = np.array([[1, 2], [3, 4]], order='F')
res = np.dot(a, a)
# integer arrays are exact
assert_equal(np.dot(a, b), res)
assert_equal(np.dot(b, a), res)
assert_equal(np.dot(b, b), res)
def test_dot_scalar_and_matrix_of_objects(self):
# Ticket #2469
arr = np.matrix([1, 2], dtype=object)
desired = np.matrix([[3, 6]], dtype=object)
assert_equal(np.dot(arr, 3), desired)
assert_equal(np.dot(3, arr), desired)
def test_dot_override(self):
class A(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return "A"
class B(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return NotImplemented
a = A()
b = B()
c = np.array([[1]])
assert_equal(np.dot(a, b), "A")
assert_equal(c.dot(a), "A")
assert_raises(TypeError, np.dot, b, c)
assert_raises(TypeError, c.dot, b)
def test_accelerate_framework_sgemv_fix(self):
def aligned_array(shape, align, dtype, order='C'):
d = dtype(0)
N = np.prod(shape)
tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8)
address = tmp.__array_interface__["data"][0]
for offset in range(align):
if (address + offset) % align == 0:
break
tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype)
return tmp.reshape(shape, order=order)
def as_aligned(arr, align, dtype, order='C'):
aligned = aligned_array(arr.shape, align, dtype, order)
aligned[:] = arr[:]
return aligned
def assert_dot_close(A, X, desired):
assert_allclose(np.dot(A, X), desired, rtol=1e-5, atol=1e-7)
m = aligned_array(100, 15, np.float32)
s = aligned_array((100, 100), 15, np.float32)
np.dot(s, m) # this will always segfault if the bug is present
testdata = itertools.product((15,32), (10000,), (200,89), ('C','F'))
for align, m, n, a_order in testdata:
# Calculation in double precision
A_d = np.random.rand(m, n)
X_d = np.random.rand(n)
desired = np.dot(A_d, X_d)
# Calculation with aligned single precision
A_f = as_aligned(A_d, align, np.float32, order=a_order)
X_f = as_aligned(X_d, align, np.float32)
assert_dot_close(A_f, X_f, desired)
# Strided A rows
A_d_2 = A_d[::2]
desired = np.dot(A_d_2, X_d)
A_f_2 = A_f[::2]
assert_dot_close(A_f_2, X_f, desired)
# Strided A columns, strided X vector
A_d_22 = A_d_2[:, ::2]
X_d_2 = X_d[::2]
desired = np.dot(A_d_22, X_d_2)
A_f_22 = A_f_2[:, ::2]
X_f_2 = X_f[::2]
assert_dot_close(A_f_22, X_f_2, desired)
# Check the strides are as expected
if a_order == 'F':
assert_equal(A_f_22.strides, (8, 8 * m))
else:
assert_equal(A_f_22.strides, (8 * n, 8))
assert_equal(X_f_2.strides, (8,))
# Strides in A rows + cols only
X_f_2c = as_aligned(X_f_2, align, np.float32)
assert_dot_close(A_f_22, X_f_2c, desired)
# Strides just in A cols
A_d_12 = A_d[:, ::2]
desired = np.dot(A_d_12, X_d_2)
A_f_12 = A_f[:, ::2]
assert_dot_close(A_f_12, X_f_2c, desired)
# Strides in A cols and X
assert_dot_close(A_f_12, X_f_2, desired)
class MatmulCommon():
"""Common tests for '@' operator and numpy.matmul.
Do not derive from TestCase to avoid nose running it.
"""
# Should work with these types. Will want to add
# "O" at some point
types = "?bhilqBHILQefdgFDG"
def test_exceptions(self):
dims = [
((1,), (2,)), # mismatched vector vector
((2, 1,), (2,)), # mismatched matrix vector
((2,), (1, 2)), # mismatched vector matrix
((1, 2), (3, 1)), # mismatched matrix matrix
((1,), ()), # vector scalar
((), (1)), # scalar vector
((1, 1), ()), # matrix scalar
((), (1, 1)), # scalar matrix
((2, 2, 1), (3, 1, 2)), # cannot broadcast
]
for dt, (dm1, dm2) in itertools.product(self.types, dims):
a = np.ones(dm1, dtype=dt)
b = np.ones(dm2, dtype=dt)
assert_raises(ValueError, self.matmul, a, b)
def test_shapes(self):
dims = [
((1, 1), (2, 1, 1)), # broadcast first argument
((2, 1, 1), (1, 1)), # broadcast second argument
((2, 1, 1), (2, 1, 1)), # matrix stack sizes match
]
for dt, (dm1, dm2) in itertools.product(self.types, dims):
a = np.ones(dm1, dtype=dt)
b = np.ones(dm2, dtype=dt)
res = self.matmul(a, b)
assert_(res.shape == (2, 1, 1))
# vector vector returns scalars.
for dt in self.types:
a = np.ones((2,), dtype=dt)
b = np.ones((2,), dtype=dt)
c = self.matmul(a, b)
assert_(np.array(c).shape == ())
def test_result_types(self):
mat = np.ones((1,1))
vec = np.ones((1,))
for dt in self.types:
m = mat.astype(dt)
v = vec.astype(dt)
for arg in [(m, v), (v, m), (m, m)]:
res = self.matmul(*arg)
assert_(res.dtype == dt)
# vector vector returns scalars
res = self.matmul(v, v)
assert_(type(res) is np.dtype(dt).type)
def test_vector_vector_values(self):
vec = np.array([1, 2])
tgt = 5
for dt in self.types[1:]:
v1 = vec.astype(dt)
res = self.matmul(v1, v1)
assert_equal(res, tgt)
# boolean type
vec = np.array([True, True], dtype='?')
res = self.matmul(vec, vec)
assert_equal(res, True)
def test_vector_matrix_values(self):
vec = np.array([1, 2])
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([7, 10])
tgt2 = np.stack([tgt1]*2, axis=0)
for dt in self.types[1:]:
v = vec.astype(dt)
m1 = mat1.astype(dt)
m2 = mat2.astype(dt)
res = self.matmul(v, m1)
assert_equal(res, tgt1)
res = self.matmul(v, m2)
assert_equal(res, tgt2)
# boolean type
vec = np.array([True, False])
mat1 = np.array([[True, False], [False, True]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([True, False])
tgt2 = np.stack([tgt1]*2, axis=0)
res = self.matmul(vec, mat1)
assert_equal(res, tgt1)
res = self.matmul(vec, mat2)
assert_equal(res, tgt2)
def test_matrix_vector_values(self):
vec = np.array([1, 2])
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([5, 11])
tgt2 = np.stack([tgt1]*2, axis=0)
for dt in self.types[1:]:
v = vec.astype(dt)
m1 = mat1.astype(dt)
m2 = mat2.astype(dt)
res = self.matmul(m1, v)
assert_equal(res, tgt1)
res = self.matmul(m2, v)
assert_equal(res, tgt2)
# boolean type
vec = np.array([True, False])
mat1 = np.array([[True, False], [False, True]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([True, False])
tgt2 = np.stack([tgt1]*2, axis=0)
res = self.matmul(vec, mat1)
assert_equal(res, tgt1)
res = self.matmul(vec, mat2)
assert_equal(res, tgt2)
def test_matrix_matrix_values(self):
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[1, 0], [1, 1]])
mat12 = np.stack([mat1, mat2], axis=0)
mat21 = np.stack([mat2, mat1], axis=0)
tgt11 = np.array([[7, 10], [15, 22]])
tgt12 = np.array([[3, 2], [7, 4]])
tgt21 = np.array([[1, 2], [4, 6]])
tgt12_21 = np.stack([tgt12, tgt21], axis=0)
tgt11_12 = np.stack((tgt11, tgt12), axis=0)
tgt11_21 = np.stack((tgt11, tgt21), axis=0)
for dt in self.types[1:]:
m1 = mat1.astype(dt)
m2 = mat2.astype(dt)
m12 = mat12.astype(dt)
m21 = mat21.astype(dt)
# matrix @ matrix
res = self.matmul(m1, m2)
assert_equal(res, tgt12)
res = self.matmul(m2, m1)
assert_equal(res, tgt21)
# stacked @ matrix
res = self.matmul(m12, m1)
assert_equal(res, tgt11_21)
# matrix @ stacked
res = self.matmul(m1, m12)
assert_equal(res, tgt11_12)
# stacked @ stacked
res = self.matmul(m12, m21)
assert_equal(res, tgt12_21)
# boolean type
m1 = np.array([[1, 1], [0, 0]], dtype=np.bool_)
m2 = np.array([[1, 0], [1, 1]], dtype=np.bool_)
m12 = np.stack([m1, m2], axis=0)
m21 = np.stack([m2, m1], axis=0)
tgt11 = m1
tgt12 = m1
tgt21 = np.array([[1, 1], [1, 1]], dtype=np.bool_)
tgt12_21 = np.stack([tgt12, tgt21], axis=0)
tgt11_12 = np.stack((tgt11, tgt12), axis=0)
tgt11_21 = np.stack((tgt11, tgt21), axis=0)
# matrix @ matrix
res = self.matmul(m1, m2)
assert_equal(res, tgt12)
res = self.matmul(m2, m1)
assert_equal(res, tgt21)
# stacked @ matrix
res = self.matmul(m12, m1)
assert_equal(res, tgt11_21)
# matrix @ stacked
res = self.matmul(m1, m12)
assert_equal(res, tgt11_12)
# stacked @ stacked
res = self.matmul(m12, m21)
assert_equal(res, tgt12_21)
def test_numpy_ufunc_override(self):
class A(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return "A"
class B(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return NotImplemented
a = A([1, 2])
b = B([1, 2])
c = np.ones(2)
assert_equal(self.matmul(a, b), "A")
assert_equal(self.matmul(b, a), "A")
assert_raises(TypeError, self.matmul, b, c)
class TestMatmul(MatmulCommon, TestCase):
matmul = np.matmul
def test_out_arg(self):
a = np.ones((2, 2), dtype=np.float)
b = np.ones((2, 2), dtype=np.float)
tgt = np.full((2,2), 2, dtype=np.float)
# test as positional argument
msg = "out positional argument"
out = np.zeros((2, 2), dtype=np.float)
self.matmul(a, b, out)
assert_array_equal(out, tgt, err_msg=msg)
# test as keyword argument
msg = "out keyword argument"
out = np.zeros((2, 2), dtype=np.float)
self.matmul(a, b, out=out)
assert_array_equal(out, tgt, err_msg=msg)
# test out with not allowed type cast (safe casting)
# einsum and cblas raise different error types, so
# use Exception.
msg = "out argument with illegal cast"
out = np.zeros((2, 2), dtype=np.int32)
assert_raises(Exception, self.matmul, a, b, out=out)
# skip following tests for now, cblas does not allow non-contiguous
# outputs and consistency with dot would require same type,
# dimensions, subtype, and c_contiguous.
# test out with allowed type cast
# msg = "out argument with allowed cast"
# out = np.zeros((2, 2), dtype=np.complex128)
# self.matmul(a, b, out=out)
# assert_array_equal(out, tgt, err_msg=msg)
# test out non-contiguous
# msg = "out argument with non-contiguous layout"
# c = np.zeros((2, 2, 2), dtype=np.float)
# self.matmul(a, b, out=c[..., 0])
# assert_array_equal(c, tgt, err_msg=msg)
if sys.version_info[:2] >= (3, 5):
class TestMatmulOperator(MatmulCommon, TestCase):
import operator
matmul = operator.matmul
def test_array_priority_override(self):
class A(object):
__array_priority__ = 1000
def __matmul__(self, other):
return "A"
def __rmatmul__(self, other):
return "A"
a = A()
b = np.ones(2)
assert_equal(self.matmul(a, b), "A")
assert_equal(self.matmul(b, a), "A")
def test_matmul_inplace():
# It would be nice to support in-place matmul eventually, but for now
# we don't have a working implementation, so better just to error out
# and nudge people to writing "a = a @ b".
a = np.eye(3)
b = np.eye(3)
assert_raises(TypeError, a.__imatmul__, b)
import operator
assert_raises(TypeError, operator.imatmul, a, b)
# we avoid writing the token `exec` so as not to crash python 2's
# parser
exec_ = getattr(builtins, "exec")
assert_raises(TypeError, exec_, "a @= b", globals(), locals())
class TestInner(TestCase):
def test_inner_scalar_and_matrix_of_objects(self):
# Ticket #4482
arr = np.matrix([1, 2], dtype=object)
desired = np.matrix([[3, 6]], dtype=object)
assert_equal(np.inner(arr, 3), desired)
assert_equal(np.inner(3, arr), desired)
def test_vecself(self):
# Ticket 844.
# Inner product of a vector with itself segfaults or give
# meaningless result
a = np.zeros(shape=(1, 80), dtype=np.float64)
p = np.inner(a, a)
assert_almost_equal(p, 0, decimal=14)
class TestSummarization(TestCase):
def test_1d(self):
A = np.arange(1001)
strA = '[ 0 1 2 ..., 998 999 1000]'
assert_(str(A) == strA)
reprA = 'array([ 0, 1, 2, ..., 998, 999, 1000])'
assert_(repr(A) == reprA)
def test_2d(self):
A = np.arange(1002).reshape(2, 501)
strA = '[[ 0 1 2 ..., 498 499 500]\n' \
' [ 501 502 503 ..., 999 1000 1001]]'
assert_(str(A) == strA)
reprA = 'array([[ 0, 1, 2, ..., 498, 499, 500],\n' \
' [ 501, 502, 503, ..., 999, 1000, 1001]])'
assert_(repr(A) == reprA)
class TestChoose(TestCase):
def setUp(self):
self.x = 2*np.ones((3,), dtype=int)
self.y = 3*np.ones((3,), dtype=int)
self.x2 = 2*np.ones((2, 3), dtype=int)
self.y2 = 3*np.ones((2, 3), dtype=int)
self.ind = [0, 0, 1]
def test_basic(self):
A = np.choose(self.ind, (self.x, self.y))
assert_equal(A, [2, 2, 3])
def test_broadcast1(self):
A = np.choose(self.ind, (self.x2, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
def test_broadcast2(self):
A = np.choose(self.ind, (self.x, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
# TODO: test for multidimensional
NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4}
class TestNeighborhoodIter(TestCase):
# Simple, 2d tests
def _test_simple2d(self, dt):
# Test zero and one padding for simple data type
x = np.array([[0, 1], [2, 3]], dtype=dt)
r = [np.array([[0, 0, 0], [0, 0, 1]], dtype=dt),
np.array([[0, 0, 0], [0, 1, 0]], dtype=dt),
np.array([[0, 0, 1], [0, 2, 3]], dtype=dt),
np.array([[0, 1, 0], [2, 3, 0]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0],
NEIGH_MODE['zero'])
assert_array_equal(l, r)
r = [np.array([[1, 1, 1], [1, 0, 1]], dtype=dt),
np.array([[1, 1, 1], [0, 1, 1]], dtype=dt),
np.array([[1, 0, 1], [1, 2, 3]], dtype=dt),
np.array([[0, 1, 1], [2, 3, 1]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0],
NEIGH_MODE['one'])
assert_array_equal(l, r)
r = [np.array([[4, 4, 4], [4, 0, 1]], dtype=dt),
np.array([[4, 4, 4], [0, 1, 4]], dtype=dt),
np.array([[4, 0, 1], [4, 2, 3]], dtype=dt),
np.array([[0, 1, 4], [2, 3, 4]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], 4,
NEIGH_MODE['constant'])
assert_array_equal(l, r)
def test_simple2d(self):
self._test_simple2d(np.float)
def test_simple2d_object(self):
self._test_simple2d(Decimal)
def _test_mirror2d(self, dt):
x = np.array([[0, 1], [2, 3]], dtype=dt)
r = [np.array([[0, 0, 1], [0, 0, 1]], dtype=dt),
np.array([[0, 1, 1], [0, 1, 1]], dtype=dt),
np.array([[0, 0, 1], [2, 2, 3]], dtype=dt),
np.array([[0, 1, 1], [2, 3, 3]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0],
NEIGH_MODE['mirror'])
assert_array_equal(l, r)
def test_mirror2d(self):
self._test_mirror2d(np.float)
def test_mirror2d_object(self):
self._test_mirror2d(Decimal)
# Simple, 1d tests
def _test_simple(self, dt):
# Test padding with constant values
x = np.linspace(1, 5, 5).astype(dt)
r = [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 0]]
l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['zero'])
assert_array_equal(l, r)
r = [[1, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 1]]
l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['one'])
assert_array_equal(l, r)
r = [[x[4], 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, x[4]]]
l = test_neighborhood_iterator(x, [-1, 1], x[4], NEIGH_MODE['constant'])
assert_array_equal(l, r)
def test_simple_float(self):
self._test_simple(np.float)
def test_simple_object(self):
self._test_simple(Decimal)
# Test mirror modes
def _test_mirror(self, dt):
x = np.linspace(1, 5, 5).astype(dt)
r = np.array([[2, 1, 1, 2, 3], [1, 1, 2, 3, 4], [1, 2, 3, 4, 5],
[2, 3, 4, 5, 5], [3, 4, 5, 5, 4]], dtype=dt)
l = test_neighborhood_iterator(x, [-2, 2], x[1], NEIGH_MODE['mirror'])
self.assertTrue([i.dtype == dt for i in l])
assert_array_equal(l, r)
def test_mirror(self):
self._test_mirror(np.float)
def test_mirror_object(self):
self._test_mirror(Decimal)
# Circular mode
def _test_circular(self, dt):
x = np.linspace(1, 5, 5).astype(dt)
r = np.array([[4, 5, 1, 2, 3], [5, 1, 2, 3, 4], [1, 2, 3, 4, 5],
[2, 3, 4, 5, 1], [3, 4, 5, 1, 2]], dtype=dt)
l = test_neighborhood_iterator(x, [-2, 2], x[0], NEIGH_MODE['circular'])
assert_array_equal(l, r)
def test_circular(self):
self._test_circular(np.float)
def test_circular_object(self):
self._test_circular(Decimal)
# Test stacking neighborhood iterators
class TestStackedNeighborhoodIter(TestCase):
# Simple, 1d test: stacking 2 constant-padded neigh iterators
def test_simple_const(self):
dt = np.float64
# Test zero and one padding for simple data type
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0], dtype=dt),
np.array([0], dtype=dt),
np.array([1], dtype=dt),
np.array([2], dtype=dt),
np.array([3], dtype=dt),
np.array([0], dtype=dt),
np.array([0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-2, 4], NEIGH_MODE['zero'],
[0, 0], NEIGH_MODE['zero'])
assert_array_equal(l, r)
r = [np.array([1, 0, 1], dtype=dt),
np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt),
np.array([3, 0, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-1, 1], NEIGH_MODE['one'])
assert_array_equal(l, r)
# 2nd simple, 1d test: stacking 2 neigh iterators, mixing const padding and
# mirror padding
def test_simple_mirror(self):
dt = np.float64
# Stacking zero on top of mirror
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 1, 1], dtype=dt),
np.array([1, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 3], dtype=dt),
np.array([3, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['mirror'],
[-1, 1], NEIGH_MODE['zero'])
assert_array_equal(l, r)
# Stacking mirror on top of zero
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 0, 0], dtype=dt),
np.array([0, 0, 1], dtype=dt),
np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 0], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 2nd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt),
np.array([3, 0, 0], dtype=dt),
np.array([0, 0, 3], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[0, 2], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 3rd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 0, 0, 1, 2], dtype=dt),
np.array([0, 0, 1, 2, 3], dtype=dt),
np.array([0, 1, 2, 3, 0], dtype=dt),
np.array([1, 2, 3, 0, 0], dtype=dt),
np.array([2, 3, 0, 0, 3], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 2], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# 3rd simple, 1d test: stacking 2 neigh iterators, mixing const padding and
# circular padding
def test_simple_circular(self):
dt = np.float64
# Stacking zero on top of mirror
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 3, 1], dtype=dt),
np.array([3, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 1], dtype=dt),
np.array([3, 1, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['circular'],
[-1, 1], NEIGH_MODE['zero'])
assert_array_equal(l, r)
# Stacking mirror on top of zero
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([3, 0, 0], dtype=dt),
np.array([0, 0, 1], dtype=dt),
np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 0], NEIGH_MODE['circular'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 2nd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt),
np.array([3, 0, 0], dtype=dt),
np.array([0, 0, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[0, 2], NEIGH_MODE['circular'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 3rd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([3, 0, 0, 1, 2], dtype=dt),
np.array([0, 0, 1, 2, 3], dtype=dt),
np.array([0, 1, 2, 3, 0], dtype=dt),
np.array([1, 2, 3, 0, 0], dtype=dt),
np.array([2, 3, 0, 0, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 2], NEIGH_MODE['circular'])
assert_array_equal(l, r)
# 4th simple, 1d test: stacking 2 neigh iterators, but with lower iterator
# being strictly within the array
def test_simple_strict_within(self):
dt = np.float64
# Stacking zero on top of zero, first neighborhood strictly inside the
# array
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 2, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'],
[-1, 2], NEIGH_MODE['zero'])
assert_array_equal(l, r)
# Stacking mirror on top of zero, first neighborhood strictly inside the
# array
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 2, 3, 3], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'],
[-1, 2], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# Stacking mirror on top of zero, first neighborhood strictly inside the
# array
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 2, 3, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'],
[-1, 2], NEIGH_MODE['circular'])
assert_array_equal(l, r)
class TestWarnings(object):
def test_complex_warning(self):
x = np.array([1, 2])
y = np.array([1-2j, 1+2j])
with warnings.catch_warnings():
warnings.simplefilter("error", np.ComplexWarning)
assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y)
assert_equal(x, [1, 2])
class TestMinScalarType(object):
def test_usigned_shortshort(self):
dt = np.min_scalar_type(2**8-1)
wanted = np.dtype('uint8')
assert_equal(wanted, dt)
def test_usigned_short(self):
dt = np.min_scalar_type(2**16-1)
wanted = np.dtype('uint16')
assert_equal(wanted, dt)
def test_usigned_int(self):
dt = np.min_scalar_type(2**32-1)
wanted = np.dtype('uint32')
assert_equal(wanted, dt)
def test_usigned_longlong(self):
dt = np.min_scalar_type(2**63-1)
wanted = np.dtype('uint64')
assert_equal(wanted, dt)
def test_object(self):
dt = np.min_scalar_type(2**64)
wanted = np.dtype('O')
assert_equal(wanted, dt)
if sys.version_info[:2] == (2, 6):
from numpy.core.multiarray import memorysimpleview as memoryview
from numpy.core._internal import _dtype_from_pep3118
class TestPEP3118Dtype(object):
def _check(self, spec, wanted):
dt = np.dtype(wanted)
if isinstance(wanted, list) and isinstance(wanted[-1], tuple):
if wanted[-1][0] == '':
names = list(dt.names)
names[-1] = ''
dt.names = tuple(names)
assert_equal(_dtype_from_pep3118(spec), dt,
err_msg="spec %r != dtype %r" % (spec, wanted))
def test_native_padding(self):
align = np.dtype('i').alignment
for j in range(8):
if j == 0:
s = 'bi'
else:
s = 'b%dxi' % j
self._check('@'+s, {'f0': ('i1', 0),
'f1': ('i', align*(1 + j//align))})
self._check('='+s, {'f0': ('i1', 0),
'f1': ('i', 1+j)})
def test_native_padding_2(self):
# Native padding should work also for structs and sub-arrays
self._check('x3T{xi}', {'f0': (({'f0': ('i', 4)}, (3,)), 4)})
self._check('^x3T{xi}', {'f0': (({'f0': ('i', 1)}, (3,)), 1)})
def test_trailing_padding(self):
# Trailing padding should be included, *and*, the item size
# should match the alignment if in aligned mode
align = np.dtype('i').alignment
def VV(n):
return 'V%d' % (align*(1 + (n-1)//align))
self._check('ix', [('f0', 'i'), ('', VV(1))])
self._check('ixx', [('f0', 'i'), ('', VV(2))])
self._check('ixxx', [('f0', 'i'), ('', VV(3))])
self._check('ixxxx', [('f0', 'i'), ('', VV(4))])
self._check('i7x', [('f0', 'i'), ('', VV(7))])
self._check('^ix', [('f0', 'i'), ('', 'V1')])
self._check('^ixx', [('f0', 'i'), ('', 'V2')])
self._check('^ixxx', [('f0', 'i'), ('', 'V3')])
self._check('^ixxxx', [('f0', 'i'), ('', 'V4')])
self._check('^i7x', [('f0', 'i'), ('', 'V7')])
def test_native_padding_3(self):
dt = np.dtype(
[('a', 'b'), ('b', 'i'),
('sub', np.dtype('b,i')), ('c', 'i')],
align=True)
self._check("T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxxi:c:}", dt)
dt = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'),
('e', 'b'), ('sub', np.dtype('b,i', align=True))])
self._check("T{b:a:=i:b:b:c:b:d:b:e:T{b:f0:xxxi:f1:}:sub:}", dt)
def test_padding_with_array_inside_struct(self):
dt = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b', (3,)),
('d', 'i')],
align=True)
self._check("T{b:a:xxxi:b:3b:c:xi:d:}", dt)
def test_byteorder_inside_struct(self):
# The byte order after @T{=i} should be '=', not '@'.
# Check this by noting the absence of native alignment.
self._check('@T{^i}xi', {'f0': ({'f0': ('i', 0)}, 0),
'f1': ('i', 5)})
def test_intra_padding(self):
# Natively aligned sub-arrays may require some internal padding
align = np.dtype('i').alignment
def VV(n):
return 'V%d' % (align*(1 + (n-1)//align))
self._check('(3)T{ix}', ({'f0': ('i', 0), '': (VV(1), 4)}, (3,)))
class TestNewBufferProtocol(object):
def _check_roundtrip(self, obj):
obj = np.asarray(obj)
x = memoryview(obj)
y = np.asarray(x)
y2 = np.array(x)
assert_(not y.flags.owndata)
assert_(y2.flags.owndata)
assert_equal(y.dtype, obj.dtype)
assert_equal(y.shape, obj.shape)
assert_array_equal(obj, y)
assert_equal(y2.dtype, obj.dtype)
assert_equal(y2.shape, obj.shape)
assert_array_equal(obj, y2)
def test_roundtrip(self):
x = np.array([1, 2, 3, 4, 5], dtype='i4')
self._check_roundtrip(x)
x = np.array([[1, 2], [3, 4]], dtype=np.float64)
self._check_roundtrip(x)
x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:]
self._check_roundtrip(x)
dt = [('a', 'b'),
('b', 'h'),
('c', 'i'),
('d', 'l'),
('dx', 'q'),
('e', 'B'),
('f', 'H'),
('g', 'I'),
('h', 'L'),
('hx', 'Q'),
('i', np.single),
('j', np.double),
('k', np.longdouble),
('ix', np.csingle),
('jx', np.cdouble),
('kx', np.clongdouble),
('l', 'S4'),
('m', 'U4'),
('n', 'V3'),
('o', '?'),
('p', np.half),
]
x = np.array(
[(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
asbytes('aaaa'), 'bbbb', asbytes('xxx'), True, 1.0)],
dtype=dt)
self._check_roundtrip(x)
x = np.array(([[1, 2], [3, 4]],), dtype=[('a', (int, (2, 2)))])
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='>i2')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='<i2')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='>i4')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='<i4')
self._check_roundtrip(x)
# check long long can be represented as non-native
x = np.array([1, 2, 3], dtype='>q')
self._check_roundtrip(x)
# Native-only data types can be passed through the buffer interface
# only in native byte order
if sys.byteorder == 'little':
x = np.array([1, 2, 3], dtype='>g')
assert_raises(ValueError, self._check_roundtrip, x)
x = np.array([1, 2, 3], dtype='<g')
self._check_roundtrip(x)
else:
x = np.array([1, 2, 3], dtype='>g')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='<g')
assert_raises(ValueError, self._check_roundtrip, x)
def test_roundtrip_half(self):
half_list = [
1.0,
-2.0,
6.5504 * 10**4, # (max half precision)
2**-14, # ~= 6.10352 * 10**-5 (minimum positive normal)
2**-24, # ~= 5.96046 * 10**-8 (minimum strictly positive subnormal)
0.0,
-0.0,
float('+inf'),
float('-inf'),
0.333251953125, # ~= 1/3
]
x = np.array(half_list, dtype='>e')
self._check_roundtrip(x)
x = np.array(half_list, dtype='<e')
self._check_roundtrip(x)
def test_roundtrip_single_types(self):
for typ in np.typeDict.values():
dtype = np.dtype(typ)
if dtype.char in 'Mm':
# datetimes cannot be used in buffers
continue
if dtype.char == 'V':
# skip void
continue
x = np.zeros(4, dtype=dtype)
self._check_roundtrip(x)
if dtype.char not in 'qQgG':
dt = dtype.newbyteorder('<')
x = np.zeros(4, dtype=dt)
self._check_roundtrip(x)
dt = dtype.newbyteorder('>')
x = np.zeros(4, dtype=dt)
self._check_roundtrip(x)
def test_roundtrip_scalar(self):
# Issue #4015.
self._check_roundtrip(0)
def test_export_simple_1d(self):
x = np.array([1, 2, 3, 4, 5], dtype='i')
y = memoryview(x)
assert_equal(y.format, 'i')
assert_equal(y.shape, (5,))
assert_equal(y.ndim, 1)
assert_equal(y.strides, (4,))
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 4)
def test_export_simple_nd(self):
x = np.array([[1, 2], [3, 4]], dtype=np.float64)
y = memoryview(x)
assert_equal(y.format, 'd')
assert_equal(y.shape, (2, 2))
assert_equal(y.ndim, 2)
assert_equal(y.strides, (16, 8))
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 8)
def test_export_discontiguous(self):
x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:]
y = memoryview(x)
assert_equal(y.format, 'f')
assert_equal(y.shape, (3, 3))
assert_equal(y.ndim, 2)
assert_equal(y.strides, (36, 4))
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 4)
def test_export_record(self):
dt = [('a', 'b'),
('b', 'h'),
('c', 'i'),
('d', 'l'),
('dx', 'q'),
('e', 'B'),
('f', 'H'),
('g', 'I'),
('h', 'L'),
('hx', 'Q'),
('i', np.single),
('j', np.double),
('k', np.longdouble),
('ix', np.csingle),
('jx', np.cdouble),
('kx', np.clongdouble),
('l', 'S4'),
('m', 'U4'),
('n', 'V3'),
('o', '?'),
('p', np.half),
]
x = np.array(
[(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
asbytes('aaaa'), 'bbbb', asbytes(' '), True, 1.0)],
dtype=dt)
y = memoryview(x)
assert_equal(y.shape, (1,))
assert_equal(y.ndim, 1)
assert_equal(y.suboffsets, EMPTY)
sz = sum([np.dtype(b).itemsize for a, b in dt])
if np.dtype('l').itemsize == 4:
assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:q:dx:B:e:@H:f:=I:g:L:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}')
else:
assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:q:dx:B:e:@H:f:=I:g:Q:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}')
# Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides
if not (np.ones(1).strides[0] == np.iinfo(np.intp).max):
assert_equal(y.strides, (sz,))
assert_equal(y.itemsize, sz)
def test_export_subarray(self):
x = np.array(([[1, 2], [3, 4]],), dtype=[('a', ('i', (2, 2)))])
y = memoryview(x)
assert_equal(y.format, 'T{(2,2)i:a:}')
assert_equal(y.shape, EMPTY)
assert_equal(y.ndim, 0)
assert_equal(y.strides, EMPTY)
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 16)
def test_export_endian(self):
x = np.array([1, 2, 3], dtype='>i')
y = memoryview(x)
if sys.byteorder == 'little':
assert_equal(y.format, '>i')
else:
assert_equal(y.format, 'i')
x = np.array([1, 2, 3], dtype='<i')
y = memoryview(x)
if sys.byteorder == 'little':
assert_equal(y.format, 'i')
else:
assert_equal(y.format, '<i')
def test_export_flags(self):
# Check SIMPLE flag, see also gh-3613 (exception should be BufferError)
assert_raises(ValueError, get_buffer_info, np.arange(5)[::2], ('SIMPLE',))
def test_padding(self):
for j in range(8):
x = np.array([(1,), (2,)], dtype={'f0': (int, j)})
self._check_roundtrip(x)
def test_reference_leak(self):
count_1 = sys.getrefcount(np.core._internal)
a = np.zeros(4)
b = memoryview(a)
c = np.asarray(b)
count_2 = sys.getrefcount(np.core._internal)
assert_equal(count_1, count_2)
del c # avoid pyflakes unused variable warning.
def test_padded_struct_array(self):
dt1 = np.dtype(
[('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')],
align=True)
x1 = np.arange(dt1.itemsize, dtype=np.int8).view(dt1)
self._check_roundtrip(x1)
dt2 = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')],
align=True)
x2 = np.arange(dt2.itemsize, dtype=np.int8).view(dt2)
self._check_roundtrip(x2)
dt3 = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'),
('e', 'b'), ('sub', np.dtype('b,i', align=True))])
x3 = np.arange(dt3.itemsize, dtype=np.int8).view(dt3)
self._check_roundtrip(x3)
def test_relaxed_strides(self):
# Test that relaxed strides are converted to non-relaxed
c = np.ones((1, 10, 10), dtype='i8')
# Check for NPY_RELAXED_STRIDES_CHECKING:
if np.ones((10, 1), order="C").flags.f_contiguous:
c.strides = (-1, 80, 8)
assert memoryview(c).strides == (800, 80, 8)
# Writing C-contiguous data to a BytesIO buffer should work
fd = io.BytesIO()
fd.write(c.data)
fortran = c.T
assert memoryview(fortran).strides == (8, 80, 800)
arr = np.ones((1, 10))
if arr.flags.f_contiguous:
shape, strides = get_buffer_info(arr, ['F_CONTIGUOUS'])
assert_(strides[0] == 8)
arr = np.ones((10, 1), order='F')
shape, strides = get_buffer_info(arr, ['C_CONTIGUOUS'])
assert_(strides[-1] == 8)
class TestArrayAttributeDeletion(object):
def test_multiarray_writable_attributes_deletion(self):
"""ticket #2046, should not seqfault, raise AttributeError"""
a = np.ones(2)
attr = ['shape', 'strides', 'data', 'dtype', 'real', 'imag', 'flat']
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_multiarray_not_writable_attributes_deletion(self):
a = np.ones(2)
attr = ["ndim", "flags", "itemsize", "size", "nbytes", "base",
"ctypes", "T", "__array_interface__", "__array_struct__",
"__array_priority__", "__array_finalize__"]
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_multiarray_flags_writable_attribute_deletion(self):
a = np.ones(2).flags
attr = ['updateifcopy', 'aligned', 'writeable']
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_multiarray_flags_not_writable_attribute_deletion(self):
a = np.ones(2).flags
attr = ["contiguous", "c_contiguous", "f_contiguous", "fortran",
"owndata", "fnc", "forc", "behaved", "carray", "farray",
"num"]
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_array_interface():
# Test scalar coercion within the array interface
class Foo(object):
def __init__(self, value):
self.value = value
self.iface = {'typestr': '=f8'}
def __float__(self):
return float(self.value)
@property
def __array_interface__(self):
return self.iface
f = Foo(0.5)
assert_equal(np.array(f), 0.5)
assert_equal(np.array([f]), [0.5])
assert_equal(np.array([f, f]), [0.5, 0.5])
assert_equal(np.array(f).dtype, np.dtype('=f8'))
# Test various shape definitions
f.iface['shape'] = ()
assert_equal(np.array(f), 0.5)
f.iface['shape'] = None
assert_raises(TypeError, np.array, f)
f.iface['shape'] = (1, 1)
assert_equal(np.array(f), [[0.5]])
f.iface['shape'] = (2,)
assert_raises(ValueError, np.array, f)
# test scalar with no shape
class ArrayLike(object):
array = np.array(1)
__array_interface__ = array.__array_interface__
assert_equal(np.array(ArrayLike()), 1)
def test_flat_element_deletion():
it = np.ones(3).flat
try:
del it[1]
del it[1:2]
except TypeError:
pass
except:
raise AssertionError
def test_scalar_element_deletion():
a = np.zeros(2, dtype=[('x', 'int'), ('y', 'int')])
assert_raises(ValueError, a[0].__delitem__, 'x')
class TestMemEventHook(TestCase):
def test_mem_seteventhook(self):
# The actual tests are within the C code in
# multiarray/multiarray_tests.c.src
test_pydatamem_seteventhook_start()
# force an allocation and free of a numpy array
# needs to be larger then limit of small memory cacher in ctors.c
a = np.zeros(1000)
del a
test_pydatamem_seteventhook_end()
class TestMapIter(TestCase):
def test_mapiter(self):
# The actual tests are within the C code in
# multiarray/multiarray_tests.c.src
a = np.arange(12).reshape((3, 4)).astype(float)
index = ([1, 1, 2, 0],
[0, 0, 2, 3])
vals = [50, 50, 30, 16]
test_inplace_increment(a, index, vals)
assert_equal(a, [[0.00, 1., 2.0, 19.],
[104., 5., 6.0, 7.0],
[8.00, 9., 40., 11.]])
b = np.arange(6).astype(float)
index = (np.array([1, 2, 0]),)
vals = [50, 4, 100.1]
test_inplace_increment(b, index, vals)
assert_equal(b, [100.1, 51., 6., 3., 4., 5.])
class TestAsCArray(TestCase):
def test_1darray(self):
array = np.arange(24, dtype=np.double)
from_c = test_as_c_array(array, 3)
assert_equal(array[3], from_c)
def test_2darray(self):
array = np.arange(24, dtype=np.double).reshape(3, 8)
from_c = test_as_c_array(array, 2, 4)
assert_equal(array[2, 4], from_c)
def test_3darray(self):
array = np.arange(24, dtype=np.double).reshape(2, 3, 4)
from_c = test_as_c_array(array, 1, 2, 3)
assert_equal(array[1, 2, 3], from_c)
class TestConversion(TestCase):
def test_array_scalar_relational_operation(self):
#All integer
for dt1 in np.typecodes['AllInteger']:
assert_(1 > np.array(0, dtype=dt1), "type %s failed" % (dt1,))
assert_(not 1 < np.array(0, dtype=dt1), "type %s failed" % (dt1,))
for dt2 in np.typecodes['AllInteger']:
assert_(np.array(1, dtype=dt1) > np.array(0, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1) < np.array(0, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
#Unsigned integers
for dt1 in 'BHILQP':
assert_(-1 < np.array(1, dtype=dt1), "type %s failed" % (dt1,))
assert_(not -1 > np.array(1, dtype=dt1), "type %s failed" % (dt1,))
assert_(-1 != np.array(1, dtype=dt1), "type %s failed" % (dt1,))
#unsigned vs signed
for dt2 in 'bhilqp':
assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(np.array(1, dtype=dt1) != np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
#Signed integers and floats
for dt1 in 'bhlqp' + np.typecodes['Float']:
assert_(1 > np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
assert_(not 1 < np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
assert_(-1 == np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
for dt2 in 'bhlqp' + np.typecodes['Float']:
assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(np.array(-1, dtype=dt1) == np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
class TestWhere(TestCase):
def test_basic(self):
dts = [np.bool, np.int16, np.int32, np.int64, np.double, np.complex128,
np.longdouble, np.clongdouble]
for dt in dts:
c = np.ones(53, dtype=np.bool)
assert_equal(np.where( c, dt(0), dt(1)), dt(0))
assert_equal(np.where(~c, dt(0), dt(1)), dt(1))
assert_equal(np.where(True, dt(0), dt(1)), dt(0))
assert_equal(np.where(False, dt(0), dt(1)), dt(1))
d = np.ones_like(c).astype(dt)
e = np.zeros_like(d)
r = d.astype(dt)
c[7] = False
r[7] = e[7]
assert_equal(np.where(c, e, e), e)
assert_equal(np.where(c, d, e), r)
assert_equal(np.where(c, d, e[0]), r)
assert_equal(np.where(c, d[0], e), r)
assert_equal(np.where(c[::2], d[::2], e[::2]), r[::2])
assert_equal(np.where(c[1::2], d[1::2], e[1::2]), r[1::2])
assert_equal(np.where(c[::3], d[::3], e[::3]), r[::3])
assert_equal(np.where(c[1::3], d[1::3], e[1::3]), r[1::3])
assert_equal(np.where(c[::-2], d[::-2], e[::-2]), r[::-2])
assert_equal(np.where(c[::-3], d[::-3], e[::-3]), r[::-3])
assert_equal(np.where(c[1::-3], d[1::-3], e[1::-3]), r[1::-3])
def test_exotic(self):
# object
assert_array_equal(np.where(True, None, None), np.array(None))
# zero sized
m = np.array([], dtype=bool).reshape(0, 3)
b = np.array([], dtype=np.float64).reshape(0, 3)
assert_array_equal(np.where(m, 0, b), np.array([]).reshape(0, 3))
# object cast
d = np.array([-1.34, -0.16, -0.54, -0.31, -0.08, -0.95, 0.000, 0.313,
0.547, -0.18, 0.876, 0.236, 1.969, 0.310, 0.699, 1.013,
1.267, 0.229, -1.39, 0.487])
nan = float('NaN')
e = np.array(['5z', '0l', nan, 'Wz', nan, nan, 'Xq', 'cs', nan, nan,
'QN', nan, nan, 'Fd', nan, nan, 'kp', nan, '36', 'i1'],
dtype=object)
m = np.array([0,0,1,0,1,1,0,0,1,1,0,1,1,0,1,1,0,1,0,0], dtype=bool)
r = e[:]
r[np.where(m)] = d[np.where(m)]
assert_array_equal(np.where(m, d, e), r)
r = e[:]
r[np.where(~m)] = d[np.where(~m)]
assert_array_equal(np.where(m, e, d), r)
assert_array_equal(np.where(m, e, e), e)
# minimal dtype result with NaN scalar (e.g required by pandas)
d = np.array([1., 2.], dtype=np.float32)
e = float('NaN')
assert_equal(np.where(True, d, e).dtype, np.float32)
e = float('Infinity')
assert_equal(np.where(True, d, e).dtype, np.float32)
e = float('-Infinity')
assert_equal(np.where(True, d, e).dtype, np.float32)
# also check upcast
e = float(1e150)
assert_equal(np.where(True, d, e).dtype, np.float64)
def test_ndim(self):
c = [True, False]
a = np.zeros((2, 25))
b = np.ones((2, 25))
r = np.where(np.array(c)[:,np.newaxis], a, b)
assert_array_equal(r[0], a[0])
assert_array_equal(r[1], b[0])
a = a.T
b = b.T
r = np.where(c, a, b)
assert_array_equal(r[:,0], a[:,0])
assert_array_equal(r[:,1], b[:,0])
def test_dtype_mix(self):
c = np.array([False, True, False, False, False, False, True, False,
False, False, True, False])
a = np.uint32(1)
b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.],
dtype=np.float64)
r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.],
dtype=np.float64)
assert_equal(np.where(c, a, b), r)
a = a.astype(np.float32)
b = b.astype(np.int64)
assert_equal(np.where(c, a, b), r)
# non bool mask
c = c.astype(np.int)
c[c != 0] = 34242324
assert_equal(np.where(c, a, b), r)
# invert
tmpmask = c != 0
c[c == 0] = 41247212
c[tmpmask] = 0
assert_equal(np.where(c, b, a), r)
def test_foreign(self):
c = np.array([False, True, False, False, False, False, True, False,
False, False, True, False])
r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.],
dtype=np.float64)
a = np.ones(1, dtype='>i4')
b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.],
dtype=np.float64)
assert_equal(np.where(c, a, b), r)
b = b.astype('>f8')
assert_equal(np.where(c, a, b), r)
a = a.astype('<i4')
assert_equal(np.where(c, a, b), r)
c = c.astype('>i4')
assert_equal(np.where(c, a, b), r)
def test_error(self):
c = [True, True]
a = np.ones((4, 5))
b = np.ones((5, 5))
assert_raises(ValueError, np.where, c, a, a)
assert_raises(ValueError, np.where, c[0], a, b)
def test_string(self):
# gh-4778 check strings are properly filled with nulls
a = np.array("abc")
b = np.array("x" * 753)
assert_equal(np.where(True, a, b), "abc")
assert_equal(np.where(False, b, a), "abc")
# check native datatype sized strings
a = np.array("abcd")
b = np.array("x" * 8)
assert_equal(np.where(True, a, b), "abcd")
assert_equal(np.where(False, b, a), "abcd")
class TestSizeOf(TestCase):
def test_empty_array(self):
x = np.array([])
assert_(sys.getsizeof(x) > 0)
def check_array(self, dtype):
elem_size = dtype(0).itemsize
for length in [10, 50, 100, 500]:
x = np.arange(length, dtype=dtype)
assert_(sys.getsizeof(x) > length * elem_size)
def test_array_int32(self):
self.check_array(np.int32)
def test_array_int64(self):
self.check_array(np.int64)
def test_array_float32(self):
self.check_array(np.float32)
def test_array_float64(self):
self.check_array(np.float64)
def test_view(self):
d = np.ones(100)
assert_(sys.getsizeof(d[...]) < sys.getsizeof(d))
def test_reshape(self):
d = np.ones(100)
assert_(sys.getsizeof(d) < sys.getsizeof(d.reshape(100, 1, 1).copy()))
def test_resize(self):
d = np.ones(100)
old = sys.getsizeof(d)
d.resize(50)
assert_(old > sys.getsizeof(d))
d.resize(150)
assert_(old < sys.getsizeof(d))
def test_error(self):
d = np.ones(100)
assert_raises(TypeError, d.__sizeof__, "a")
class TestHashing(TestCase):
def test_collections_hashable(self):
x = np.array([])
self.assertFalse(isinstance(x, collections.Hashable))
from numpy.core._internal import _view_is_safe
class TestObjViewSafetyFuncs(TestCase):
def test_view_safety(self):
psize = np.dtype('p').itemsize
# creates dtype but with extra character code - for missing 'p' fields
def mtype(s):
n, offset, fields = 0, 0, []
for c in s.split(','): # subarrays won't work
if c != '-':
fields.append(('f{0}'.format(n), c, offset))
n += 1
offset += np.dtype(c).itemsize if c != '-' else psize
names, formats, offsets = zip(*fields)
return np.dtype({'names': names, 'formats': formats,
'offsets': offsets, 'itemsize': offset})
# test nonequal itemsizes with objects:
# these should succeed:
_view_is_safe(np.dtype('O,p,O,p'), np.dtype('O,p,O,p,O,p'))
_view_is_safe(np.dtype('O,O'), np.dtype('O,O,O'))
# these should fail:
assert_raises(TypeError, _view_is_safe, np.dtype('O,O,p'), np.dtype('O,O'))
assert_raises(TypeError, _view_is_safe, np.dtype('O,O,p'), np.dtype('O,p'))
assert_raises(TypeError, _view_is_safe, np.dtype('O,O,p'), np.dtype('p,O'))
# test nonequal itemsizes with missing fields:
# these should succeed:
_view_is_safe(mtype('-,p,-,p'), mtype('-,p,-,p,-,p'))
_view_is_safe(np.dtype('p,p'), np.dtype('p,p,p'))
# these should fail:
assert_raises(TypeError, _view_is_safe, mtype('p,p,-'), mtype('p,p'))
assert_raises(TypeError, _view_is_safe, mtype('p,p,-'), mtype('p,-'))
assert_raises(TypeError, _view_is_safe, mtype('p,p,-'), mtype('-,p'))
# scans through positions at which we can view a type
def scanView(d1, otype):
goodpos = []
for shift in range(d1.itemsize - np.dtype(otype).itemsize+1):
d2 = np.dtype({'names': ['f0'], 'formats': [otype],
'offsets': [shift], 'itemsize': d1.itemsize})
try:
_view_is_safe(d1, d2)
except TypeError:
pass
else:
goodpos.append(shift)
return goodpos
# test partial overlap with object field
assert_equal(scanView(np.dtype('p,O,p,p,O,O'), 'p'),
[0] + list(range(2*psize, 3*psize+1)))
assert_equal(scanView(np.dtype('p,O,p,p,O,O'), 'O'),
[psize, 4*psize, 5*psize])
# test partial overlap with missing field
assert_equal(scanView(mtype('p,-,p,p,-,-'), 'p'),
[0] + list(range(2*psize, 3*psize+1)))
# test nested structures with objects:
nestedO = np.dtype([('f0', 'p'), ('f1', 'p,O,p')])
assert_equal(scanView(nestedO, 'p'), list(range(psize+1)) + [3*psize])
assert_equal(scanView(nestedO, 'O'), [2*psize])
# test nested structures with missing fields:
nestedM = np.dtype([('f0', 'p'), ('f1', mtype('p,-,p'))])
assert_equal(scanView(nestedM, 'p'), list(range(psize+1)) + [3*psize])
# test subarrays with objects
subarrayO = np.dtype('p,(2,3)O,p')
assert_equal(scanView(subarrayO, 'p'), [0, 7*psize])
assert_equal(scanView(subarrayO, 'O'),
list(range(psize, 6*psize+1, psize)))
#test dtype with overlapping fields
overlapped = np.dtype({'names': ['f0', 'f1', 'f2', 'f3'],
'formats': ['p', 'p', 'p', 'p'],
'offsets': [0, 1, 3*psize-1, 3*psize],
'itemsize': 4*psize})
assert_equal(scanView(overlapped, 'p'), [0, 1, 3*psize-1, 3*psize])
class TestArrayPriority(TestCase):
# This will go away when __array_priority__ is settled, meanwhile
# it serves to check unintended changes.
op = operator
binary_ops = [
op.pow, op.add, op.sub, op.mul, op.floordiv, op.truediv, op.mod,
op.and_, op.or_, op.xor, op.lshift, op.rshift, op.mod, op.gt,
op.ge, op.lt, op.le, op.ne, op.eq
]
if sys.version_info[0] < 3:
binary_ops.append(op.div)
class Foo(np.ndarray):
__array_priority__ = 100.
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
class Bar(np.ndarray):
__array_priority__ = 101.
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
class Other(object):
__array_priority__ = 1000.
def _all(self, other):
return self.__class__()
__add__ = __radd__ = _all
__sub__ = __rsub__ = _all
__mul__ = __rmul__ = _all
__pow__ = __rpow__ = _all
__div__ = __rdiv__ = _all
__mod__ = __rmod__ = _all
__truediv__ = __rtruediv__ = _all
__floordiv__ = __rfloordiv__ = _all
__and__ = __rand__ = _all
__xor__ = __rxor__ = _all
__or__ = __ror__ = _all
__lshift__ = __rlshift__ = _all
__rshift__ = __rrshift__ = _all
__eq__ = _all
__ne__ = _all
__gt__ = _all
__ge__ = _all
__lt__ = _all
__le__ = _all
def test_ndarray_subclass(self):
a = np.array([1, 2])
b = self.Bar([1, 2])
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Bar), msg)
assert_(isinstance(f(b, a), self.Bar), msg)
def test_ndarray_other(self):
a = np.array([1, 2])
b = self.Other()
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Other), msg)
assert_(isinstance(f(b, a), self.Other), msg)
def test_subclass_subclass(self):
a = self.Foo([1, 2])
b = self.Bar([1, 2])
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Bar), msg)
assert_(isinstance(f(b, a), self.Bar), msg)
def test_subclass_other(self):
a = self.Foo([1, 2])
b = self.Other()
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Other), msg)
assert_(isinstance(f(b, a), self.Other), msg)
class TestBytestringArrayNonzero(TestCase):
def test_empty_bstring_array_is_falsey(self):
self.assertFalse(np.array([''], dtype=np.str))
def test_whitespace_bstring_array_is_falsey(self):
a = np.array(['spam'], dtype=np.str)
a[0] = ' \0\0'
self.assertFalse(a)
def test_all_null_bstring_array_is_falsey(self):
a = np.array(['spam'], dtype=np.str)
a[0] = '\0\0\0\0'
self.assertFalse(a)
def test_null_inside_bstring_array_is_truthy(self):
a = np.array(['spam'], dtype=np.str)
a[0] = ' \0 \0'
self.assertTrue(a)
class TestUnicodeArrayNonzero(TestCase):
def test_empty_ustring_array_is_falsey(self):
self.assertFalse(np.array([''], dtype=np.unicode))
def test_whitespace_ustring_array_is_falsey(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = ' \0\0'
self.assertFalse(a)
def test_all_null_ustring_array_is_falsey(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = '\0\0\0\0'
self.assertFalse(a)
def test_null_inside_ustring_array_is_truthy(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = ' \0 \0'
self.assertTrue(a)
if __name__ == "__main__":
run_module_suite()
| MichaelAquilina/numpy | numpy/core/tests/test_multiarray.py | Python | bsd-3-clause | 220,691 |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef mitkVtkPropRenderer_h
#define mitkVtkPropRenderer_h
#include "mitkBaseRenderer.h"
#include <MitkCoreExports.h>
#include <itkCommand.h>
#include <mitkDataStorage.h>
#include <mitkRenderingManager.h>
#include <map>
#include <utility>
class vtkRenderWindow;
class vtkLight;
class vtkLightKit;
class vtkWorldPointPicker;
class vtkPointPicker;
class vtkCellPicker;
class vtkTextActor;
class vtkTextProperty;
class vtkAssemblyPath;
#include <vtkAssemblyPaths.h>
#include <vtkSmartPointer.h>
namespace mitk
{
class Mapper;
/*!
\brief VtkPropRenderer
VtkPropRenderer organizes the MITK rendering process. The MITK rendering process is completely integrated into the VTK
rendering pipeline.
The vtkMitkRenderProp is a custom vtkProp derived class, which implements the rendering interface between MITK and
VTK.
It redirects render() calls to the VtkPropRenderer, which is responsible for rendering of the datatreenodes.
VtkPropRenderer replaces the old OpenGLRenderer.
\sa rendering
\ingroup rendering
*/
class MITKCORE_EXPORT VtkPropRenderer : public BaseRenderer
{
// Workaround for Displaylistbug
private:
bool didCount;
void checkState();
// Workaround END
public:
mitkClassMacro(VtkPropRenderer, BaseRenderer);
mitkNewMacro3Param(VtkPropRenderer, const char *, vtkRenderWindow *, mitk::RenderingManager *);
mitkNewMacro4Param(VtkPropRenderer,
const char *,
vtkRenderWindow *,
mitk::RenderingManager *,
mitk::BaseRenderer::RenderingMode::Type);
typedef std::map<int, Mapper *> MappersMapType;
// Render - called by vtkMitkRenderProp, returns the number of props rendered
enum RenderType
{
Opaque,
Translucent,
Overlay,
Volumetric
};
int Render(RenderType type);
/** \brief This methods contains all method neceassary before a VTK Render() call */
virtual void PrepareRender();
// Active current renderwindow
virtual void MakeCurrent();
virtual void SetDataStorage(
mitk::DataStorage *storage) override; ///< set the datastorage that will be used for rendering
virtual void InitRenderer(vtkRenderWindow *renderwindow) override;
virtual void Update(mitk::DataNode *datatreenode);
virtual void SetMapperID(const MapperSlotId mapperId) override;
// Size
virtual void InitSize(int w, int h) override;
virtual void Resize(int w, int h) override;
// Picking
enum PickingMode
{
WorldPointPicking,
PointPicking,
CellPicking
};
/** \brief Set the picking mode.
This method is used to set the picking mode for 3D object picking. The user can select one of
the three options WorldPointPicking, PointPicking and CellPicking. The first option uses the zBuffer
from graphics rendering, the second uses the 3D points from the closest surface mesh, and the third
option uses the cells of that mesh. The last option is the slowest, the first one the fastest.
However, the first option cannot use transparent data object and the tolerance of the picked position
to the selected point should be considered. PointPicking also need a tolerance around the picking
position to select the closest point in the mesh. The CellPicker performs very well, if the
foreground surface part (i.e. the surfacepart that is closest to the scene's cameras) needs to be
picked. */
itkSetEnumMacro(PickingMode, PickingMode);
itkGetEnumMacro(PickingMode, PickingMode);
virtual void PickWorldPoint(const Point2D &displayPoint, Point3D &worldPoint) const override;
virtual mitk::DataNode *PickObject(const Point2D &displayPosition, Point3D &worldPosition) const override;
/**
* @brief WriteSimpleText Write a text in a renderwindow.
*
* Writes some 2D text as overlay. Function returns an unique int Text_ID for each call, which can be used via the
GetTextLabelProperty(int text_id) function
in order to get a vtkTextProperty. This property enables the setup of font, font size, etc.
*
* @deprecatedSince{2015_05} Please use mitkTextOverlay2D instead.
* See mitkTextOverlay2DRenderingTest for an example.
*/
DEPRECATED(int WriteSimpleText(std::string text,
double posX,
double posY,
double color1 = 0.0,
double color2 = 1.0,
double color3 = 0.0,
float opacity = 1.0));
/**
* @brief CGetTextLabelProperty an be used in order to get a vtkTextProperty for
* a specific text_id. This property enables the setup of font, font size, etc.
* @param text_id the id of the text property.
* @deprecatedSince{2015_05} Please use mitkTextOverlay2D instead.
* See mitkTextOverlay2DRenderingTest for an example.
*/
DEPRECATED(vtkTextProperty *GetTextLabelProperty(int text_id));
/** This method calculates the bounds of the DataStorage (if it contains any
* valid data), creates a geometry from these bounds and sets it as world
* geometry of the renderer.
*
* Call this method to re-initialize the renderer to the current DataStorage
* (e.g. after loading an additional dataset), to ensure that the view is
* aligned correctly.
*/
virtual bool SetWorldGeometryToDataStorageBounds() override;
/**
* \brief Used by vtkPointPicker/vtkPicker.
* This will query a list of all objects in MITK and provide every vtk based mapper to the picker.
*/
void InitPathTraversal();
/**
* \brief Used by vtkPointPicker/vtkPicker.
* This will query a list of all objects in MITK and provide every vtk based mapper to the picker.
*/
vtkAssemblyPath *GetNextPath();
int GetNumberOfPaths();
const vtkWorldPointPicker *GetWorldPointPicker() const;
const vtkPointPicker *GetPointPicker() const;
const vtkCellPicker *GetCellPicker() const;
/**
* \brief Release vtk-based graphics resources. Called by
* vtkMitkRenderProp::ReleaseGraphicsResources.
*/
virtual void ReleaseGraphicsResources(vtkWindow *renWin);
MappersMapType GetMappersMap() const;
static bool useImmediateModeRendering();
protected:
VtkPropRenderer(
const char *name = "VtkPropRenderer",
vtkRenderWindow *renWin = nullptr,
mitk::RenderingManager *rm = nullptr,
mitk::BaseRenderer::RenderingMode::Type renderingMode = mitk::BaseRenderer::RenderingMode::Standard);
virtual ~VtkPropRenderer();
virtual void Update() override;
static void RenderingCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata);
virtual void UpdatePaths(); // apply transformations and properties recursively
private:
vtkSmartPointer<vtkAssemblyPaths> m_Paths;
vtkTimeStamp m_PathTime;
// prepare all mitk::mappers for rendering
void PrepareMapperQueue();
/** \brief Set parallel projection, remove the interactor and the lights of VTK. */
bool Initialize2DvtkCamera();
bool m_InitNeeded;
bool m_ResizeNeeded;
MapperSlotId m_CameraInitializedForMapperID;
// Picking
vtkWorldPointPicker *m_WorldPointPicker;
vtkPointPicker *m_PointPicker;
vtkCellPicker *m_CellPicker;
PickingMode m_PickingMode;
// Explicit use of SmartPointer to avoid circular #includes
itk::SmartPointer<mitk::Mapper> m_CurrentWorldPlaneGeometryMapper;
vtkLightKit *m_LightKit;
// sorted list of mappers
MappersMapType m_MappersMap;
// rendering of text
vtkRenderer *m_TextRenderer;
typedef std::map<unsigned int, vtkTextActor *> TextMapType;
TextMapType m_TextCollection;
};
} // namespace mitk
#endif /* mitkVtkPropRenderer_h */
| iwegner/MITK | Modules/Core/include/mitkVtkPropRenderer.h | C | bsd-3-clause | 8,434 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.